def test_id_clean(self): from Products.PlonePAS.utils import cleanId, decleanId a = [ "asdfasdf", "asdf-asdf", "asdf--asdf", "asdf---asdf", "asdf----asdf", "asdf-----asdf", "asdf%asdf", "asdf%%asdf", "asdf%%%asdf", "asdf%%%%asdf", "asdf%%%%%asdf", "asdf-%asdf", "asdf%-asdf", "asdf-%-asdf", "asdf%-%asdf", "asdf--%asdf", "asdf%--asdf", "asdf--%-asdf", "asdf-%--asdf", "asdf--%--asdf", "asdf%-%asdf", "asdf%--%asdf", "asdf%---%asdf", "-asdf", "--asdf", "---asdf", "----asdf", "-----asdf", "asdf-", "asdf--", "asdf---", "asdf----", "asdf-----", "%asdf", "%%asdf", "%%%asdf", "%%%%asdf", "%%%%%asdf", "asdf%", "asdf%%", "asdf%%%", "asdf%%%%", "asdf%%%%%", "asdf\x00asdf", ] b = [cleanId(id) for id in a] c = [decleanId(id) for id in b] ac = zip(a, c) for aa, cc in ac: self.assertTrue(aa == cc) cleaned = cleanId(u'abc') self.assertEqual(cleaned, 'abc') self.assertTrue(isinstance(cleaned, str)) if six.PY2: self.assertFalse(isinstance(cleaned, six.text_type))
def test_id_clean(self): from Products.PlonePAS.utils import cleanId, decleanId a = [ "asdfasdf", "asdf-asdf", "asdf--asdf", "asdf---asdf", "asdf----asdf", "asdf-----asdf", "asdf%asdf", "asdf%%asdf", "asdf%%%asdf", "asdf%%%%asdf", "asdf%%%%%asdf", "asdf-%asdf", "asdf%-asdf", "asdf-%-asdf", "asdf%-%asdf", "asdf--%asdf", "asdf%--asdf", "asdf--%-asdf", "asdf-%--asdf", "asdf--%--asdf", "asdf%-%asdf", "asdf%--%asdf", "asdf%---%asdf", "-asdf", "--asdf", "---asdf", "----asdf", "-----asdf", "asdf-", "asdf--", "asdf---", "asdf----", "asdf-----", "%asdf", "%%asdf", "%%%asdf", "%%%%asdf", "%%%%%asdf", "asdf%", "asdf%%", "asdf%%%", "asdf%%%%", "asdf%%%%%", "asdf\x00asdf", ] b = [cleanId(id) for id in a] c = [decleanId(id) for id in b] ac = zip(a, c) for aa, cc in ac: self.assertTrue(aa == cc) cleaned = cleanId(u"abc") self.assertEqual(cleaned, "abc") self.assertTrue(isinstance(cleaned, str)) self.assertFalse(isinstance(cleaned, unicode))
def prepareid(values): logger = logging.getLogger('rctsync.people') fn = values['fields']['first_name'].encode('utf8') ln = values['fields']['last_name'].encode('utf8') id = "%s-%s" % (fn,ln) id = id.replace(' ','') if id == '-': generated = "rct-user-%s" % values['pk'] message = "auth.user '%s' has no name set. Using '%s' instead." \ % (values['pk'], generated) logger.warning(message) return cleanId(generated) logger.debug("Generating id based on '%s'" % id) return cleanId(id)
def addImplementationDetails(site, impl, data, logger): """Adding implementation details to a service component implementation""" logger.debug("addImplemenationDetails called with this data: '%s'" % data) id = cleanId('version-' + data['version']) if id not in impl.contentIds(): impl.invokeFactory('ServiceComponentImplementationDetails', id) logger.info( "Adding service component implementation details '%s' to '%s'" % (id, impl.Title())) details = impl[id] data['title'] = 'Version ' + data['version'] data['description'] = 'Implementation details of ' + impl.Title( ) + ': version ' + data['version'] data['identifiers'] = [ { 'type': 'spmt_uid', 'value': data['uuid'] }, ] raw_config_data = data['configuration_parameters'] if raw_config_data is not None: config_items = raw_config_data.splitlines() keys = [item.split()[0] for item in config_items] data['configuration_parameters'] = keys else: data['configuration_parameters'] = [] details.edit(**data) details.reindexObject() site.portal_repository.save(obj=details, comment="Synchronization from SPMT") logger.info("Updated '%s': implementation of '%s'" % (data['title'], impl.Title()))
def addImplementationDetails(site, impl, data, logger): """Adding implementation details to a service component implementation""" logger.debug("addImplemenationDetails called with this data: '%s'" % data) id = cleanId('version-' + data['version']) if id not in impl.contentIds(): impl.invokeFactory('ServiceComponentImplementationDetails', id) logger.info("Adding service component implementation details '%s' to '%s'" % (id, impl.Title())) details = impl[id] data['title'] = 'Version ' + data['version'] data['description'] = 'Implementation details of ' + impl.Title() + ': version ' + data['version'] data['identifiers'] = [{'type':'spmt_uid', 'value': data['uuid']}, ] raw_config_data = data['configuration_parameters'] if raw_config_data is not None: config_items = raw_config_data.splitlines() keys = [item.split()[0] for item in config_items] data['configuration_parameters'] = keys else: data['configuration_parameters'] = [] details.edit(**data) details.reindexObject() site.portal_repository.save(obj=details, comment="Synchronization from SPMT") logger.info("Updated '%s': implementation of '%s'" % (data['title'], impl.Title()))
def addComponent(service, site, data, logger): """Adding a service component to 'service' described by 'data'""" logger.debug("addComponent called with this data: '%s'" % data) id = cleanId(data['name']) if id not in service.contentIds(): service.invokeFactory('ServiceComponent', id) logger.info("Adding service component '%s' to '%s'" % (id, service.Title())) component = service[id] data['title'] = "Service component '%s'" % data['name'] data['identifiers'] = [ { 'type': 'spmt_uid', 'value': data['uuid'] }, ] component.edit(**data) component.reindexObject() site.portal_repository.save(obj=component, comment="Synchronization from SPMT") logger.info("Updated '%s' component of '%s'" % (data['name'], service.Title())) implementations_data = utils.getDataFromSPMT( data['service_component_implementations_link']['related']['href']) # print implementations_data implementations = implementations_data[ 'service_component_implementations_list'][ 'service_component_implementations'] if not implementations: logger.info("No implemenations found for '%s'" % data['title']) return for implementation in implementations: addImplementation(site, component, implementation, logger)
def addComponent(service, site, data, logger): """Adding a service component to 'service' described by 'data'""" logger.debug("addComponent called with this data: '%s'" % data) id = cleanId(data['name']) if id not in service.contentIds(): service.invokeFactory('ServiceComponent', id) logger.info("Adding service component '%s' to '%s'" % (id, service.Title())) component = service[id] data['title'] = "Service component '%s'" % data['name'] data['identifiers'] = [{'type':'spmt_uid', 'value': data['uuid']}, ] component.edit(**data) component.reindexObject() site.portal_repository.save(obj=component, comment="Synchronization from SPMT") logger.info("Updated '%s' component of '%s'" % (data['name'], service.Title())) implementations_data = utils.getDataFromSPMT(data['service_component_implementations_link']['related']['href']) # print implementations_data implementations = implementations_data['service_component_implementations_list']['service_component_implementations'] if not implementations: logger.info("No implemenations found for '%s'" % data['title']) return for implementation in implementations: addImplementation(site, component, implementation, logger)
def addImplementation(site, component, data, logger): """Adding an implementation to a service component""" logger.debug("addImplemenation called with this data: '%s'" % data) id = cleanId(data['name']) if id not in component.contentIds(): component.invokeFactory('ServiceComponentImplementation', id) logger.info("Adding service component implementation '%s' to '%s'" % (id, component.Title())) implementation = component[id] data['title'] = component.Title() + ' implementation: ' + data['name'] data['identifiers'] = [ { 'type': 'spmt_uid', 'value': data['uuid'] }, ] implementation.edit(**data) implementation.reindexObject() site.portal_repository.save(obj=implementation, comment="Synchronization from SPMT") logger.info("Updated '%s': implementation of '%s'" % (data['name'], component.Title())) details_data = utils.getDataFromSPMT( data['component_implementation_details_link']['related']['href']) details = details_data['service_component_implementation_details_list'][ 'service_component_implementation_details'] if not details: logger.info("No implemenation details found for '%s'" % data['title']) return for detail in details: addImplementationDetails(site, implementation, detail, logger)
def memberLookup(self, mtool, uid): member = mtool.getMemberById(uid) if member is None: for m in mtool.listMemberIds(): m2 = mtool.getMemberById(m) if m2.getUserName() == uid: uid = cleanId(m) member = m2 break return (member, uid)
def applyChanges(self, data): context = aq_inner(self.context) mtool = getToolByName(context, 'portal_membership') member = mtool.getAuthenticatedMember() member.setMemberProperties({ 'fullname': data['fullname'], 'location': data['location'], 'home_page': data['home_page'], 'organization': data['organization'], 'presslink': data['presslink']}) image_file = data['portrait'] if image_file: portrait = StringIO(image_file.data) scaled, mimetype = scale_image(portrait) portrait = Image(id=cleanId(member.getId()), file=scaled, title='') mdata = getToolByName(context, 'portal_memberdata') mdata._setPortrait(portrait, cleanId(member.getId())) IStatusMessage(self.request).addStatusMessage( _(u"Member information has been updated successfully."), type='info') return self.request.response.redirect(context.absolute_url())
def createMemberArea(logged_in): """Use the template if available""" if not hasattr(logged_in.principal, 'Members'): return safe_member_id = utils.cleanId(logged_in.principal.getId()) container = logged_in.principal.Members if container.hasObject(safe_member_id): return createObjectAsPortalOwner( container, type_name=container.portal_membership.memberarea_type, id_=safe_member_id)
def test_id_clean(self): from Products.PlonePAS.utils import cleanId, decleanId a = [ "asdfasdf", "asdf-asdf", "asdf--asdf", "asdf---asdf", "asdf----asdf", "asdf-----asdf", "asdf%asdf", "asdf%%asdf", "asdf%%%asdf", "asdf%%%%asdf", "asdf%%%%%asdf", "asdf-%asdf", "asdf%-asdf", "asdf-%-asdf", "asdf%-%asdf", "asdf--%asdf", "asdf%--asdf", "asdf--%-asdf", "asdf-%--asdf", "asdf--%--asdf", "asdf%-%asdf", "asdf%--%asdf", "asdf%---%asdf", "-asdf", "--asdf", "---asdf", "----asdf", "-----asdf", "asdf-", "asdf--", "asdf---", "asdf----", "asdf-----", "%asdf", "%%asdf", "%%%asdf", "%%%%asdf", "%%%%%asdf", "asdf%", "asdf%%", "asdf%%%", "asdf%%%%", "asdf%%%%%", "asdf\x00asdf", ] b = [cleanId(id) for id in a] c = [decleanId(id) for id in b] ac = zip(a, c) for aa, cc in ac: self.assertTrue(aa == cc)
def _getSafeMemberId(self, id=None): """Return a safe version of a member id. If no id is given return the id for the currently authenticated user. """ if id is None: member = self.getAuthenticatedMember() if not hasattr(member, 'getMemberId'): return None id = member.getMemberId() return cleanId(id)
def portrait_for(self, username, use_default=False): """ Get portrait object for username, or return None (if use_default is False). If use_default is True and no portrait exists, return the default. """ userid = self.userid_for(username) portrait = self._memberdata_tool()._getPortrait(cleanId(userid)) if portrait is None or isinstance(portrait, str): if use_default: return getattr(self.portal, default_portrait, None) return None return portrait
def portrait_for(self, username, use_default=False): """ Get portrait object for username, or return None (if use_default is False). If use_default is True and no portrait exists, return the default. """ username = self.applyTransform(username) userid = self.userid_for(username) portrait = self._memberdata_tool()._getPortrait(cleanId(userid)) if portrait is None or isinstance(portrait, str): if use_default: return getattr(self.portal, default_portrait, None) return None return portrait
def resolveDependencies(site, data): """Resolve dependencies by looking up the UIDs of the respective services. It is assumed that the services are there and can be looked up by name in the 'catalog' folder.""" deps = data['dependencies_list']['services'] if not deps: data['dependencies'] = [] else: dependencies = [] for dep in deps: name = dep['service']['name'] uid = site['catalog'][cleanId(name)].UID() dependencies.append(uid) data['dependencies'] = dependencies return data
def __call__(self, *args, **kw): if self.request.get('submit'): mtool = getToolByName(self.context, 'portal_membership') portrait = self.request.form.get('portrait') if (portrait and portrait.filename): portal = api.portal.get() profiles = portal.profiles profile = mtool.getAuthenticatedMember().getId() scaled, mimetype = scale_image(portrait) img = Image(id=cleanId(profile), file=scaled, title='') image = NamedBlobImage( data=str(img.data), filename=portrait.filename.decode('utf-8')) getattr(profiles, profile).portrait = image IStatusMessage(self.request).add(_( "Personal image updated. Keep browsing or reload the " "page to see the change."), type="success") # purge varnish portrait_url = mtool.getPersonalPortrait( profile).absolute_url() try: requests.request("PURGE", portrait_url, verify=False, timeout=3) except (requests.exceptions.RequestException, requests.exceptions.SSLError) as e: # Attempt to purge failed. Log and continue. logging.exception(e) redirect = self.request['HTTP_REFERER'] or \ self.context.absolute_url() self.request.RESPONSE.setHeader("X-Patterns-Redirect-Url", redirect) self.request['disable_toolbar'] = True return super(PersonalTools, self).__call__(*args, **kw)
def makeGenericContact(site, fields, contact_type='generic'): logger = logging.getLogger('contacts') try: provider_id = fields['shortname'] except KeyError: parentsite_id = fields['parentsite_id'] provider_id = config.cid2dpid[int(parentsite_id)] if contact_type == 'security': email = fields['csirtemail'] phone = {'type': 'Office', 'number': fields['csirttel']} lastname = "Security Contact" elif contact_type == 'support': email = fields['email'] phone = {} lastname = "Support Contact" else: email = fields['email'] phone = {'type': 'Office', 'number': fields['telephone']} lastname = "Contact" title = ' '.join([provider_id, lastname]) id = cleanId(title) description = "Generic %s details for %s" % (lastname.lower(), provider_id) data = { 'title': title, 'description': description, 'name': dict(firstname=provider_id, lastname=lastname), 'email': email, 'phone': [phone], } if id in site.people.objectIds(): return site.people[id].UID() site.people.invokeFactory('Person', id) logger.info("Added %s to the people folder" % id) site.people[id].edit(**data) logger.debug(data) logger.info("Updated %s in the people folder" % id) site.people[id].reindexObject() return site.people[id].UID()
def makeGenericContact(site, fields, contact_type='generic'): logger = logging.getLogger('contacts') try: provider_id = fields['shortname'] except KeyError: parentsite_id = fields['parentsite_id'] provider_id = config.cid2dpid[int(parentsite_id)] if contact_type == 'security': email = fields['csirtemail'] phone = {'type':'Office', 'number':fields['csirttel']} lastname = "Security Contact" elif contact_type == 'support': email = fields['email'] phone = {} lastname = "Support Contact" else: email = fields['email'] phone = {'type':'Office','number':fields['telephone']} lastname = "Contact" title = ' '.join([provider_id, lastname]) id = cleanId(title) description = "Generic %s details for %s" % (lastname.lower(), provider_id) data = {'title':title, 'description':description, 'name':dict(firstname=provider_id, lastname=lastname), 'email':email, 'phone':[phone], } if id in site.people.objectIds(): return site.people[id].UID() site.people.invokeFactory('Person', id) logger.info("Added %s to the people folder" % id) site.people[id].edit(**data) logger.debug(data) logger.info("Updated %s in the people folder" % id) site.people[id].reindexObject() return site.people[id].UID()
def addImplementation(site, component, data, logger): """Adding an implementation to a service component""" logger.debug("addImplemenation called with this data: '%s'" % data) id = cleanId(data['name']) if id not in component.contentIds(): component.invokeFactory('ServiceComponentImplementation', id) logger.info("Adding service component implementation '%s' to '%s'" % (id, component.Title())) implementation = component[id] data['title'] = component.Title() + ' implementation: ' + data['name'] data['identifiers'] = [{'type':'spmt_uid', 'value': data['uuid']}, ] implementation.edit(**data) implementation.reindexObject() site.portal_repository.save(obj=implementation, comment="Synchronization from SPMT") logger.info("Updated '%s': implementation of '%s'" % (data['name'], component.Title())) details_data = utils.getDataFromSPMT(data['component_implementation_details_link']['related']['href']) details = details_data['service_component_implementation_details_list']['service_component_implementation_details'] if not details: logger.info("No implemenation details found for '%s'" % data['title']) return for detail in details: addImplementationDetails(site, implementation, detail, logger)
def quote_userid(user_id): if isinstance(user_id, unicode): user_id = user_id.encode('utf-8') return cleanId(user_id)
def prepareid(values): #id = values['fields']['name'].encode('utf8') #id = id.replace(' ','') id = 'she' # there should only be one per provider return cleanId(id)
def createMemberarea(self, member_id=None, minimal=True): """ Create a member area for 'member_id' or the authenticated user, but don't assume that member_id is url-safe. Unfortunately, a pretty close copy of the (very large) original and only a few lines different. Plone should probably do this. """ if not self.getMemberareaCreationFlag(): return None catalog = getToolByName(self, 'portal_catalog') membership = getToolByName(self, 'portal_membership') members = self.getMembersFolder() if not member_id: # member_id is optional (see CMFCore.interfaces.portal_membership: # Create a member area for 'member_id' or authenticated user.) member = membership.getAuthenticatedMember() member_id = member.getId() if hasattr(members, 'aq_explicit'): members=members.aq_explicit if members is None: # no members area logger.debug('createMemberarea: members area does not exist.') return safe_member_id = cleanId(member_id) if hasattr(members, safe_member_id): # has already this member logger.debug( 'createMemberarea: member area ' 'for %r already exists.' % safe_member_id) return if not safe_member_id: # Could be one of two things: # - A Emergency User # - cleanId made a empty string out of member_id logger.debug( 'createMemberarea: empty member id ' '(%r, %r), skipping member area creation.' % ( member_id, safe_member_id)) return _createObjectByType(self.memberarea_type, members, id=safe_member_id) # Get the user object from acl_users acl_users = self.__getPUS() user = acl_users.getUserById(member_id) if user is not None: user = user.__of__(acl_users) else: user = getSecurityManager().getUser() # check that we do not do something wrong if user.getId() != member_id: raise NotImplementedError, \ 'cannot get user for member area creation' member_object = self.getMemberById(member_id) ## Modify member folder member_folder = self.getHomeFolder(member_id) # Grant Ownership and Owner role to Member member_folder.changeOwnership(user) member_folder.__ac_local_roles__ = None member_folder.manage_setLocalRoles(member_id, ['Owner']) # We use ATCT now use the mutators fullname = member_object.getProperty('fullname') member_folder.setTitle(fullname or member_id) member_folder.reindexObject() if not minimal: ## add homepage text # get the text from portal_skins automagically homepageText = getattr(self, 'homePageText', None) if homepageText: portal = getToolByName(self, "portal_url").getPortalObject() # call the page template content = homepageText(member=member_object, portal=portal).strip() _createObjectByType('Document', member_folder, id='index_html') hpt = getattr(member_folder, 'index_html') # edit title, text and format hpt.setTitle(fullname or member_id) if hpt.meta_type == 'Document': hpt.edit(text_format='structured-text', text=content) else: hpt.update(text=content) hpt.setFormat('structured-text') hpt.reindexObject() # Grant Ownership and Owner role to Member hpt.changeOwnership(user) hpt.__ac_local_roles__ = None hpt.manage_setLocalRoles(member_id, ['Owner']) ## Hook to allow doing other things after memberarea creation. notify_script = getattr(member_folder, 'notifyMemberAreaCreated', None) if notify_script is not None: notify_script()
def normalize(id): return cleanId(id)
def prepareid(values): id = values['fields']['name'].encode('utf8') id = id.replace(' ','') return cleanId(id)
def prepareid(id): return cleanId(id)
def createMemberarea(self, member_id=None, minimal=None): """ Create a member area for 'member_id' or the authenticated user, but don't assume that member_id is url-safe. """ if not self.getMemberareaCreationFlag(): return None membership = getToolByName(self, 'portal_membership') members = self.getMembersFolder() if not member_id: # member_id is optional (see CMFCore.interfaces.portal_membership: # Create a member area for 'member_id' or authenticated user.) member = membership.getAuthenticatedMember() member_id = member.getId() fname = member.getProperty('first_name', '').split(' ')[0] if member.getProperty('first_name') else '' mname = member.getProperty('mid_initial', '')[:1] if member.getProperty('mid_initial') else '' lname = member.getProperty('last_name', '') if member.getProperty('last_name') else '' new_id = normalizeString(fname + mname + lname) complete_name = '%s %s. %s' % (fname, mname, lname) if hasattr(members, new_id): #context_id = new_id return else: # Try juandcruz-1, juandcruz-2, etc. idx = 1 while idx <= RENAME_AFTER_CREATION_ATTEMPTS: if idx == 1: new_id1 = "%s" % new_id else: new_id1 = "%s%d" % (new_id, idx-1) if hasattr(members, new_id1): continue else: context_id = new_id1 break; idx += 1 if hasattr(members, 'aq_explicit'): members = members.aq_explicit if members is None: # no members area logger.debug('createMemberarea: members area does not exist.') return safe_member_id = cleanId(context_id).replace('--', '-') if hasattr(members, safe_member_id): # has already this member logger.debug( 'createMemberarea: member area ' 'for %r already exists.' % safe_member_id) return if not safe_member_id: # Could be one of two things: # - A Emergency User # - cleanId made a empty string out of member_id logger.debug( 'createMemberarea: empty member id ' '(%r, %r), skipping member area creation.' % (member_id, safe_member_id) ) return # Create member area without security checks typesTool = getToolByName(members, 'portal_types') fti = typesTool.getTypeInfo(self.memberarea_type) member_folder = fti._constructInstance(members, safe_member_id) # Get the user object from acl_users acl_users = getToolByName(self, "acl_users") user = acl_users.getUserById(member_id) if user is not None: user = user.__of__(acl_users) else: user = getSecurityManager().getUser() # check that we do not do something wrong if user.getId() != member_id: raise NotImplementedError( 'cannot get user for member area creation' ) # Modify member folder member_folder = self.getHomeFolder(safe_member_id) # Grant Ownership and Owner role to Member member_folder.changeOwnership(user) member_folder.__ac_local_roles__ = None member_folder.manage_setLocalRoles(member_id, ['Owner']) # We use ATCT now use the mutators #member_folder.setTitle(safe_member_id or member_id) #custom Title member_folder.setTitle(complete_name or '') member_folder.reindexObject() # Hook to allow doing other things after memberarea creation. notify_script = getattr(member_folder, 'notifyMemberAreaCreated', None) if notify_script is not None: notify_script()
def createMemberarea(self, member_id=None, minimal=None): """ Create a member area for 'member_id' or the authenticated user, but don't assume that member_id is url-safe. """ if not self.getMemberareaCreationFlag(): return None catalog = getToolByName(self, 'portal_catalog') membership = getToolByName(self, 'portal_membership') members = self.getMembersFolder() if not member_id: # member_id is optional (see CMFCore.interfaces.portal_membership: # Create a member area for 'member_id' or authenticated user.) member = membership.getAuthenticatedMember() member_id = member.getId() if hasattr(members, 'aq_explicit'): members=members.aq_explicit if members is None: # no members area logger.debug('createMemberarea: members area does not exist.') return safe_member_id = cleanId(member_id) if hasattr(members, safe_member_id): # has already this member logger.debug( 'createMemberarea: member area ' 'for %r already exists.' % safe_member_id) return if not safe_member_id: # Could be one of two things: # - A Emergency User # - cleanId made a empty string out of member_id logger.debug( 'createMemberarea: empty member id ' '(%r, %r), skipping member area creation.' % ( member_id, safe_member_id)) return # Create member area without security checks typesTool = getToolByName(members, 'portal_types') fti = typesTool.getTypeInfo(self.memberarea_type) member_folder = fti._constructInstance(members, safe_member_id) # Get the user object from acl_users acl_users = getToolByName(self, "acl_users") user = acl_users.getUserById(member_id) if user is not None: user = user.__of__(acl_users) else: user = getSecurityManager().getUser() # check that we do not do something wrong if user.getId() != member_id: raise NotImplementedError, \ 'cannot get user for member area creation' member_object = self.getMemberById(member_id) ## Modify member folder member_folder = self.getHomeFolder(member_id) # Grant Ownership and Owner role to Member member_folder.changeOwnership(user) member_folder.__ac_local_roles__ = None member_folder.manage_setLocalRoles(member_id, ['Owner']) # We use ATCT now use the mutators fullname = member_object.getProperty('fullname') member_folder.setTitle(fullname or member_id) member_folder.reindexObject() ## Hook to allow doing other things after memberarea creation. notify_script = getattr(member_folder, 'notifyMemberAreaCreated', None) if notify_script is not None: notify_script()
def createMemberarea(self, member_id=None, minimal=None): """ Create a member area for 'member_id' or the authenticated user, but don't assume that member_id is url-safe. """ if not self.getMemberareaCreationFlag(): return None membership = getToolByName(self, 'portal_membership') members = self.getMembersFolder() if not member_id: # member_id is optional (see CMFCore.interfaces.portal_membership: # Create a member area for 'member_id' or authenticated user.) member = membership.getAuthenticatedMember() member_id = member.getId() if hasattr(members, 'aq_explicit'): members = members.aq_explicit if members is None: # no members area logger.debug('createMemberarea: members area does not exist.') return safe_member_id = cleanId(member_id) if hasattr(members, safe_member_id): # has already this member logger.debug('createMemberarea: member area ' 'for %r already exists.' % safe_member_id) return if not safe_member_id: # Could be one of two things: # - A Emergency User # - cleanId made a empty string out of member_id logger.debug('createMemberarea: empty member id ' '(%r, %r), skipping member area creation.' % (member_id, safe_member_id)) return # Create member area without security checks typesTool = getToolByName(members, 'portal_types') fti = typesTool.getTypeInfo(self.memberarea_type) member_folder = fti._constructInstance(members, safe_member_id) # Get the user object from acl_users acl_users = getToolByName(self, "acl_users") user = acl_users.getUserById(member_id) if user is not None: user = user.__of__(acl_users) else: user = getSecurityManager().getUser() # check that we do not do something wrong if user.getId() != member_id: raise NotImplementedError( 'cannot get user for member area creation') member_object = self.getMemberById(member_id) # Modify member folder member_folder = self.getHomeFolder(member_id) # Grant Ownership and Owner role to Member member_folder.changeOwnership(user) member_folder.__ac_local_roles__ = None member_folder.manage_setLocalRoles(member_id, ['Owner']) # We use ATCT now use the mutators fullname = member_object.getProperty('fullname') member_folder.setTitle(fullname or member_id) member_folder.reindexObject() # Hook to allow doing other things after memberarea creation. notify_script = getattr(member_folder, 'notifyMemberAreaCreated', None) if notify_script is not None: notify_script()