def updateSkinCookie(self): """ If needed, updates the skin cookie based on the member preference. """ mtool = getToolByName(self, 'portal_membership') utool = getToolByName(self, 'portal_url') member = mtool.getAuthenticatedMember() if hasattr(aq_base(member), 'getProperty'): mskin = member.getProperty('portal_skin', None) if mskin: req = self.REQUEST cookie = req.cookies.get(self.request_varname, None) if cookie != mskin: resp = req.RESPONSE portal_path = req['BASEPATH1'] + '/' + utool(1) if not self.cookie_persistence: # *Don't* make the cookie persistent! resp.setCookie(self.request_varname, mskin, path=portal_path) else: expires = ( DateTime( 'GMT' ) + 365 ).rfc822() resp.setCookie( self.request_varname , mskin , path=portal_path , expires=expires ) # Ensure updateSkinCookie() doesn't try again # within this request. req.cookies[self.request_varname] = mskin req[self.request_varname] = mskin return 1 return 0
def afterCreate(ob): wf = getToolByName(ob, 'portal_workflow', None) if ob is not None: wf.notifyCreated(ob) catalog = getToolByName(ob, 'portal_catalog', None) if catalog is not None: catalog.reindexObject(ob)
def updateSkinCookie(self): ''' If needed, updates the skin cookie based on the member preference. ''' pm = getToolByName(self, 'portal_membership') pu = getToolByName(self, 'portal_url') member = pm.getAuthenticatedMember() if hasattr(aq_base(member), 'portal_skin'): mskin = member.portal_skin if mskin: req = self.REQUEST cookie = req.cookies.get(self.request_varname, None) if cookie != mskin: resp = req.RESPONSE portalPath = '/' + pu.getPortalObject().absolute_url(1) if not self.cookie_persistence: # *Don't* make the cookie persistent! resp.setCookie( self.request_varname, mskin, path=portalPath ) else: expires = ( DateTime( 'GMT' ) + 365 ).rfc822() resp.setCookie( self.request_varname , mskin , path=portalPath , expires=expires ) # Ensure updateSkinCookie() doesn't try again # within this request. req.cookies[self.request_varname] = mskin req[self.request_varname] = mskin return 1 return 0
def __call__(self, instance, *args, **kw): ''' Invokes the method. ''' wf = getToolByName(instance, 'portal_workflow', None) if wf is None or not hasattr(wf, 'wrapWorkflowMethod'): # No workflow tool found. try: res = apply(self._m, (instance,) + args, kw) except ObjectDeleted, ex: res = ex.getResult() else: catalog = getToolByName(instance, 'portal_catalog', None) if catalog is not None: catalog.reindexObject(ob)
def reindexObjectSecurity(self, skip_self=False): """Reindex security-related indexes on the object. Recurses in the children to reindex them too. If skip_self is True, only the children will be reindexed. This is a useful optimization if the object itself has just been fully reindexed, as there's no need to reindex its security twice. """ catalog = getToolByName(self, 'portal_catalog', None) if catalog is None: return path = '/'.join(self.getPhysicalPath()) for brain in catalog.unrestrictedSearchResults(path=path): brain_path = brain.getPath() if brain_path == path and skip_self: continue # Get the object if hasattr(aq_base(brain), '_unrestrictedGetObject'): ob = brain._unrestrictedGetObject() else: # BBB: Zope 2.7 ob = self.unrestrictedTraverse(brain_path, None) if ob is None: # BBB: Ignore old references to deleted objects. # Can happen only in Zope 2.7, or when using # catalog-getObject-raises off in Zope 2.8 LOG('reindexObjectSecurity', PROBLEM, "Cannot get %s from catalog" % brain_path) continue # Recatalog with the same catalog uid. s = getattr(ob, '_p_changed', 0) catalog.reindexObject(ob, idxs=self._cmf_security_indexes, update_metadata=0, uid=brain_path) if s is None: ob._p_deactivate()
def wrapUser(self, u, wrap_anon=0): """ Set up the correct acquisition wrappers for a user object. Provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. """ b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) mdtool = getToolByName(self, 'portal_memberdata', None) if mdtool is not None: try: u = mdtool.wrapUser(u) except ConflictError: raise except: logging.exception('CMFCore.MembershipTool', 'Error during wrapUser') return u
def _filteredItems( self, ids, filt ): """ Apply filter, a mapping, to child objects indicated by 'ids', returning a sequence of ( id, obj ) tuples. """ # Restrict allowed content types if filt is None: filt = {} else: # We'll modify it, work on a copy. filt = filt.copy() pt = filt.get('portal_type', []) if type(pt) is type(''): pt = [pt] types_tool = getToolByName(self, 'portal_types') allowed_types = types_tool.listContentTypes() if not pt: pt = allowed_types else: pt = [t for t in pt if t in allowed_types] if not pt: # After filtering, no types remain, so nothing should be # returned. return [] filt['portal_type'] = pt query = ContentFilter(**filt) result = [] append = result.append get = self._getOb for id in ids: obj = get( id ) if query(obj): append( (id, obj) ) return result
def reindexObjectSecurity(self, skip_self=False): """ Reindex security-related indexes on the object (and its descendants). """ catalog = getToolByName(self, 'portal_catalog', None) if catalog is not None: path = '/'.join(self.getPhysicalPath()) for brain in catalog.unrestrictedSearchResults(path=path): brain_path = brain.getPath() # self is treated at the end of the method # Optimization in case of an indexable container if brain_path == path: continue # Get the object ob = brain._unrestrictedGetObject() if ob is None: # Ignore old references to deleted objects. LOG('reindexObjectSecurity', PROBLEM, "Cannot get %s from catalog" % brain_path) continue s = getattr(ob, '_p_changed', 0) catalog.reindexObject(ob, idxs=self._cmf_security_indexes, update_metadata=0) if s is None: ob._p_deactivate() # Reindex the object itself in here if not explicitly # asked to not to if not skip_self: catalog.reindexObject(self, idxs=self._cmf_security_indexes, update_metadata=0)
def getExprContext(context, object=None): request = getattr(context, 'REQUEST', None) if request: cache = request.get('_ec_cache', None) if cache is None: request['_ec_cache'] = cache = {} ec = cache.get( id(object), None ) else: ec = None if ec is None: utool = getToolByName(context, 'portal_url') portal = utool.getPortalObject() if object is None or not hasattr(object, 'aq_base'): folder = portal else: folder = object # Search up the containment hierarchy until we find an # object that claims it's a folder. while folder is not None: if getattr(aq_base(folder), 'isPrincipiaFolderish', 0): # found it. break else: folder = aq_parent(aq_inner(folder)) ec = createExprContext(folder, portal, object) if request: cache[ id(object) ] = ec return ec
def manage_doCustomize(self, folder_path, RESPONSE=None): """Makes a ZODB Based clone with the same data. Calls _createZODBClone for the actual work. """ obj = self._createZODBClone() id = obj.getId() fpath = tuple(split(folder_path, '/')) portal_skins = getToolByName(self,'portal_skins') folder = portal_skins.restrictedTraverse(fpath) if id in folder.objectIds(): # we cant catch the badrequest so # we'll that to check before hand, which makes # sense anyway... obj = folder._getOb(id) if RESPONSE is not None: RESPONSE.redirect('%s/manage_main?manage_tabs_message=%s' % ( obj.absolute_url(), html_quote("An object with this id already exists") )) else: folder._verifyObjectPaste(obj, validate_src=0) folder._setObject(id, obj) if RESPONSE is not None: RESPONSE.redirect('%s/%s/manage_main' % ( folder.absolute_url(), id))
def addMember(self, id, password, roles=('Member',), domains='', properties=None): '''Creates a PortalMember and returns it. The properties argument can be a mapping with additional member properties. Raises an exception if the given id already exists, the password does not comply with the policy in effect, or the authenticated user is not allowed to grant one of the roles listed (where Member is a special role that can always be granted); these conditions should be detected before the fact so that a cleaner message can be printed. ''' if not self.isMemberIdAllowed(id): raise 'Bad Request', 'The login name you selected is already ' \ 'in use or is not valid. Please choose another.' failMessage = self.testPasswordValidity(password) if failMessage is not None: raise 'Bad Request', failMessage failMessage = self.testPropertiesValidity(properties) if failMessage is not None: raise 'Bad Request', failMessage # Limit the granted roles. # Anyone is always allowed to grant the 'Member' role. limitGrantedRoles(roles, self, ('Member',)) membership = getToolByName(self, 'portal_membership') membership.addMember(id, password, roles, domains) member = membership.getMemberById(id) if properties is not None: member.setMemberProperties(properties) self.afterAdd(member, id, password, properties) return member
def manage_addActionForm(self): """Form for adding a new CMF Action object. """ profiles = [] stool = getToolByName(self, 'portal_setup', None) if stool: for info in stool.listContextInfos(): action_paths = [] context = stool._getImportContext(info['id']) body = context.readDataFile('actions.xml') if body is None: continue root = parseString(body).documentElement for node in root.childNodes: if node.nodeName != 'object': continue action_paths += _extractChildren(node) action_paths.sort() profiles.append({'id': info['id'], 'title': info['title'], 'action_paths': tuple(action_paths)}) template = PageTemplateResource('www/addAction.zpt', globals()).__of__(self) return template(profiles=tuple(profiles))
def reindexObjectSecurity(self): """ Reindex security-related indexes on the object (and its descendants). """ catalog = getToolByName(self, 'portal_catalog', None) if catalog is not None: path = '/'.join(self.getPhysicalPath()) for brain in catalog.unrestrictedSearchResults(path=path): brain_path = brain.getPath() # self is treated at the end of the method # Optimization in case of an indexable container if brain_path == path: continue # Get the object if hasattr(aq_base(brain), '_unrestrictedGetObject'): ob = brain._unrestrictedGetObject() else: # BBB older Zope ob = self.unrestrictedTraverse(brain_path, None) if ob is None: # Ignore old references to deleted objects. LOG('reindexObjectSecurity', PROBLEM, "Cannot get %s from catalog" % brain_path) continue s = getattr(ob, '_p_changed', 0) catalog.reindexObject(ob, idxs=['allowedRolesAndUsers'], update_metadata=0) if s is None: ob._p_deactivate() # Reindex the object itself, as the PathIndex only gave us # the descendants. catalog.reindexObject(self, idxs=['allowedRolesAndUsers'], update_metadata=0)
def addMember(self, id, password, roles=('Member',), domains='', properties=None, REQUEST=None): '''Creates a PortalMember and returns it. The properties argument can be a mapping with additional member properties. Raises an exception if the given id already exists, the password does not comply with the policy in effect, or the authenticated user is not allowed to grant one of the roles listed (where Member is a special role that can always be granted); these conditions should be detected before the fact so that a cleaner message can be printed. ''' # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool if not self.isMemberIdAllowed(id): raise ValueError(_(u'The login name you selected is already in ' u'use or is not valid. Please choose another.')) failMessage = self.testPasswordValidity(password) if failMessage is not None: raise ValueError(failMessage) if properties is not None: failMessage = self.testPropertiesValidity(properties) if failMessage is not None: raise ValueError(failMessage) # Limit the granted roles. # Anyone is always allowed to grant the 'Member' role. _limitGrantedRoles(roles, self, ('Member',)) membership = getToolByName(self, 'portal_membership') membership.addMember(id, password, roles, domains, properties) member = membership.getMemberById(id) self.afterAdd(member, id, password, properties) return member
def searchMembers( self, search_param, search_term ): """ Search the membership """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool md = getToolByName( self, 'portal_memberdata' ) return md.searchMemberData( search_param, search_term )
def createCPContext( content, view_method, keywords, time=None ): """ Construct an expression context for TALES expressions, for use by CachingPolicy objects. """ pm = getToolByName( content, 'portal_membership', None ) if not pm or pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() if time is None: time = DateTime() # The name "content" is deprecated and will go away in CMF 1.7, # please use "object" in your policy data = { 'content' : content , 'object' : content , 'view' : view_method , 'keywords' : keywords , 'request' : getattr( content, 'REQUEST', {} ) , 'member' : member , 'modules' : SecureModuleImporter , 'nothing' : None , 'time' : time } return getEngine().getContext( data )
def invokeFactory(self, type_name, id, RESPONSE=None, *args, **kw): ''' Invokes the portal_types tool. ''' pt = getToolByName(self, 'portal_types') apply(pt.constructContent, (type_name, self, id, RESPONSE) + args, kw)
def getDefaultChainFor(self, ob): types_tool = getToolByName( self, 'portal_types', None ) if ( types_tool is not None and types_tool.getTypeInfo( ob ) is not None ): return self._default_chain return ()
def createExprContext(folder, portal, object): ''' An expression context provides names for TALES expressions. ''' pm = getToolByName(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() if pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), 'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, 'portal': portal, 'nothing': None, 'request': getattr( object, 'REQUEST', None ), 'modules': SecureModuleImporter, 'member': member, } return getEngine().getContext(data)
def notifyWorkflowCreated(self): """ Notify the workflow that self was just created. """ wftool = getToolByName(self, 'portal_workflow', None) if wftool is not None: wftool.notifyCreated(self)
def manage_workflowsTab(self, REQUEST, manage_tabs_message=None): """ Tab displaying the current workflows for the content object. """ ob = self wftool = getToolByName(self, 'portal_workflow', None) # XXX None ? if wftool is not None: wf_ids = wftool.getChainFor(ob) states = {} chain = [] for wf_id in wf_ids: wf = wftool.getWorkflowById(wf_id) if wf is not None: # XXX a standard API would be nice if hasattr(wf, 'getReviewStateOf'): # Default Workflow state = wf.getReviewStateOf(ob) elif hasattr(wf, '_getWorkflowStateOf'): # DCWorkflow state = wf._getWorkflowStateOf(ob, id_only=1) else: state = '(Unknown)' states[wf_id] = state chain.append(wf_id) return self._manage_workflowsTab( REQUEST, chain=chain, states=states, management_view='Workflows', manage_tabs_message=manage_tabs_message)
def indexObject(self): """ Index the object in the portal catalog. """ catalog = getToolByName(self, 'portal_catalog', None) if catalog is not None: catalog.indexObject(self)
def unindexObject(self): """ Unindex the object from the portal catalog. """ catalog = getToolByName(self, 'portal_catalog', None) if catalog is not None: catalog.unindexObject(self)
def manage_addTypeInfo(dispatcher, add_meta_type, id, settings_id='', REQUEST=None): """Add a new TypeInformation object of type 'add_meta_type' with ID 'id'. """ settings_node = None if settings_id: stool = getToolByName(dispatcher, 'portal_setup', None) if stool: profile_id, type_id = settings_id.split('/') context = stool._getImportContext(profile_id) filenames = context.listDirectory('types') for filename in filenames or (): body = context.readDataFile(filename, subdir='types') if body is not None: root = parseString(body).documentElement if root.getAttribute('name') != type_id: continue if root.getAttribute('meta_type') == add_meta_type: settings_node = root if not id: id = type_id break for mt in Products.meta_types: if mt['name'] == add_meta_type: klass = mt['instance'] break else: raise ValueError('Meta type %s is not a type class.' % add_meta_type) obj = klass(id) if settings_node: INodeImporter(obj).importNode(settings_node) dispatcher._setObject(id, obj) if REQUEST: return dispatcher.manage_main(dispatcher, REQUEST)
def searchMemberDataContents( self, search_param, search_term ): """ Search members. This method will be deprecated soon. """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool res = [] if search_param == 'username': search_param = 'id' mtool = getToolByName(self, 'portal_membership') for member_id in self._members.keys(): user_wrapper = mtool.getMemberById( member_id ) if user_wrapper is not None: memberProperty = user_wrapper.getProperty searched = memberProperty( search_param, None ) if searched is not None and searched.find(search_term) != -1: res.append( { 'username': memberProperty( 'id' ) , 'email' : memberProperty( 'email', '' ) } ) return res
def _getProfileInfo(dispatcher, meta_type): profiles = [] stool = getToolByName(dispatcher, 'portal_setup', None) if stool: for info in stool.listContextInfos(): type_ids = [] context = stool._getImportContext(info['id']) filenames = context.listDirectory('types') if filenames is None: continue for filename in filenames: body = context.readDataFile(filename, subdir='types') if body is None: continue root = parseString(body).documentElement if root.getAttribute('meta_type') == meta_type: type_id = root.getAttribute('name') type_ids.append(type_id) if not type_ids: continue type_ids.sort() profiles.append({'id': info['id'], 'title': info['title'], 'type_ids': tuple(type_ids)}) return tuple(profiles)
def searchMemberData(self, search_param, search_term, attributes=()): """ Search members. """ res = [] if not search_param: return res membership = getToolByName(self, 'portal_membership') if len(attributes) == 0: attributes = ('id', 'email') if search_param == 'username': search_param = 'id' for user_id in self._members.keys(): u = membership.getMemberById(user_id) if u is not None: memberProperty = u.getProperty searched = memberProperty(search_param, None) if searched is not None and searched.find(search_term) != -1: user_data = {} for desired in attributes: if desired == 'id': user_data['username'] = memberProperty(desired, '') else: user_data[desired] = memberProperty(desired, '') res.append(user_data) return res
def getTypeInfo(self): """ Get the TypeInformation object specified by the portal type. """ tool = getToolByName(self, 'portal_types', None) if tool is None: return None return tool.getTypeInfo(self) # Can return None.
def _uuid_unregister(self, reference_manager=None): """remove all references""" if not reference_manager: reference_manager = getToolByName(self, REFERENCE_MANAGER, None) if reference_manager is not None: reference_manager.unregisterObject(self)
def getBRefs(self, relationship=None): """get all the back referenced objects for this object""" tool = getToolByName(self, REFERENCE_MANAGER) refs = tool.getBackReferences(self, relationship) if refs: return [ref.getSourceObject() for ref in refs] return []
def wrapUser(self, u, wrap_anon=0): ''' Sets up the correct acquisition wrappers for a user object and provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. ''' b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u parent = self.aq_inner.aq_parent base = getattr(parent, 'aq_base', None) if hasattr(base, 'portal_memberdata'): # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) # Get portal_memberdata to do the wrapping. md = getToolByName(parent, 'portal_memberdata') try: portal_user = md.wrapUser(u) # Check for the member area creation flag and # take appropriate (non-) action if getattr(self, 'memberareaCreationFlag', 0) != 0: if self.getHomeUrl(portal_user.getId()) is None: self.createMemberarea(portal_user.getId()) return portal_user except: from zLOG import LOG, ERROR import sys type,value,tb = sys.exc_info() try: LOG('CMFCore.MembershipTool', ERROR, 'Error during wrapUser:', "\nType:%s\nValue:%s\n" % (type,value)) finally: tb = None # Avoid leaking frame pass # Failed. return u
def getDefaultChainFor(self, ob): """ Get the default chain, if applicable, for ob. """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool types_tool = getToolByName( self, 'portal_types', None ) if ( types_tool is not None and types_tool.getTypeInfo( ob ) is not None ): return self._default_chain return ()
def listContentTypes(self, by_meta_type=0): """ List all registered portal content types. """ mtSet = {} for info in getToolByName(self, 'portal_types').listTypeInfo(): if by_meta_type: mtSet[info.Metatype()] = 1 else: mtSet[info.Type()] = 1 return mtSet.keys()
def _listTypeInfo(self): """ List the portal types which are available. """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool pt = getToolByName(self, 'portal_types', None) if pt is None: return () else: return pt.listTypeInfo()
def setProperties(self, properties=None, **kw): '''Allows the authenticated member to set his/her own properties. Accepts either keyword arguments or a mapping for the "properties" argument. ''' # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool if properties is None: properties = kw membership = getToolByName(self, 'portal_membership') registration = getToolByName(self, 'portal_registration', None) if not membership.isAnonymousUser(): member = membership.getAuthenticatedMember() if registration: failMessage = registration.testPropertiesValidity(properties, member) if failMessage is not None: raise BadRequest(failMessage) member.setMemberProperties(properties) else: raise BadRequest('Not logged in.')
def isDiscussionAllowedFor(self, content): ''' Returns a boolean indicating whether a discussion is allowed for the specified content. ''' if hasattr(content, 'allow_discussion'): return content.allow_discussion typeInfo = getToolByName(self, 'portal_types').getTypeInfo(content) if typeInfo: return typeInfo.allowDiscussion() return 0
def isMemberIdAllowed(self, id): '''Returns 1 if the ID is not in use and is not reserved. ''' if len(id) < 1 or id == 'Anonymous User': return 0 if not self.__ALLOWED_MEMBER_ID_PATTERN.match(id): return 0 membership = getToolByName(self, 'portal_membership') if membership.getMemberById(id) is not None: return 0 return 1
def invokeFactory(self, type_name, id, RESPONSE=None, *args, **kw): """ Invokes the portal_types tool. """ pt = getToolByName(self, 'portal_types') myType = pt.getTypeInfo(self) if myType is not None: if not myType.allowType( type_name ): raise ValueError('Disallowed subobject type: %s' % type_name) return pt.constructContent(type_name, self, id, RESPONSE, *args, **kw)
def deleteMembers(self, member_ids, delete_memberareas=1, delete_localroles=1): """ Delete members specified by member_ids. """ # Delete members in acl_users. acl_users = self.acl_users if _checkPermission(ManageUsers, acl_users): if type(member_ids) is StringType: member_ids = (member_ids,) member_ids = list(member_ids) for member_id in member_ids[:]: if not acl_users.getUserById(member_id, None): member_ids.remove(member_id) try: acl_users.userFolderDelUsers(member_ids) except (NotImplementedError, 'NotImplemented'): raise NotImplementedError('The underlying User Folder ' 'doesn\'t support deleting members.') else: raise AccessControl_Unauthorized('You need the \'Manage users\' ' 'permission for the underlying User Folder.') # Delete member data in portal_memberdata. mdtool = getToolByName(self, 'portal_memberdata', None) if mdtool is not None: for member_id in member_ids: mdtool.deleteMemberData(member_id) # Delete members' home folders including all content items. if delete_memberareas: for member_id in member_ids: self.deleteMemberArea(member_id) # Delete members' local roles. if delete_localroles: utool = getToolByName(self, 'portal_url', None) self.deleteLocalRoles( utool.getPortalObject(), member_ids, reindex=1, recursive=1 ) return tuple(member_ids)
def setPassword(self, password, domains=None): '''Allows the authenticated member to set his/her own password. ''' membership = getToolByName(self, 'portal_membership') if not membership.isAnonymousUser(): member = membership.getAuthenticatedMember() failMessage = self.testPasswordValidity(password) if failMessage is not None: raise 'Bad Request', failMessage member.setSecurityProfile(password=password, domains=domains) else: raise 'Bad Request', 'Not logged in.'
def manage_afterAdd(self, item, container): """ Add self to the workflow and catalog. """ # # Are we being added (or moved)? # if aq_base(container) is not aq_base(self): wf = getToolByName(self, 'portal_workflow', None) if wf is not None: wf.notifyCreated(self) self.indexObject()
def pruneMemberDataContents(self): """ Delete data contents of all members not listet in acl_users. """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool membertool = getToolByName(self, 'portal_membership') members = self._members user_list = membertool.listMemberIds() for member_id in list(members.keys()): if member_id not in user_list: del members[member_id]
def invokeFactory(self, type_name, id, RESPONSE=None, *args, **kw): ''' Invokes the portal_types tool. ''' pt = getToolByName(self, 'portal_types') myType = pt.getTypeInfo(self) if myType is not None: if not myType.allowType(type_name): raise ValueError, 'Disallowed subobject type: %s' % type_name apply(pt.constructContent, (type_name, self, id, RESPONSE) + args, kw)
def __call__(self, instance, *args, **kw): ''' Invokes the method. ''' wf = getToolByName(instance, 'portal_workflow', None) if wf is None or not hasattr(wf, 'wrapWorkflowMethod'): # No workflow found. res = apply(self._m, (instance, ) + args, kw) else: res = wf.wrapWorkflowMethod(instance, self._id, self._m, (instance, ) + args, kw) return res
def pruneMemberDataContents(self): """ Delete data contents of all members not listet in acl_users. """ membertool = getToolByName(self, 'portal_membership') members = self._members user_list = membertool.listMemberIds() for tuple in members.items(): member_name = tuple[0] member_obj = tuple[1] if member_name not in user_list: del members[member_name]
def doTestRegistry(self, name, content_type, body, REQUEST): """ """ typeName = self.findTypeName(name, content_type, body) if typeName is None: typeName = '<unknown>' else: types_tool = getToolByName(self, 'portal_types') typeName = types_tool.getTypeInfo(typeName).Title() REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_testRegistry' + '?testResults=Type:+%s' % urllib.quote(typeName))
def _uuid_register(self, reference_manager=None): """get a uuid that can be used for references""" uuid = getattr(self, UUID_ATTR, None) if uuid: return uuid if not reference_manager: reference_manager = getToolByName(self, REFERENCE_MANAGER, None) if reference_manager is not None: reference_manager.registerObject(self) uc = getattr(reference_manager, UID_MANAGER) uc.catalog_object(self, '/'.join(self.getPhysicalPath()))
def setPassword(self, password, domains=None): '''Allows the authenticated member to set his/her own password. ''' registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise BadRequest(failMessage) member.setSecurityProfile(password=password, domains=domains) else: raise BadRequest('Not logged in.')
def setReviewStateOf(self, ob, review_state, action, comment): tool = aq_parent(aq_inner(self)) tool.notifyBefore(ob, action) try: pm = getToolByName(self, 'portal_membership') current_user = pm.getAuthenticatedMember().getUserName() status = { 'actor': current_user, 'action': action, 'review_state': review_state, 'time': DateTime(), 'comments': comment, } tool.setStatusOf(self.id, ob, status) except: tool.notifyException(ob, action, sys.exc_info()) raise else: tool.notifySuccess(ob, action) catalog = getToolByName(self, 'portal_catalog', None) if catalog is not None: catalog.reindexObject(ob)
def traverse(self, name, ignored): ttool = getToolByName(self.context, 'portal_types') ti = ttool.getTypeInfo(name) if ti is not None: add_view = queryMultiAdapter((self.context, self.request, ti), name=ti.factory) if add_view is None: add_view = queryMultiAdapter((self.context, self.request, ti)) if add_view is not None: add_view.__name__ = ti.factory return add_view.__of__(self.context) raise TraversalError(self.context, name)
def isMemberIdAllowed(self, id): '''Returns 1 if the ID is not in use and is not reserved. ''' # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool if len(id) < 1 or id == 'Anonymous User': return 0 if not self._ALLOWED_MEMBER_ID_PATTERN.match(id): return 0 membership = getToolByName(self, 'portal_membership') if membership.getMemberById(id) is not None: return 0 return 1
def __call__(self, instance, *args, **kw): """ Invoke the wrapped method, and deal with the results. """ wf = getToolByName(instance, 'portal_workflow', None) if wf is None or not hasattr(wf, 'wrapWorkflowMethod'): # No workflow tool found. try: res = self._m(instance, *args, **kw) except ObjectDeleted, ex: res = ex.getResult() else: if hasattr(aq_base(instance), 'reindexObject'): instance.reindexObject()
def __call__(self, instance, *args, **kw): ''' Invokes the method. ''' wf = getToolByName(instance, 'portal_workflow', None) if wf is None: # No workflow found. return apply(self._m, (instance, ) + args, kw) else: action = self._a wf.notifyBefore(instance, action) # Can throw an exception. try: res = apply(self._m, (instance, ) + args, kw) except: wf.notifyException(instance, action, sys.exc_info()) raise else: wf.notifySuccess(instance, action, res) if self._reindex: catalog = getToolByName(instance, 'portal_catalog', None) if catalog is not None: catalog.reindexObject(instance) return res
def invokeFactory( self , type_name , id , RESPONSE=None , *args , **kw ): ''' Invokes the portal_types tool. ''' pt = getToolByName( self, 'portal_types' ) apply( pt.constructContent , (type_name, self, id, RESPONSE) + args , kw )
def setPassword(self, password, domains=None, REQUEST=None): '''Allows the authenticated member to set his/her own password. ''' # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise BadRequest(failMessage) member.setSecurityProfile(password=password, domains=domains) else: raise BadRequest('Not logged in.')
def doTestRegistry(self, name, content_type, body, REQUEST): """ """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool typeName = self.findTypeName(name, content_type, body) if typeName is None: typeName = '<unknown>' else: types_tool = getToolByName(self, 'portal_types') typeName = types_tool.getTypeInfo(typeName).Title() REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_testRegistry' + '?testResults=Type:+%s' % urllib.quote(typeName))
def catalog_object(self, obj, uid=None, idxs=None, update_metadata=1, pghandler=None): # Wraps the object with workflow and accessibility # information just before cataloging. wftool = getToolByName(self, 'portal_workflow', None) if wftool is not None: vars = wftool.getCatalogVariablesFor(obj) else: vars = {} w = IndexableObjectWrapper(vars, obj) ZCatalog.catalog_object(self, w, uid, idxs, update_metadata, pghandler)
def pruneMemberDataContents(self): ''' Compare the user IDs stored in the member data tool with the list in the actual underlying acl_users and delete anything not in acl_users ''' membertool = getToolByName(self, 'portal_membership') members = self._members user_list = membertool.listMemberIds() for tuple in members.items(): member_name = tuple[0] member_obj = tuple[1] if member_name not in user_list: del members[member_name]
def wrapUser(self, u, wrap_anon=0): ''' Sets up the correct acquisition wrappers for a user object and provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. ''' b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u parent = self.aq_inner.aq_parent base = getattr(parent, 'aq_base', None) if hasattr(base, 'portal_memberdata'): # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) # Get portal_memberdata to do the wrapping. md = getToolByName(parent, 'portal_memberdata') try: portal_user = md.wrapUser(u) # Check for the member area creation flag and # take appropriate (non-) action if getattr(self, 'memberareaCreationFlag', 0) != 0: if self.getHomeUrl(portal_user.getId()) is None: self.createMemberarea(portal_user.getId()) return portal_user except: # DEBUGGING CODE import traceback traceback.print_exc() pass # Failed. return u
def deleteMembers(self, member_ids, delete_memberareas=1, delete_localroles=1, REQUEST=None): """ Delete members specified by member_ids. """ # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool # Delete members in acl_users. acl_users = self.acl_users if _checkPermission(ManageUsers, acl_users): if isinstance(member_ids, basestring): member_ids = (member_ids, ) member_ids = list(member_ids) for member_id in member_ids[:]: if not acl_users.getUserById(member_id, None): member_ids.remove(member_id) try: acl_users.userFolderDelUsers(member_ids) except (AttributeError, NotImplementedError, 'NotImplemented'): raise NotImplementedError('The underlying User Folder ' 'doesn\'t support deleting members.') else: raise AccessControl_Unauthorized( 'You need the \'Manage users\' ' 'permission for the underlying User Folder.') # Delete member data in portal_memberdata. mdtool = getToolByName(self, 'portal_memberdata', None) if mdtool is not None: for member_id in member_ids: mdtool.deleteMemberData(member_id) # Delete members' home folders including all content items. if delete_memberareas: for member_id in member_ids: self.deleteMemberArea(member_id) # Delete members' local roles. if delete_localroles: self.deleteLocalRoles(getUtility(ISiteRoot), member_ids, reindex=1, recursive=1) return tuple(member_ids)