def searchResults(self, query=None, **kw): # Calls ZCatalog.searchResults with extra arguments that # limit the results to what the user is allowed to see. # # This version uses the 'effectiveRange' DateRangeIndex. # # It also accepts a keyword argument show_inactive to disable # effectiveRange checking entirely even for those without portal # wide AccessInactivePortalContent permission. # Make sure any pending index tasks have been processed processQueue() kw = kw.copy() show_inactive = kw.get('show_inactive', False) if isinstance(query, dict) and not show_inactive: show_inactive = 'show_inactive' in query user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not show_inactive and not self.allow_inactive(kw): kw['effectiveRange'] = DateTime() sort_on = kw.get('sort_on') if sort_on and sort_on not in self.indexes(): # I get crazy sort_ons like '194' or 'null'. kw.pop('sort_on') return ZCatalog.searchResults(self, query, **kw)
def searchResults(self, REQUEST=None, check_perms=False, **kw): mode = self.mode if mode == DISABLE_MODE: return self.patched.searchResults(REQUEST, **kw) if isinstance(REQUEST, dict): query = REQUEST.copy() else: query = {} query.update(kw) if check_perms: show_inactive = query.get('show_inactive', False) if isinstance(REQUEST, dict) and not show_inactive: show_inactive = 'show_inactive' in REQUEST user = _getAuthenticatedUser(self.catalogtool) query['allowedRolesAndUsers'] = self.catalogtool._listAllowedRolesAndUsers(user) if not show_inactive and not _checkPermission( AccessInactivePortalContent, self.catalogtool): query['effectiveRange'] = DateTime() orig_query = query.copy() # info('Running query: %s' % repr(orig_query)) try: return self.query(query) except: info("Error running Query: %s\n%s" %( repr(orig_query), traceback.format_exc())) if mode == DUAL_MODE: # fall back now... return self.patched.searchResults(REQUEST, **kw) else: return LazyMap(BrainFactory(self.catalog), [], 0)
def searchResults(self, REQUEST=None, check_perms=False, **kw): mode = self.mode if mode == DISABLE_MODE: return self.patched.searchResults(REQUEST, **kw) if isinstance(REQUEST, dict): query = REQUEST.copy() else: query = {} query.update(kw) if check_perms: show_inactive = query.get('show_inactive', False) if isinstance(REQUEST, dict) and not show_inactive: show_inactive = 'show_inactive' in REQUEST user = _getAuthenticatedUser(self.catalogtool) query[ 'allowedRolesAndUsers'] = self.catalogtool._listAllowedRolesAndUsers( user) if not show_inactive and not _checkPermission( AccessInactivePortalContent, self.catalogtool): query['effectiveRange'] = DateTime() orig_query = query.copy() # info('Running query: %s' % repr(orig_query)) try: return self.query(query) except: info("Error running Query: %s\n%s" % (repr(orig_query), traceback.format_exc())) if mode == DUAL_MODE: # fall back now... return self.patched.searchResults(REQUEST, **kw) else: return LazyMap(BrainFactory(self.catalog), [], 0)
def credentialsChanged(self, password, REQUEST=None): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' # XXX: this method violates the rules for tools/utilities: # it depends on self.REQUEST if REQUEST is None: REQUEST = self.REQUEST warn("credentialsChanged should be called with 'REQUEST' as " "second argument. The BBB code will be removed in CMF 2.3.", DeprecationWarning, stacklevel=2) if not self.isAnonymousUser(): acl_users = self.acl_users user = _getAuthenticatedUser(self) name = user.getUserName() # this really does need to be the user name, and not the user id, # because we're dealing with authentication credentials p = getattr(REQUEST, '_credentials_changed_path', None) if p is not None: # Use an interface provided by CookieCrumbler. change = self.restrictedTraverse(p) change(user, name, password)
def credentialsChanged(self, password, REQUEST=None): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' # XXX: this method violates the rules for tools/utilities: # it depends on self.REQUEST if REQUEST is None: REQUEST = self.REQUEST warn( "credentialsChanged should be called with 'REQUEST' as " "second argument. The BBB code will be removed in CMF 2.3.", DeprecationWarning, stacklevel=2) if not self.isAnonymousUser(): acl_users = self.acl_users user = _getAuthenticatedUser(self) name = user.getUserName() # this really does need to be the user name, and not the user id, # because we're dealing with authentication credentials p = getattr(REQUEST, '_credentials_changed_path', None) if p is not None: # Use an interface provided by CookieCrumbler. change = self.restrictedTraverse(p) change(user, name, password)
def listMFUndoableTransactionsFor(self, object, first_transaction=None, last_transaction=None, PrincipiaUndoBatchSize=None, #mount_folder_path='/content' ): """ Lists all transaction IDs the user is allowed to undo inside the MountFolder (self). """ portal = self.aq_inner.aq_parent #if mount_folder_path=='/content': # mount_folder = portal.content #else: # pass # FIXME transactions = self.undoable_transactions( first_transaction=first_transaction, last_transaction=last_transaction, PrincipiaUndoBatchSize=PrincipiaUndoBatchSize) for t in transactions: # Ensure transaction ids don't have embedded LF. t['id'] = t['id'].replace('\n', '') if not _checkPermission('Manage portal', portal): # Filter out transactions done by other members of the portal. user_id = _getAuthenticatedUser(self).getId() transactions = filter( lambda record, user_id=user_id: record['user_name'].split()[-1] == user_id, transactions ) return transactions
def searchResults(self, query=None, **kw): # Calls ZCatalog.searchResults with extra arguments that # limit the results to what the user is allowed to see. # # This version uses the 'effectiveRange' DateRangeIndex. # # It also accepts a keyword argument show_inactive to disable # effectiveRange checking entirely even for those without portal # wide AccessInactivePortalContent permission. # Make sure any pending index tasks have been processed processQueue() kw = kw.copy() show_inactive = kw.get('show_inactive', False) if isinstance(query, dict) and not show_inactive: show_inactive = 'show_inactive' in query user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not show_inactive and not self.allow_inactive(kw): kw['effectiveRange'] = DateTime() sort_on = kw.get('sort_on') if sort_on and sort_on not in self.indexes(): # I get crazy sort_ons like '194' or 'null'. kw.pop('sort_on') return ZCatalog.searchResults(self, query, **kw)
def __call__(self): if self.request.method != 'POST': self.request.response.setStatus(405) return '' self.request.stdin.seek(0, 0) payload = json.load(self.request.stdin) if not isinstance(payload, dict): self.request.response.setStatus(400) return '' if 'fields' in payload: if (not isinstance(payload['fields'], list) or 'contents' in payload['fields']): # Prevent people to retrieve the fulltext. self.request.response.setStatus(400) return '' authorizedFilter = { 'terms': { 'authorizedUsers': self._listAllowedRolesAndUsers( _getAuthenticatedUser(self.context)), 'execution': 'or'}} if 'query' in payload: if 'filtered' in payload['query']: filtered = payload['query']['filtered'] if ('filter' not in filtered or not isinstance(filtered['filter'], dict)): self.request.response.setStatus(400) return '' if 'and' not in filtered['filter']: filters = [filtered.pop('filter')] filtered['filter'] = {'and': filters} else: filters = filtered['filter']['and'] if not isinstance(filters, list): self.request.response.setStatus(400) return '' filters.append(authorizedFilter) else: query = payload.pop('query') payload['query'] = { 'filtered': { 'query': query, 'filter': authorizedFilter}} else: payload['query'] = { 'filtered': {'filter': authorizedFilter}} settings = IElasticSettings(getUtility(IPloneSiteRoot)) try: response = urllib2.urlopen( random.choice(settings.get_search_urls()), json.dumps(payload)) except: self.request.response.setStatus(500) return '' self.request.response.setHeader( 'Content-Type', 'application/json;charset=UTF-8') return response.read()
def isAnonymousUser(self): ''' Returns 1 if the user is not logged in. ''' u = _getAuthenticatedUser(self) if u is None or u.getUserName() == 'Anonymous User': return 1 return 0
def isAnonymousUser(self): ''' Returns 1 if the user is not logged in. ''' u = _getAuthenticatedUser(self) if u is None or u.getUserName() == 'Anonymous User': return 1 return 0
def __call__(self, *args, **kwargs): """ See IVocabularyFactory interface """ user = _getAuthenticatedUser(getSite()) user_id = user.getId() user_name = user.getUserName() return SimpleVocabulary([SimpleTerm(user_id, user_id, user_name)])
def __call__(self, context): """ See IVocabularyFactory interface """ user = _getAuthenticatedUser(context) user_id = user.getId() user_name = user.getUserName() return SimpleVocabulary([SimpleTerm(user_id, user_id, user_name)])
def __call__(self, context): """ See IVocabularyFactory interface """ user = _getAuthenticatedUser(context) user_id = user.getId() user_name = user.getUserName() return SimpleVocabulary([SimpleTerm(user_id, user_id, user_name)])
def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. ''' u = _getAuthenticatedUser(self) if u is None: u = nobody return self.wrapUser(u)
def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. ''' u = _getAuthenticatedUser(self) if u is None: u = nobody return self.wrapUser(u)
def searchResults(self, REQUEST=None, **kw): """ Calls ZCatalog.searchResults with extra arguments that limit the results to what the user is allowed to see. """ processQueue() user = _getAuthenticatedUser(self) kw[ 'allowedRolesAndUsers' ] = self._listAllowedRolesAndUsers( user ) if not _checkPermission( AccessInactivePortalContent, self ): now = DateTime() self._convertQuery(kw) # Intersect query restrictions with those implicit to the tool for k in 'effective', 'expires': if kw.has_key(k): range = kw[k]['range'] or '' query = kw[k]['query'] if not isinstance(query, (tuple, list)): query = (query,) else: range = '' query = None if range.find('min') > -1: lo = min(query) else: lo = None if range.find('max') > -1: hi = max(query) else: hi = None if k == 'effective': if hi is None or hi > now: hi = now if lo is not None and hi < lo: return () else: # 'expires': if lo is None or lo < now: lo = now if hi is not None and hi < lo: return () # Rebuild a query if lo is None: query = hi range = 'max' elif hi is None: query = lo range = 'min' else: query = (lo, hi) range = 'min:max' kw[k] = {'query': query, 'range': range} return ZCatalog.searchResults(self, REQUEST, **kw)
def getNotAddableTypes(self): """ Only allow managers to add members """ from Products.CMFCore.utils import _getAuthenticatedUser user = _getAuthenticatedUser(self) if 'Manager' in user.getRoles(): return () else: return ('Member',)
def searchResults(self, REQUEST=None, **kw): """ Calls ZCatalog.searchResults with extra arguments that limit the results to what the user is allowed to see. """ user = _getAuthenticatedUser(self) kw[ 'allowedRolesAndUsers' ] = self._listAllowedRolesAndUsers( user ) if not _checkPermission( AccessInactivePortalContent, self ): now = DateTime() self._convertQuery(kw) # Intersect query restrictions with those implicit to the tool for k in 'effective', 'expires': if kw.has_key(k): range = kw[k]['range'] or '' query = kw[k]['query'] if not isinstance(query, (tuple, list)): query = (query,) else: range = '' query = None if range.find('min') > -1: lo = min(query) else: lo = None if range.find('max') > -1: hi = max(query) else: hi = None if k == 'effective': if hi is None or hi > now: hi = now if lo is not None and hi < lo: return () else: # 'expires': if lo is None or lo < now: lo = now if hi is not None and hi < lo: return () # Rebuild a query if lo is None: query = hi range = 'max' elif hi is None: query = lo range = 'min' else: query = (lo, hi) range = 'min:max' kw[k] = {'query': query, 'range': range} return ZCatalog.searchResults(self, REQUEST, **kw)
def getNotAddableTypes(self): """ Only allow managers to add members """ from Products.CMFCore.utils import _getAuthenticatedUser user = _getAuthenticatedUser(self) if 'Manager' in user.getRoles(): return () else: return self.getAllowedMemberTypes()
def __call__(self): user = _getAuthenticatedUser(self) pc = getToolByName(self.context, "portal_catalog") self.request.response.setHeader("Content-Type", "application/json") # noinspection PyProtectedMember return json.dumps({ "allowedRolesAndUsers": { "tokens": list(pc._listAllowedRolesAndUsers(user)), "expires": time.time() + 60, } })
def workspacesSearchResults(catalog, REQUEST=None, **kw): """Catalog search rseults, but only for those objects for which you have a specific ownership. That is, we take the roles out of allowedRolesAndUsers. This can still bite a few users (whomever owns the portal) but most managers will get a reasonable set of data--only what they own. Unlike regular searchResults, doesn't check for expiry, since we don't use that. """ user = _getAuthenticatedUser(catalog) allowedRolesAndUsers = catalog._listAllowedRolesAndUsers(user) allowedRolesAndUsers = [x for x in allowedRolesAndUsers if x.startswith('user:'******'allowedRolesAndUsers'] = allowedRolesAndUsers return catalog.unrestrictedSearchResults(REQUEST, **kw)
def searchResults(self, REQUEST=None, **kw): """Calls lenses_catalog.searchResults with extra arguments that limit the results to what the user is allowed to see. """ portal_catalog = getToolByName(self, 'portal_catalog') lens_catalog = getToolByName(self, 'lens_catalog') user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = portal_catalog._listAllowedRolesAndUsers(user) # portal_catalog checks expiry here, but we don't care return lens_catalog.searchResults(REQUEST=REQUEST, **kw)
def search(self, query, sort_index=None, reverse=0, limit=None, merge=1): # Wrap search() the same way that searchResults() is # Make sure any pending index tasks have been processed processQueue() user = _getAuthenticatedUser(self) query['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not self.allow_inactive(query): query['effectiveRange'] = DateTime() return super().search(query, sort_index, reverse, limit, merge)
def development(self): """ To set development mode: - we can define a envvar: FEDEV - otherwise if its anonymous is using production mode - finally is checked on the registry entry """ if RESOURCE_DEVELOPMENT_MODE: return True if _getAuthenticatedUser(self.context).getUserName() == 'Anonymous User': return False return self.registry.records['plone.resources.development'].value
def searchResults(self, REQUEST=None, **kw): """Calls lenses_catalog.searchResults with extra arguments that limit the results to what the user is allowed to see. """ portal_catalog = getToolByName(self, 'portal_catalog') lens_catalog = getToolByName(self, 'lens_catalog') user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = portal_catalog._listAllowedRolesAndUsers( user) # portal_catalog checks expiry here, but we don't care return lens_catalog.searchResults(REQUEST=REQUEST, **kw)
def workspacesSearchResults(catalog, REQUEST=None, **kw): """Catalog search rseults, but only for those objects for which you have a specific ownership. That is, we take the roles out of allowedRolesAndUsers. This can still bite a few users (whomever owns the portal) but most managers will get a reasonable set of data--only what they own. Unlike regular searchResults, doesn't check for expiry, since we don't use that. """ user = _getAuthenticatedUser(catalog) allowedRolesAndUsers = catalog._listAllowedRolesAndUsers(user) allowedRolesAndUsers = [ x for x in allowedRolesAndUsers if x.startswith('user:'******'allowedRolesAndUsers'] = allowedRolesAndUsers return catalog.unrestrictedSearchResults(REQUEST, **kw)
def handleDynamicTypeCopiedEvent(ob, event): """ Event subscriber for (IDynamicType, IObjectCopiedEvent) events. """ # Make sure owner local role is set after pasting # The standard Zope mechanisms take care of executable ownership current_user = _getAuthenticatedUser(ob) if current_user is None: return current_user_id = current_user.getId() if current_user_id is not None: local_role_holders = [ x[0] for x in ob.get_local_roles() ] ob.manage_delLocalRoles(local_role_holders) ob.manage_setLocalRoles(current_user_id, ['Owner'])
def development(self): """ To set development mode: - we can define a envvar: FEDEV - otherwise if its anonymous is using production mode - finally is checked on the registry entry """ if RESOURCE_DEVELOPMENT_MODE: return True if _getAuthenticatedUser( self.context).getUserName() == 'Anonymous User': return False return self.registry.records['plone.resources.development'].value
def searchResults(self, REQUEST=None, **kw): """ based on the version in `CMFPlone/CatalogTool.py` """ kw = kw.copy() only_active = not kw.get('show_inactive', False) user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if only_active and not _checkPermission(AccessInactivePortalContent, self): kw['effectiveRange'] = DateTime() adapter = queryAdapter(self, ISearchDispatcher) if adapter is not None: return adapter(REQUEST, **kw) else: return self._cs_old_searchResults(REQUEST, **kw)
def searchResults(self, REQUEST=None, **kw): """ based on the version in `CMFPlone/CatalogTool.py` """ kw = kw.copy() only_active = not kw.get('show_inactive', False) user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if only_active and not _checkPermission(AccessInactivePortalContent, self): kw['effectiveRange'] = DateTime() adapter = queryAdapter(self, ISearchDispatcher) if adapter is not None: return adapter(REQUEST, **kw) else: return self._cs_old_searchResults(REQUEST, **kw)
def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. This caches the value in the reqeust... ''' if not "_c_authenticatedUser" in self.REQUEST: u = _getAuthenticatedUser(self) if u is None: u = nobody if str(u) not in ('Anonymous User',): self.REQUEST['_c_authenticatedUser'] = u else: u = self.REQUEST['_c_authenticatedUser'] return self.wrapUser(u)
def search(self, query, sort_index=None, reverse=0, limit=None, merge=1): # Wrap search() the same way that searchResults() is # Make sure any pending index tasks have been processed processQueue() user = _getAuthenticatedUser(self) query['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not self.allow_inactive(query): query['effectiveRange'] = DateTime() return super(CatalogTool, self).search( query, sort_index, reverse, limit, merge)
def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. This caches the value in the reqeust... ''' if not "_c_authenticatedUser" in self.REQUEST: u = _getAuthenticatedUser(self) if u is None: u = nobody if str(u) not in ('Anonymous User',): self.REQUEST['_c_authenticatedUser'] = u else: u = self.REQUEST['_c_authenticatedUser'] return self.wrapUser(u)
def search_es(self, query, start, size): user = _getAuthenticatedUser(self.catalog) query['allowedRolesAndUsers'] = self.catalog._listAllowedRolesAndUsers( user) es = ElasticSearchCatalog(self.catalog) qassembler = getMultiAdapter((self.request, es), IQueryAssembler) dquery, sort = qassembler.normalize(query) equery = qassembler(dquery) doc_type = es.doc_type if 'searchSite' in self.request.form: doc_type = CRAWLED_SITE_ES_DOC_TYPE equery = { 'filtered': { 'filter': { "term": { "domain": self.request.form['searchSite'] } }, 'query': equery['function_score']['query']['filtered']['query'] } } query = { 'query': equery, "suggest": { "SearchableText": { "text": query.get('SearchableText', ''), "term": { "field": "SearchableText" } } }, 'sort': sort } query_params = { 'from_': start, 'size': size, 'fields': ','.join(_search_attributes) + ',path.path' } return es.connection.search(index=es.index_name, doc_type=doc_type, body=query, **query_params)
def search_es(self, query, start, size): user = _getAuthenticatedUser(self.catalog) query['allowedRolesAndUsers'] = self.catalog._listAllowedRolesAndUsers( user) es = ElasticSearchCatalog(self.catalog) qassembler = getMultiAdapter((self.request, es), IQueryAssembler) dquery, sort = qassembler.normalize(query) equery = qassembler(dquery) index_name = es.index_name if 'searchSite' in self.request.form: index_name = '{index_name}_crawler'.format( index_name=es.index_name) # get rid of allowedRolesAndUsers,trashed,popularity script,etc (n/a for public crawl) equery = equery['script_score']['query'] equery['bool']['filter'] = [{ 'term': { 'domain': self.request.form['searchSite'] } }] query = { 'query': equery, "suggest": { "SearchableText": { "text": query.get('SearchableText', ''), "term": { "field": "SearchableText" } } }, 'sort': sort } query_params = { 'stored_fields': ','.join(_search_attributes), 'from_': start, 'size': size, } return es.connection.search(index=index_name, body=query, **query_params)
def credentialsChanged(self, password, REQUEST=None): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' if not self.isAnonymousUser(): user = _getAuthenticatedUser(self) name = user.getUserName() # this really does need to be the user name, and not the user id, # because we're dealing with authentication credentials try: cctool = getToolByName(self, 'cookie_authentication') cctool.credentialsChanged(user, name, password, REQUEST) except AttributeError: # No CookieCrumbler pass
def credentialsChanged(self, password, REQUEST=None): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' if not self.isAnonymousUser(): user = _getAuthenticatedUser(self) name = user.getUserName() # this really does need to be the user name, and not the user id, # because we're dealing with authentication credentials try: cctool = getToolByName(self, 'cookie_authentication') cctool.credentialsChanged(user, name, password, REQUEST) except AttributeError: # No CookieCrumbler pass
def createMemberArea(self, member_id=''): """ Create a member area for 'member_id' or authenticated user. """ if not self.getMemberareaCreationFlag(): return None members = self.getMembersFolder() if members is None: return None if self.isAnonymousUser(): return None # Note: We can't use getAuthenticatedMember() and getMemberById() # because they might be wrapped by MemberDataTool. user = _getAuthenticatedUser(self) user_id = user.getId() if member_id in ('', user_id): member = user member_id = user_id else: if _checkPermission(ManageUsers, self): uf = self._huntUserFolder(member_id, self) if uf: member = uf.getUserById(member_id).__of__(uf) else: raise ValueError('Member %s does not exist' % member_id) else: return None if hasattr( aq_base(members), member_id ): return None else: f_title = "%s's Home" % member_id members.manage_addPortalFolder( id=member_id, title=f_title ) f=getattr(members, member_id) f.manage_permission(View, ['Owner','Manager','Reviewer'], 0) f.manage_permission(AccessContentsInformation, ['Owner','Manager','Reviewer'], 0) # Grant Ownership and Owner role to Member f.changeOwnership(member) f.__ac_local_roles__ = None f.manage_setLocalRoles(member_id, ['Owner']) return f
def createMemberArea(self, member_id=''): """ Create a member area for 'member_id' or authenticated user. """ if not self.getMemberareaCreationFlag(): return None members = self.getMembersFolder() if members is None: return None if self.isAnonymousUser(): return None # Note: We can't use getAuthenticatedMember() and getMemberById() # because they might be wrapped by MemberDataTool. user = _getAuthenticatedUser(self) user_id = user.getId() if member_id in ('', user_id): member = user member_id = user_id else: if _checkPermission(ManageUsers, self): uf = self._huntUserFolder(member_id, self) if uf: member = uf.getUserById(member_id).__of__(uf) else: raise ValueError('Member %s does not exist' % member_id) else: return None if hasattr( aq_base(members), member_id ): return None else: f_title = "%s's Home" % member_id members.manage_addPortalFolder( id=member_id, title=f_title ) f=getattr(members, member_id) f.manage_permission(View, ['Owner','Manager','Reviewer'], 0) f.manage_permission(AccessContentsInformation, ['Owner','Manager','Reviewer'], 0) # Grant Ownership and Owner role to Member f.changeOwnership(member) f.__ac_local_roles__ = None f.manage_setLocalRoles(member_id, ['Owner']) return f
def handleDynamicTypeCopiedEvent(ob, event): # Make sure owner local role is set after pasting # The standard Zope mechanisms take care of executable ownership current_user = _getAuthenticatedUser(ob) if current_user is None: return current_user_id = current_user.getId() if current_user_id is not None: # Customization are_all_local_roles_deleted = RoleAssignmentManager(ob)\ .update_local_roles_after_copying(current_user_id) if not are_all_local_roles_deleted: message = _( 'local_roles_copied', default=u"Some local roles were copied with the objects") api.portal.show_message(message=message, request=getRequest(), type='info')
def searchResults(self, REQUEST=None, check_perms=False, **kw): enabled = False if self.enabled: # need to also check if it is a search result we care about # using EL for if getESOnlyIndexes().intersection(kw.keys()): enabled = True if not enabled: if check_perms: return self.catalogtool._old_searchResults(REQUEST, **kw) else: return self.catalogtool._old_unrestrictedSearchResults( REQUEST, **kw) if isinstance(REQUEST, dict): query = REQUEST.copy() else: query = {} query.update(kw) if check_perms: show_inactive = query.get('show_inactive', False) if isinstance(REQUEST, dict) and not show_inactive: show_inactive = 'show_inactive' in REQUEST user = _getAuthenticatedUser(self.catalogtool) query['allowedRolesAndUsers'] = \ self.catalogtool._listAllowedRolesAndUsers(user) if not show_inactive and not _checkPermission( AccessInactivePortalContent, self.catalogtool): query['effectiveRange'] = DateTime() orig_query = query.copy() logger.debug('Running query: %s' % repr(orig_query)) try: results = self.search(query) return results except Exception: logger.error( 'Error running Query: {0!r}'.format(orig_query), exc_info=True) return self.catalogtool._old_searchResults(REQUEST, **kw)
def searchResults(self, REQUEST=None, check_perms=False, **kw): enabled = False if self.enabled: # need to also check if it is a search result we care about # using EL for if getESOnlyIndexes().intersection(kw.keys()): enabled = True if not enabled: if check_perms: return self.catalogtool._old_searchResults(REQUEST, **kw) else: return self.catalogtool._old_unrestrictedSearchResults( REQUEST, **kw) if isinstance(REQUEST, dict): query = REQUEST.copy() else: query = {} query.update(kw) if check_perms: show_inactive = query.get('show_inactive', False) if isinstance(REQUEST, dict) and not show_inactive: show_inactive = 'show_inactive' in REQUEST user = _getAuthenticatedUser(self.catalogtool) query['allowedRolesAndUsers'] = \ self.catalogtool._listAllowedRolesAndUsers(user) if not show_inactive and not _checkPermission( AccessInactivePortalContent, self.catalogtool): query['effectiveRange'] = DateTime() orig_query = query.copy() logger.debug('Running query: %s' % repr(orig_query)) try: results = self.search(query) return results except Exception: logger.error( 'Error running Query: {0!r}'.format(orig_query), exc_info=True) return self.catalogtool._old_searchResults(REQUEST, **kw)
def handleDynamicTypeCopiedEvent(ob, event): # Make sure owner local role is set after pasting # The standard Zope mechanisms take care of executable ownership current_user = _getAuthenticatedUser(ob) if current_user is None: return current_user_id = current_user.getId() if current_user_id is not None: # Customization are_all_local_roles_deleted = RoleAssignmentManager(ob)\ .update_local_roles_after_copying(current_user_id) if not are_all_local_roles_deleted: message = _( 'local_roles_copied', default=u"Some local roles were copied with the objects" ) api.portal.show_message(message=message, request=getRequest(), type='info')
def searchResults(self, REQUEST=None, **kw): """Calls ZCatalog.searchResults with extra arguments that limit the results to what the user is allowed to see. This version uses the 'effectiveRange' DateRangeIndex. It also accepts a keyword argument show_inactive to disable effectiveRange checking entirely even for those without portal wide AccessInactivePortalContent permission. """ kw = kw.copy() show_inactive = kw.get('show_inactive', False) user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not show_inactive and not _checkPermission(AccessInactivePortalContent, self): kw['effectiveRange'] = DateTime() return ZCatalog.searchResults(self, REQUEST, **kw)
def search(self, *args, **kw): # Wrap search() the same way that searchResults() is query = {} if args: query = args[0] elif 'query_request' in kw: query = kw.get('query_request') kw['query_request'] = query.copy() user = _getAuthenticatedUser(self) query['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not _checkPermission(AccessInactivePortalContent, self): query['effectiveRange'] = DateTime() kw['query_request'] = query return super(CatalogTool, self).search(**kw)
def search(self, *args, **kw): # Wrap search() the same way that searchResults() is query = {} if args: query = args[0] elif 'query_request' in kw: query = kw.get('query_request') kw['query_request'] = query.copy() user = _getAuthenticatedUser(self) query['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not _checkPermission(AccessInactivePortalContent, self): query['effectiveRange'] = DateTime() kw['query_request'] = query return super(CatalogTool, self).search(**kw)
def searchResults(self, REQUEST=None, check_perms=False, **kw): enabled = False if self.enabled: # need to also check is it is a search result we care about # using EL for if 'Title' in kw or 'SearchableText' in kw or 'Description' in kw: # XXX need a smarter check here... enabled = True if not enabled: if check_perms: return self.catalogtool._old_searchResults(REQUEST, **kw) else: return self.catalogtool._old_unrestrictedSearchResults(REQUEST, **kw) if isinstance(REQUEST, dict): query = REQUEST.copy() else: query = {} query.update(kw) if check_perms: show_inactive = query.get('show_inactive', False) if isinstance(REQUEST, dict) and not show_inactive: show_inactive = 'show_inactive' in REQUEST user = _getAuthenticatedUser(self.catalogtool) query['allowedRolesAndUsers'] = \ self.catalogtool._listAllowedRolesAndUsers(user) if not show_inactive and not _checkPermission( AccessInactivePortalContent, self.catalogtool): query['effectiveRange'] = DateTime() orig_query = query.copy() # info('Running query: %s' % repr(orig_query)) try: return self.search(query) except: info('Error running Query: %s\n%s' % ( repr(orig_query), traceback.format_exc())) return self.catalogtool._old_searchResults(REQUEST, **kw)
def listUndoableTransactionsFor(self, object, first_transaction=None, last_transaction=None, PrincipiaUndoBatchSize=None): """ List all transaction IDs the user is allowed to undo on 'object'. """ transactions = object.undoable_transactions( first_transaction=first_transaction, last_transaction=last_transaction, PrincipiaUndoBatchSize=PrincipiaUndoBatchSize) for t in transactions: # Ensure transaction ids don't have embedded LF. t['id'] = t['id'].replace('\n', '') if not _checkPermission(ManagePortal, object): # Filter out transactions done by other members of the portal. user_id = _getAuthenticatedUser(self).getId() transactions = filter(lambda record, user_id=user_id: record[ 'user_name'].split()[-1] == user_id, transactions) return transactions
def searchResults(self, REQUEST=None, **kw): """ Calls ZCatalog.searchResults with extra arguments that limit the results to what the user is allowed to see. """ user = _getAuthenticatedUser(self) kw[ 'allowedRolesAndUsers' ] = self._listAllowedRolesAndUsers( user ) if not _checkPermission( AccessInactivePortalContent, self ): base = aq_base( self ) #now = DateTime() #if hasattr( base, 'addIndex' ): # Zope 2.4 and above #kw[ 'effective' ] = { 'query' : now, 'range' : 'max' } #kw[ 'expires' ] = { 'query' : now, 'range' : 'min' } #else: # Zope 2.3 #kw[ 'effective' ] = kw[ 'expires' ] = now #kw[ 'effective_usage'] = 'range:max' #kw[ 'expires_usage' ] = 'range:min' kw['effectiveRange'] = DateTime() return apply(ZCatalog.searchResults, (self, REQUEST), kw)
def refreshlocalroles(self, user=None): if user is None: userid = _getAuthenticatedUser(None).getId() else: userid = user.getId() if not userid: return for path in self.localRoles.iterkeys(): obj = self.unrestrictedTraverse(path, None) if obj is not None: roles = self._findroles(obj) reindex = False current_localroles = obj.get_local_roles_for_userid(userid) if not roles and current_localroles: obj.manage_delLocalRoles((userid,)) reindex = True elif tuple(roles) != current_localroles: obj.manage_setLocalRoles(userid, roles) reindex = True if reindex: obj.reindexObjectSecurity()
def searchResultsTrashed(self, REQUEST=None, **kw): kw = kw.copy() show_inactive = kw.get('show_inactive', False) user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if (not show_inactive and not _checkPermission(AccessInactivePortalContent, self)): kw['effectiveRange'] = DateTime() request = getattr(self, 'REQUEST', None) if request is None: session = None else: session = getattr(self.REQUEST, 'SESSION', None) if 'trashed' not in kw: kw['trashed'] = session and session.get('trashcan', False) or False return ZCatalog.searchResults(self, REQUEST, **kw)
def refreshlocalroles(self, user=None): if user is None: userid = _getAuthenticatedUser(None).getId() else: userid = user.getId() if not userid: return for path in self.localRoles.iterkeys(): obj = self.unrestrictedTraverse(path, None) if obj is not None: roles = self._findroles(obj) reindex = False current_localroles = obj.get_local_roles_for_userid(userid) if not roles and current_localroles: obj.manage_delLocalRoles((userid,)) reindex = True elif tuple(roles) != current_localroles: obj.manage_setLocalRoles(userid, roles) reindex = True if reindex: obj.reindexObjectSecurity()
def searchResultsTrashed(self, REQUEST=None, **kw): kw = kw.copy() show_inactive = kw.get('show_inactive', False) user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if (not show_inactive and not _checkPermission(AccessInactivePortalContent, self)): kw['effectiveRange'] = DateTime() request = getattr(self, 'REQUEST', None) if request is None: session = None else: session = getattr(self.REQUEST, 'SESSION', None) if 'trashed' not in kw: kw['trashed'] = session and session.get('trashcan', False) or False return ZCatalog.searchResults(self, REQUEST, **kw)
def searchResults(self, query=None, **kw): # Calls ZCatalog.searchResults with extra arguments that # limit the results to what the user is allowed to see. # # This version uses the 'effectiveRange' DateRangeIndex. # # It also accepts a keyword argument show_inactive to disable # effectiveRange checking entirely even for those without portal # wide AccessInactivePortalContent permission. # Make sure any pending index tasks have been processed processQueue() kw = kw.copy() show_inactive = kw.get('show_inactive', False) if isinstance(query, dict) and not show_inactive: show_inactive = 'show_inactive' in query user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not show_inactive and not self.allow_inactive(kw): kw['effectiveRange'] = DateTime() # filter out invalid sort_on indexes sort_on = kw.get('sort_on') or [] if isinstance(sort_on, six.string_types): sort_on = [sort_on] valid_indexes = self.indexes() try: sort_on = [idx for idx in sort_on if idx in valid_indexes] except TypeError: # sort_on is not iterable sort_on = [] if not sort_on: kw.pop('sort_on', None) else: kw['sort_on'] = sort_on return ZCatalog.searchResults(self, query, **kw)
def _apply_index(self, request, cid=''): record = parseIndexRequest(request, self.getId(), self.query_options) if record.keys is None: return None catalog = getToolByName(self, 'portal_catalog') geoIndex = catalog._catalog.getIndex(self.geoindex_id) geoRequest = {} geoRequest[self.geoindex_id] = { 'query': record.keys, 'range': record.range} geo_response = geoIndex._apply_index(geoRequest, raw=True) paths = {} for item in geo_response: paths[int(item['id'])] = item['properties']['path'] rolesIndex = catalog._catalog.getIndex('allowedRolesAndUsers') user = _getAuthenticatedUser(self) perms_set = rolesIndex._apply_index( {'allowedRolesAndUsers': catalog._listAllowedRolesAndUsers(user)} )[0] r = intersection(perms_set, IISet(paths.keys())) if isinstance(r, int): r = IISet((r,)) if r is None: return IISet(), (self.getId(),) else: url_tool = getToolByName(self, 'portal_url') portal_path = url_tool.getPortalObject().getPhysicalPath() root = list(portal_path) def up(path): return '/'.join(root + path.strip('/').split('/')[:-1]) return union( r, IISet([catalog.getrid(up(paths[lid])) for lid in r]) ), (self.getId(),)
def searchResults(self, query=None, **kw): # Calls ZCatalog.searchResults with extra arguments that # limit the results to what the user is allowed to see. # # This version uses the 'effectiveRange' DateRangeIndex. # # It also accepts a keyword argument show_inactive to disable # effectiveRange checking entirely even for those without portal # wide AccessInactivePortalContent permission. # Make sure any pending index tasks have been processed processQueue() kw = kw.copy() show_inactive = kw.get('show_inactive', False) if isinstance(query, dict) and not show_inactive: show_inactive = 'show_inactive' in query user = _getAuthenticatedUser(self) kw['allowedRolesAndUsers'] = self._listAllowedRolesAndUsers(user) if not show_inactive and not self.allow_inactive(kw): kw['effectiveRange'] = DateTime() # filter out invalid sort_on indexes sort_on = kw.get('sort_on') or [] if isinstance(sort_on, six.string_types): sort_on = [sort_on] valid_indexes = self.indexes() try: sort_on = [idx for idx in sort_on if idx in valid_indexes] except TypeError: # sort_on is not iterable sort_on = [] if not sort_on: kw.pop('sort_on', None) else: kw['sort_on'] = sort_on return ZCatalog.searchResults(self, query, **kw)