def add(container, obj, rename=True): """Add an object to a container.""" id_ = getattr(aq_base(obj), "id", None) # Archetypes objects are already created in a container thus we just fire # the notification events and rename the object if necessary. if base_hasattr(obj, "_at_rename_after_creation"): notify(ObjectAddedEvent(obj, container, id_)) notifyContainerModified(container) if obj._at_rename_after_creation and rename: obj._renameAfterCreation(check_auto_id=True) return obj else: if rename: chooser = INameChooser(container) # INameFromTitle adaptable objects should not get a name # suggestion. NameChooser would prefer the given name instead of # the one provided by the INameFromTitle adapter. suggestion = None name_from_title = INameFromTitle(obj, None) if name_from_title is None: suggestion = obj.Title() id_ = chooser.chooseName(suggestion, obj) obj.id = id_ new_id = container._setObject(id_, obj) # _setObject triggers ObjectAddedEvent which can end up triggering a # content rule to move the item to a different container. In this case # look up the object by UUID. try: return container._getOb(new_id) except AttributeError: uuid = IUUID(obj) return uuidToObject(uuid)
def chooseName(self, name, object): container = aq_inner(self.context) if not name: nameFromTitle = INameFromTitle(object, None) if nameFromTitle is not None: name = nameFromTitle.title if not name: name = getattr(aq_base(object), 'id', None) if not name: name = getattr(aq_base(object), 'portal_type', None) if not name: name = object.__class__.__name__ if not isinstance(name, unicode): name = unicode(name, 'utf-8') request = getattr(object.__of__(container), 'REQUEST', None) if request is not None: name = IUserPreferredURLNormalizer(request).normalize(name) else: name = getUtility(IURLNormalizer).normalize(name) if name[:1] == '_': name = name[1:] return self._findUniqueName(name, object)
def test_container(self): container = api.content.create( title="Container", type="ClassificationContainer", container=self.folder ) self.assertEqual("Container", container.Title()) self.assertEqual("Container", INameFromTitle(container).title) self.assertEqual("container", container.id)
def current_user(self): result = {} current = api.user.get_current() current_profile = api.content.get(UID=current.id) result['url'] = current_profile and current_profile.absolute_url( ) or "#" result['fullname'] = current_profile and INameFromTitle( current_profile).title or u"" return result
def person_title(person): title = INameFromTitle(person).title adapted = IPerson(person, None) if adapted: bound = IPerson['position'].bind(adapted) position = bound.get(adapted) title_position = _('person_title', default=u'${title}, ${position}', mapping={'title': title, 'position': position}) if position: title = translate(title_position, context=api.portal.getRequest()) return title
def create_title_from_id(obj, event): if not api.portal.get_registry_record( 'ploneintranet.workspace.rename_after_title_changed', default=True, ): return autosave_portal_types = api.portal.get_registry_record( 'ploneintranet.workspace.autosave_portal_types', default=[], ) if obj.portal_type in autosave_portal_types: # autosave does not work well with autorename because the form action # will point to the old URL and the redirection tool will not work # with the ajax calls return if IContainerModifiedEvent.providedBy(event): # The container modified event gets triggered during the creation # of a folder. We must not change the id before an item as been # properly created. return if IBaseWorkspaceFolder.providedBy(obj): # Don't change the ID of a workspace return if not in_workspace(obj): # Don't handle content outside of a workspace return orig_id = obj.getId() title_adapter = INameFromTitle(obj, None) name = title_adapter and title_adapter.title if not name: # No title present, no point in changing the id return if len(name) > MAX_ID_FROM_TITLE_LENGTH: plone_view = getMultiAdapter((obj, obj.REQUEST), name='plone') name = plone_view.cropText(name, MAX_ID_FROM_TITLE_LENGTH, ellipsis="") normalized_name = IUserPreferredURLNormalizer(obj.REQUEST).normalize(name) container = aq_parent(obj) # Check if the id is already looking good if _is_id_good_enough(orig_id, normalized_name, container): return chooser = INameChooser(container) new_id = chooser and chooser.chooseName(normalized_name, container) if new_id and new_id != orig_id: unlock_view = obj.restrictedTraverse('@@toggle-lock', None) if unlock_view and unlock_view.can_unlock(): unlock_view.unlock() api.content.rename(obj, new_id)
def test_name_from_full_name(self): # We do not want to set a title but instead have the first and # last name used as title. We do not mind too much if the # title field itself is empty, as long as we have our ways to # get the fullname and get a name (basis for id) based on our # title. member = self._createType(self.portal, 'dexterity.membrane.member', 'joe') name_title = INameFromTitle(member) self.assertEqual(name_title.title, u'') member.title = u"Title field" self.assertEqual(name_title.title, u'') member.last_name = u"User" self.assertEqual(name_title.title, u'User') member.first_name = u"Joe" self.assertEqual(name_title.title, u'Joe User') self.assertEqual(get_full_name(member), u'Joe User')
def rename_object(self, obj): # Archetypes objects may get renamed during deserialization. # Do not rename again. if (base_hasattr(obj, '_isIDAutoGenerated') and not obj._isIDAutoGenerated(obj.getId())): return chooser = INameChooser(self.context) # INameFromTitle adaptable objects should not get a name # suggestion. NameChooser would prefer the given name instead of # the one provided by the INameFromTitle adapter. suggestion = None name_from_title = INameFromTitle(obj, None) if name_from_title is None: if base_hasattr(obj, 'generateNewId'): suggestion = obj.generateNewId() else: suggestion = obj.Title() name = chooser.chooseName(suggestion, obj) transaction.savepoint(optimistic=True) self.context.manage_renameObject(obj.getId(), name)
def handleApply(self, action): logger.info("contact_bluechurchprofile") context = self.context data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return # Handle order here. For now, just print it to the console. A more # realistic action would be to send the order to another system, send # an email, or similar fullname = INameFromTitle(context).title response = self.request.response request = self.request current = api.user.get_current() current_profile = api.content.get(UID=current.id) if not current_profile: response.redirect(self.context.absolute_url()) return recipient = self.context sender = current_profile subject = data['messagesubject'] # subject = subject or _(u"{} wants to contact you due to Jazz and Sermon stuff.".format(INameFromTitle(sender).title)) # subject = subject.decode('utf-8') text = data['messagetext'] #.decode('utf-8') messages = IStatusMessage(request) try: sendMail(sender, recipient, subject, text, request) logger.info("contact_bluechurchprofile send.") except Exception, e: msg = _(u"Message '{}' not sent to {}. There were errors.".format( subject, recipient.email)) logger.error(msg) logger.error(str(e)) # messages.addStatusMessage(_(msg, "error")) raise e
def test_behaviors(self): """Validate that the required behaviors are available.""" self.assertTrue(INameFromTitle.providedBy(self.ct))
def Title(self): """ return the title """ return INameFromTitle(self).title
def __getattribute__(self, name): if name.startswith('_') or name.startswith( 'portal_') or name.startswith('@@') or name == 'sql_id': return super(SQLDexterityItem, self).__getattribute__(name) connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None) if connection == None and self.portal_type: fti = queryUtility(IDexterityFTI, name=self.portal_type, default=None) if not fti: return None updateConnectionsForFti(fti) connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None) if name == 'view': #be sure session and sqlitem are up to date self._v_sql_item = None connection.session.close() if not connection: return super(SQLDexterityItem, self).__getattribute__(name) if name == 'UID' and self.sql_virtual: return self.portal_type + '-' + connection.sql_table + '-' + str( self.sql_id) if name == 'id' and 'id' not in connection.fieldnames.keys(): if not self.sql_virtual: return super(SQLDexterityItem, self).__getattribute__(name) fti = ISQLTypeSettings( getUtility(IDexterityFTI, name=self.portal_type)) nameFromTitle = INameFromTitle(self, None) if nameFromTitle is not None and nameFromTitle.title: sql_folder_id = getattr(fti, 'sql_folder_id', 'data-' + self.portal_type) title = nameFromTitle.title folder = None if IRelationValue.providedBy(sql_folder_id): folder = sql_folder_id.to_object elif sql_folder_id and sql_folder_id.startswith('/'): portal = getToolByName(getSite(), 'portal_url').getPortalObject() folder = portal.restrictedTraverse(sql_folder_id) if folder: name = INameChooser(folder).chooseName(title, self) return name # return INameChooser(getSite()).chooseName(title, self) # return getUtility(IURLNormalizer).normalize(title) return self.sql_id if name in connection.fieldnames.keys(): sql_column = connection.fieldnames[name] sql_item = self.getSQLItem() try: sql_id = getattr(sql_item, connection.sql_id_column, None) except orm_exc.DetachedInstanceError: self._v_sql_item = None sql_item = self.getSQLItem() sql_id = getattr(sql_item, connection.sql_id_column, None) fieldname = 'name' if sql_item and sql_column: while '.' in sql_column: sql_key = sql_column.split('.')[0] sql_item = getattr(sql_item, sql_key, None) if isinstance(sql_item, list): value = sql_item fieldname = sql_column.split('.')[-1] break sql_column = '.'.join(sql_column.split('.')[1:]) else: if not isinstance(sql_item, list): value = getattr(sql_item, sql_column, None) if not value and (isinstance(value, list) or hasattr(value, '_sa_instance_state')): value = '' elif (isinstance(value, list) or hasattr(value, '_sa_instance_state')): sqlftis = [ a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None) ] if name == 'subject': return tuple( [getattr(a, fieldname, '') for a in value]) tableftis = [] for iface in iterSchemataForType(self.portal_type): if name in iface.names(): field = iface[name] if IRelationChoice.providedBy( field) or IRelationList.providedBy(field): if IRelationChoice.providedBy(field): allowed_types = field.source.query.get( 'portal_type', []) else: allowed_types = field.value_type.source.query.get( 'portal_type', []) tableftis = [] for sqlfti in sqlftis: adapted = ISQLTypeSettings(sqlfti, None) if isinstance(value, list): classname = value[0].__class__.__name__ else: classname = value.__class__.__name__ if adapted and getattr( adapted, 'sql_table', None) == classname: if not allowed_types or sqlfti.id in allowed_types: tableftis.append(adapted) catalog = getToolByName( getSite(), 'portal_catalog') relations = [] for tablefti in tableftis: sql_id_column = getattr( tablefti, 'sql_id_column', 'id') valueids = [] if isinstance(value, list): valueids = [ getattr(a, sql_id_column, None) for a in value if getattr(a, sql_id_column, None) ] else: valueids = getattr( value, sql_id_column, None) valueids = [str(a) for a in valueids] brains = catalog.unrestrictedSearchResults( portal_type=tablefti.id, sql_id=valueids) for brain in brains: relations.append( SQLRelationValue( brain.portal_type, brain.UID, self)) if IRelationChoice.providedBy( field) and relations: return relations[0] elif IRelationList.providedBy( field) and relations: return relations elif ITuple.providedBy(field): return tuple( [getattr(a, fieldname, '') for a in value]) elif IList.providedBy(field): return [ getattr(a, fieldname, '') for a in value ] elif value and isinstance(value, list): value = getattr(value[0], fieldname, '') for iface in iterSchemataForType(self.portal_type): if name == 'subject': try: return tuple([ a.decode('utf-8') for a in literal_eval(value) ]) except: return tuple([a.strip() for a in value.split(',')]) if name in iface.names(): field = iface[name] if IRichText.providedBy(field): if not value: return '' if not '<p' in value or not '<br' in value: value = '<p>' + '</p><p>'.join([ a for a in value.split('\n') if a.strip() ]) + '</p>' # try: # value = str(value) # except: # try: # value = value.decode('utf-8') # except: # try: # value = value.encode('utf-8') # except: # pass return RichTextValue(unidecode(value)) elif INamedBlobImage.providedBy(field): return NamedBlobImage( base64.b64decode(value), filename=unicode(self.portal_type + self.id + ".jpg")) elif ITuple.providedBy(field): if not value: return tuple([]) try: return tuple([ a.decode('utf-8') for a in literal_eval(value) ]) except: return tuple( [a.strip() for a in value.split(',')]) elif IList.providedBy(field): if not value: return [] try: return [ a.decode('utf-8') for a in literal_eval(value) ] except: return [a.strip() for a in value.split(',')] elif IDatetime.providedBy(field) and hasattr( value, 'day') and not hasattr(value, 'hour'): value = datetime.datetime.combine( value, datetime.datetime.min.time()) if name in [ 'expiration_date', 'effective_date', 'effective', 'expires' ] and hasattr(value, 'day') and not hasattr(value, 'hour'): value = datetime.datetime.combine( value, datetime.datetime.min.time()) if isinstance(value, unicode) or name == 'id': try: value = str(value) except: pass return value return super(SQLDexterityItem, self).__getattribute__(name)
def kontaktperson_fullname(self): profile = self.kontaktperson_profile name_title = INameFromTitle(profile) return name_title.title
def __getattribute__(self, name): if name.startswith('_') or name.startswith( 'portal_') or name.startswith('@@'): return super(SQLDexterityItem, self).__getattribute__(name) if name == 'id' and not self.sql_virtual: return super(SQLDexterityItem, self).__getattribute__(name) connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None) if connection == None and self.portal_type: fti = queryUtility(IDexterityFTI, name=self.portal_type, default=None) if not fti: return None updateConnectionsForFti(fti) connection = queryUtility(ISQLConnectionsUtility, name=self.portal_type, default=None) if not connection: return super(SQLDexterityItem, self).__getattribute__(name) if name == 'UID': return self.portal_type + '-' + connection.sql_table + '-' + str( self.sql_id) if name == 'id' and 'id' not in connection.fieldnames.keys(): fti = ISQLTypeSettings( getUtility(IDexterityFTI, name=self.portal_type)) nameFromTitle = INameFromTitle(self, None) if nameFromTitle is not None and nameFromTitle.title: sql_folder_id = getattr(fti, 'sql_folder_id', 'data-' + self.portal_type) title = nameFromTitle.title if IRelationValue.providedBy(name): folder = sql_folder_id.to_object if folder: return INameChooser(folder).chooseName(title, self) return INameChooser(getSite()).chooseName(title, self) if name in connection.fieldnames.keys(): sql_column = connection.fieldnames[name] sql_item = self.getSQLItem() fieldname = 'name' if sql_item and sql_column: while '.' in sql_column: sql_item = getattr(sql_item, sql_column.split('.')[0], None) if sql_item and ( (isinstance(sql_item, list) and len(sql_item) > 1) or hasattr(sql_item, '_sa_instance_state')): value = sql_item fieldname = sql_column.split('.')[-1] break sql_column = '.'.join(sql_column.split('.')[1:]) else: value = getattr(sql_item, sql_column, None) #this is a relation if value and (isinstance(value, list) or hasattr(value, '_sa_instance_state')): sqlftis = [ a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None) ] if name == 'subject': return tuple( [getattr(a, fieldname, '') for a in value]) tableftis = [] for iface in iterSchemataForType(self.portal_type): if name in iface.names(): field = iface[name] if IList.providedBy(field): return [ getattr(a, fieldname, '') for a in value ] # hope it has name! elif ITuple.providedBy(field): return tuple( [getattr(a, fieldname, '') for a in value]) if IRelationChoice.providedBy( field) or IRelationList.providedBy(field): if IRelationChoice.providedBy(field): allowed_types = field.source.query.get( 'portal_type', []) else: allowed_types = field.value_type.source.query.get( 'portal_type', []) tableftis = [] for sqlfti in sqlftis: adapted = ISQLTypeSettings(sqlfti, None) if isinstance(value, list): classname = value[0].__class__.__name__ else: classname = value.__class__.__name__ if adapted and getattr( adapted, 'sql_table', None) == classname: if not allowed_types or sqlfti.id in allowed_types: tableftis.append(adapted) catalog = getToolByName( getSite(), 'portal_catalog') relations = [] for tablefti in tableftis: sql_id_column = getattr( tablefti, 'sql_id_column', 'id') valueids = [] if isinstance(value, list): valueids = [ getattr(a, sql_id_column, None) for a in value if getattr(a, sql_id_column, None) ] else: valueids = getattr( value, sql_id_column, None) brains = catalog.searchResults( portal_type=tablefti.id, sql_id=valueids) for brain in brains: relations.append( SQLRelationValue( brain.portal_type, brain.sql_id)) if IRelationChoice.providedBy( field) and relations: return relations[0] elif IRelationList.providedBy( field) and relations: return relations for iface in iterSchemataForType(self.portal_type): if name == 'subject': try: return tuple([ a.decode('utf-8') for a in literal_eval(value) ]) except: return tuple([a.strip() for a in value.split(',')]) if name in iface.names(): field = iface[name] if IRichText.providedBy(field): return RichTextValue(value) if INamedBlobImage.providedBy(field): return NamedBlobImage( base64.b64decode(value), filename=unicode(self.portal_type + self.id + ".jpg")) if IList.providedBy(field): try: return [ a.decode('utf-8') for a in literal_eval(value) ] except: return [a.strip() for a in value.split(',')] if ITuple.providedBy(field): try: return tuple([ a.decode('utf-8') for a in literal_eval(value) ]) except: return tuple( [a.strip() for a in value.split(',')]) if isinstance(value, unicode) or name == 'id': try: return str(value) except: pass return value return super(SQLDexterityItem, self).__getattribute__(name)