class CWPropertiesForm(SystemCWPropertiesForm): """user's preferences properties edition form""" __regid__ = 'propertiesform' __select__ = ((none_rset() & match_user_groups('users', 'managers')) | (one_line_rset() & match_user_groups('users') & logged_user_in_rset()) | (one_line_rset() & match_user_groups('managers') & is_instance('CWUser'))) title = _('user preferences') @property def user(self): if self.cw_rset is None: return self._cw.user return self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0) @property @cached def cwprops_rset(self): return self._cw.execute( 'Any P,K,V WHERE P is CWProperty, P pkey K, P value V,' 'P for_user U, U eid %(x)s', {'x': self.user.eid}) def form_row(self, form, key, splitlabel): subform = super(CWPropertiesForm, self).form_row(form, key, splitlabel) # if user is in the managers group and the property is being created, # we have to set for_user explicitly if not subform.edited_entity.has_eid() and self.user.matching_groups( 'managers'): subform.add_hidden('for_user', self.user.eid, eidparam=True, role='subject') return subform
class InGroupHook(hook.Hook): """ Set moderators rights when they administrate groups through the 'in_group' relation. """ __regid__ = "in-group-hook" __select__ = (hook.Hook.__select__ & hook.match_rtype("in_group") & ~match_user_groups("managers")) events = ("before_add_relation", "before_delete_relation") def __call__(self): """ Before an 'in_group' relation deletion or addition, check the assocaited group name: can't modifiy managers, users, guests and moderators group associated unless you are administrator. """ parent = self._cw.entity_from_eid(self.eidto) child = self._cw.entity_from_eid(self.eidfrom) group_name = parent.name if child.firstname is None or child.surname is None: user_name = child.login else: user_name = child.firstname + " " + child.surname if group_name in self._cw.vreg.config.get("restricted-groups", []): raise ConfigurationError( "You do not have sufficient permissions to administrate '%s' " "in the '%s' group." % (user_name, group_name))
class StatsService(Service): """Return a dictionary containing some statistics about the repository resources usage. """ __regid__ = 'repo_stats' __select__ = match_user_groups('managers', 'users') def call(self): repo = self._cw.repo # Service are repo side only. results = {} querier = repo.querier source = repo.system_source for size, maxsize, hits, misses, title in ( (len(querier.rql_cache), repo.config['rql-cache-size'], querier.rql_cache.cache_hit, querier.rql_cache.cache_miss, 'rqlt_st'), (len(source._cache), repo.config['rql-cache-size'], source.cache_hit, source.cache_miss, 'sql'), ): results['%s_cache_size' % title] = { 'size': size, 'maxsize': maxsize } results['%s_cache_hit' % title] = hits results['%s_cache_miss' % title] = misses results['%s_cache_hit_percent' % title] = (hits * 100) / (hits + misses) results['type_cache_size'] = len(repo._type_cache) results['sql_no_cache'] = repo.system_source.no_cache results['nb_active_threads'] = threading.activeCount() results['available_cnxsets'] = repo.cnxsets.qsize() results['threads'] = [t.name for t in threading.enumerate()] return results
class GcStatsService(Service): """Return a dictionary containing some statistics about the repository resources usage. """ __regid__ = 'repo_gc_stats' __select__ = match_user_groups('managers') def call(self, nmax=20): """Return a dictionary containing some statistics about the repository memory usage. nmax is the max number of (most) referenced object returned as the 'referenced' result """ from cubicweb._gcdebug import gc_info from cubicweb.appobject import AppObject from cubicweb.rset import ResultSet from cubicweb.web.request import CubicWebRequestBase from rql.stmts import Union lookupclasses = (AppObject, Union, ResultSet, CubicWebRequestBase) results = {} counters, ocounters, garbage = gc_info(lookupclasses, viewreferrersclasses=()) values = sorted(counters.items(), key=lambda x: x[1], reverse=True) results['lookupclasses'] = values values = sorted(ocounters.items(), key=lambda x: x[1], reverse=True)[:nmax] results['referenced'] = values results['unreachable'] = garbage return results
class SCHIIRDORUsersTable(EntityTableView): """ Display a table with the user information to be managed. """ __regid__ = "schiirdor.users-table" __select__ = (is_instance("CWUser") & match_user_groups("managers", "moderators")) columns = [ "user", "in_state", "firstname", "surname", "in_group", "primary_email", "cw_source" ] finalvid = "editable-final" column_renderers = { "user": EntityTableColRenderer(renderfunc=lambda w, x: w(x.login), sortfunc=lambda x: x.login), "in_state": EntityTableColRenderer( renderfunc=lambda w, x: w( x.cw_adapt_to("IWorkflowable").printable_state), sortfunc=lambda x: x.cw_adapt_to("IWorkflowable").printable_state), "in_group": EntityTableColRenderer(renderfunc=lambda w, x: x.view( "reledit", rtype="in_group", role="subject", w=w)), "primary_email": EntityTableColRenderer(renderfunc=lambda w, x: w( x.primary_email and x.primary_email[0].display_address() or u""), sortfunc=lambda x: x.primary_email and x. primary_email[0].display_address() or u""), "cw_source": EntityTableColRenderer(renderfunc=lambda w, x: w(x.cw_source[0].name), sortfunc=lambda x: x.cw_source[0].name) }
class RegistryView(StartupView): """display vregistry content""" __regid__ = 'registry' __select__ = StartupView.__select__ & match_user_groups('managers') title = _('registry') cache_max_age = 0 def call(self, **kwargs): self.w(u'<h2>%s</h2>' % self._cw._("Registry's content")) keys = sorted(self._cw.vreg) url = xml_escape(self._cw.url()) self.w(u'<p>%s</p>\n' % ' - '.join('<a href="%s#%s">%s</a>' % (url, key, key) for key in keys)) for key in keys: if key in ('boxes', 'contentnavigation'): # those are bw compat registries continue self.w(u'<h3 id="%s">%s</h3>' % (key, key)) if self._cw.vreg[key]: values = sorted(self._cw.vreg[key].items()) self.wview('pyvaltable', pyvalue=[(key, xml_escape(repr(val))) for key, val in values]) else: self.w(u'<p>Empty</p>\n')
class ManagersAction(action.Action): __abstract__ = True __select__ = match_user_groups('managers') category = 'siteactions' def url(self): return self._cw.build_url(self.__regid__)
class TestService(Service): __regid__ = 'test_service' __select__ = Service.__select__ & match_user_groups('managers') passed_here = [] def call(self, msg): self.passed_here.append(msg) return 'babar'
class CWGroupsManagementView(StartupView): __regid__ = 'cw.groups-management' __select__ = StartupView.__select__ & match_user_groups('managers') cache_max_age = 0 # disable caching rql = ('Any G,GN ORDERBY GN WHERE G is CWGroup, G name GN, NOT G name "owners"') def call(self, **kwargs): self.w(add_etype_button(self._cw, 'CWGroup')) self.w(u'<div class="clear"></div>') self.wview('cw.groups-table', self._cw.execute(self.rql))
class SCHIIRDORAdminUsersTable(EntityTableView): """ Display a table with the users information to be managed. """ __regid__ = "shiirdor.admin-users-table" __select__ = is_instance("CWUser") & match_user_groups("managers") columns = ["user"] column_renderers = { "user": MainEntityColRenderer(), }
class UserPreferencesEntityAction(action.Action): __regid__ = 'prefs' __select__ = (one_line_rset() & is_instance('CWUser') & match_user_groups('owners', 'managers')) title = _('preferences') category = 'mainactions' def url(self): user = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0) return user.absolute_url(vid='propertiesform')
class UsersAndGroupsManagementView(tabs.TabsMixin, StartupView): __regid__ = 'cw.users-and-groups-management' __select__ = StartupView.__select__ & match_user_groups('managers') title = _('Users and groups management') tabs = [_('cw.users-management'), _('cw.groups-management')] default_tab = 'cw.users-management' def call(self, **kwargs): """The default view representing the instance's management""" self.w(u'<h1>%s</h1>' % self._cw._(self.title)) self.render_tabs(self.tabs, self.default_tab)
class AdminGroupButton(HeaderComponent): """ Build a create group button displayed in the header. Only the managers have accessed to this functionality. """ __regid__ = "admin-status" __select__ = match_user_groups("managers") & authenticated_user() context = "header-right" order = 4 def attributes(self): return (self._cw.build_url("view", vid="shiirdor.groups-management"), "Create groups", "fa-plus-square")
class ManagePermissionsAction(action.Action): __regid__ = 'managepermission' __select__ = (action.Action.__select__ & one_line_rset() & non_final_entity() & match_user_groups('managers')) title = _('manage permissions') category = 'moreactions' order = 15 def url(self): return self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0).absolute_url(vid='security')
class CondorRemoveController(Controller): __regid__ = 'do_condor_remove' __select__ = Controller.__select__ & match_user_groups( CondorJobView.condor_manager_groups) def publish(self, rset=None): job_id = self._cw.form['condor_job_id'] schedd_name = self._cw.form['condor_schedd_name'] errcode, output = remove(self._cw.vreg.config, schedd_name, job_id) raise Redirect( self._cw.build_url(vid='condor_jobs', __message=xml_escape(output.strip())))
class SourceSynchronizationService(Service): """Force synchronization of a datafeed source. Actual synchronization is done asynchronously, this will simply create and return the entity which will hold the import log. """ __regid__ = 'source-sync' __select__ = Service.__select__ & match_user_groups('managers') def call(self, source_eid): source = self._cw.repo.source_by_eid(source_eid) result = source.pull_data(self._cw, force=True, sync=False) return result['import_log_eid']
class AdminImportButton(HeaderComponent): """ Build an importation button displayed in the header. Only the managers have accessed to this functionality. """ __regid__ = "admin-import" __select__ = match_user_groups("managers") & authenticated_user() context = "header-right" order = 5 def attributes(self): return (self._cw.build_url("view", vid="shiirdor.users-groups-import"), "Import users & groups", "fa-cloud-download")
class CWSourceSyncAction(action.Action): __regid__ = 'cw.source-sync' __select__ = (action.Action.__select__ & match_user_groups('managers') & one_line_rset() & is_instance('CWSource') & score_entity(lambda x: x.name != 'system')) title = _('synchronize') category = 'mainactions' order = 20 def url(self): entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0) return entity.absolute_url(vid=self.__regid__)
class ManagerManageButton(HeaderComponent): """ Build a manage button displayed in the header. Only administrators and moderators will see this button. """ __regid__ = "manager-manage" __select__ = match_user_groups("managers", "moderators") & authenticated_user() context = "header-right" order = 2 def attributes(self): return (self._cw.build_url("view", vid="schiirdor.users-management"), "Users & groups", "fa-users")
class ManagerSyncButton(HeaderComponent): """ Build a synchronisation button displayed in the header. Only administrators and moderators will see this button. """ __regid__ = "manager-sync" __select__ = match_user_groups("managers", "moderators") & authenticated_user() context = "header-right" order = 3 def attributes(self): return (self._cw.build_url("view", vid="schiirdor.sync-management"), "Sync", "fa-exchange")
class SCHIIRDORGroupsManagementView(StartupView): """ Manage groups. """ __regid__ = "shiirdor.groups-management" title = _("Manage Groups") __select__ = StartupView.__select__ & match_user_groups("managers") cache_max_age = 0 # disable caching rql = ("Any G,GN ORDERBY GN WHERE G is CWGroup, G name GN, NOT G " "name 'owners'") def call(self, **kwargs): self.w(u"<h1>{0}</h1>".format(self.title)) self.w(add_etype_button(self._cw, "CWGroup")) self.w(u"<div class='clear'></div>") self.wview('shiirdor.groups-table', self._cw.execute(self.rql))
class SCHIIRDORAdminUsersManagementView(StartupView): """ Manage users. """ __regid__ = "shiirdor.admin-users-management" title = _("Manage Users") __select__ = StartupView.__select__ & match_user_groups("managers") cache_max_age = 0 # disable caching rql = ("Any U,UL ORDERBY UL WHERE U is CWUser, U login UL, NOT U " "login 'admin'") def call(self, **kwargs): self.w(u"<h1>{0}</h1>".format(self.title)) self.w(add_etype_button(self._cw, "CWUser")) self.w(u"<div class='clear'></div>") self.wview('shiirdor.admin-users-table', self._cw.execute(self.rql))
class SCHIIRDORGroupsTable(EntityTableView): """ Display a table with the groups information to be managed. """ __regid__ = "shiirdor.groups-table" __select__ = is_instance("CWGroup") & match_user_groups("managers") columns = ["group", "nb_users"] column_renderers = { "group": MainEntityColRenderer(), "nb_users": EntityTableColRenderer( header=_('num. users'), renderfunc=lambda w, x: w(unicode(x.num_users())), sortfunc=lambda x: x.num_users()), }
class CWSourceSyncView(EntityView): __regid__ = 'cw.source-sync' __select__ = (match_user_groups('managers') & one_line_rset() & is_instance('CWSource') & score_entity(lambda x: x.name != 'system')) title = _('synchronize') def entity_call(self, entity): import_log_eid = self._cw.call_service('source-sync', source_eid=entity.eid) msg = self._cw._( 'Synchronization has been requested, refresh this page in a few ' 'minutes.') import_log = self._cw.entity_from_eid(import_log_eid) url = import_log.absolute_url(__message=msg) raise Redirect(url)
class CWUserManagementView(StartupView): __regid__ = 'cw.users-management' __select__ = StartupView.__select__ & match_user_groups('managers') cache_max_age = 0 # disable caching # XXX one could wish to display for instance only user's firstname/surname # for non managers but filtering out NULL caused crash with an ldapuser # source. The ldapuser source has been dropped and this code can be updated. rql = ('Any U,US,F,S,U,UAA,UDS, L,UAA,USN,UDSN ORDERBY L WHERE U is CWUser, ' 'U login L, U firstname F, U surname S, ' 'U in_state US, US name USN, ' 'U primary_email UA?, UA address UAA, ' 'U cw_source UDS, US name UDSN') def call(self, **kwargs): self.w(add_etype_button(self._cw, 'CWUser')) self.w(u'<div class="clear"></div>') self.wview('cw.users-table', self._cw.execute(self.rql))
class SCHIIRDORModeratorIndexView(IndexView): """ Class that defines the index view. """ __regid__ = "index" __select__ = authenticated_user() & match_user_groups( "managers", "moderators") title = _("Index") def call(self, **kwargs): """ Create the loggedin 'index' page of our site. """ # Format template template = self._cw.vreg.template_env.get_template( "startup.logged.jinja2") html = template.render( header_url=self._cw.data_url("creative/img/neurospin.jpg"), moderator=True) self.w(html)
class GCView(StartupView): """display garbage collector information""" __regid__ = 'gc' __select__ = StartupView.__select__ & match_user_groups('managers') title = _('memory leak debugging') cache_max_age = 0 def call(self, **kwargs): stats = self._cw.call_service('repo_gc_stats') self.w(u'<h2>%s</h2>' % _('Garbage collection information')) self.w(u'<h3>%s</h3>' % self._cw._('Looked up classes')) self.wview('pyvaltable', pyvalue=stats['lookupclasses']) self.w(u'<h3>%s</h3>' % self._cw._('Most referenced classes')) self.wview('pyvaltable', pyvalue=stats['referenced']) if stats['unreachable']: self.w(u'<h3>%s</h3>' % self._cw._('Unreachable objects')) values = [xml_escape(val) for val in stats['unreachable']] self.wview('pyvallist', pyvalue=values)
class CwStats(View): """A textual stats output for monitoring tools such as munin """ __regid__ = 'processinfo' content_type = 'text/plain' templatable = False __select__ = none_rset() & match_user_groups('users', 'managers') def call(self): stats = self._cw.call_service('repo_stats') stats['threads'] = ', '.join(sorted(stats['threads'])) for k in stats: if k in ('extid_cache_size', 'type_source_cache_size'): continue if k.endswith('_cache_size'): stats[k] = '%s / %s' % (stats[k]['size'], stats[k]['maxsize']) results = [] for element in stats: results.append(u'%s %s' % (element, stats[element])) self.w(u'\n'.join(results))
class SCHIIRDORUserManagementView(StartupView): """ Manage user associated groups. """ __regid__ = "schiirdor.users-management" __select__ = (StartupView.__select__ & match_user_groups("managers", "moderators")) title = _("Manage User associated Groups") cache_max_age = 0 # disable caching rql = ("Any U,US,F,S,U,UAA,UDS, L,UAA,USN,UDSN ORDERBY L WHERE " "U is CWUser, U login L, NOT U login IN ('anon', 'admin'), " "U firstname F, U surname S, U in_state US, US name USN, " "U primary_email UA?, UA address UAA, " "U cw_source UDS, US name UDSN") def call(self, **kwargs): self.w(u"<h1>{0}</h1>".format(self.title)) rset = self._cw.execute(self.rql) if rset.rowcount > 0: self.wview("schiirdor.users-table", rset) else: self.w(u"No user to manage.".format(self.title))
class ViewAction(action.Action): __regid__ = 'view' __select__ = (action.Action.__select__ & match_user_groups('users', 'managers') & view_is_not_default_view() & non_final_entity()) title = _('view') category = 'mainactions' order = 0 def url(self): params = self._cw.form.copy() for param in ('vid', '__message') + controller.NAV_FORM_PARAMETERS: params.pop(param, None) if self._cw.ajax_request: path = 'view' if self.cw_rset is not None: params = {'rql': self.cw_rset.printable_rql()} else: path = self._cw.relative_path(includeparams=False) return self._cw.build_url(path, **params)
for link in links: url = self._cw.build_url(rql=self.cw_rset.printable_rql(), vid=link.download_vid) _id = link.__regid__ w(u'<a class="btn btn-primary btn-block download-ctx" id="%s" href="%s">' % (_id, url)) w(u'<i class="icon-download icon-white"></i>%s</a>' % self._cw._(link.title)) w(u'</div>') # Add on load the rql facet change self._cw.add_onload("""$(cw).bind('facets-content-loaded', cw.cubes.brainomics.changeDownloadUrls);""") ############################################################################### ### REGISTRATION CALLBACK ##################################################### ############################################################################### BookmarksBox.__select__ = BookmarksBox.__select__ & match_user_groups('users', 'managers') ApplicationName.context = 'header-left' def registration_callback(vreg): vreg.register_all(globals().values(), __name__, (BrainomicsSearchBox, BrainomicsEditBox, )) vreg.register_and_replace(BrainomicsSearchBox, SearchBox) vreg.register_and_replace(BrainomicsEditBox, EditBox) # Unregister breadcrumbs from cubicweb.web.views.ibreadcrumbs import (BreadCrumbEntityVComponent, BreadCrumbLinkToVComponent, BreadCrumbAnyRSetVComponent, BreadCrumbETypeVComponent) vreg.unregister(BreadCrumbEntityVComponent)