def test_install_dx_type_if_needed(self): from plone.app.contenttypes.migration.utils import installTypeIfNeeded tt = self.portal.portal_types tt.manage_delObjects('Document') tt.manage_addTypeInformation( 'Factory-based Type Information with dynamic views', id='Document') applyProfile(self.portal, 'plone.app.contenttypes:default', blacklisted_steps=['typeinfo']) fti = tt.getTypeInfo('Document') self.assertFalse(IDexterityFTI.providedBy(fti)) installTypeIfNeeded('Document') fti = tt.getTypeInfo('Document') self.assertTrue(IDexterityFTI.providedBy(fti))
def lookup_fti(portal_type, cache=True): # if its a string lookup fti if isinstance(portal_type, six.string_types): # looking up a utility is expensive, using the global request as # cache is twice as fast if cache: request = getRequest() if request: fti_cache = getattr(request, FTI_CACHE_KEY, None) if fti_cache is None: fti_cache = dict() setattr(request, FTI_CACHE_KEY, fti_cache) if portal_type in fti_cache: fti = fti_cache[portal_type] else: fti_cache[portal_type] = fti = queryUtility( IDexterityFTI, name=portal_type) return fti return queryUtility(IDexterityFTI, name=portal_type) if IDexterityFTI.providedBy(portal_type): # its already an IDexterityFTI instance return portal_type raise ValueError( 'portal_type has to either string or IDexterityFTI instance but is ' '{0!r}'.format(portal_type))
def remove_versioning_behavior(self, fti): if not IDexterityFTI.providedBy(fti): return behaviors = list(fti.behaviors) if self.behavior_name in behaviors: behaviors.remove(self.behavior_name) fti.behaviors = behaviors
def portal_types(self): """A list with info on all content types with existing items.""" catalog = api.portal.get_tool("portal_catalog") portal_types = api.portal.get_tool("portal_types") results = [] query = self.build_query() for fti in portal_types.listTypeInfo(): if not IDexterityFTI.providedBy( fti ) and not IDynamicViewTypeInformation.providedBy(fti): # Ignore non-DX and non-AT types continue query["portal_type"] = fti.id number = len(catalog(**query)) if number >= 1: results.append( { "number": number, "value": fti.id, "title": translate( fti.title, domain="plone", context=self.request ), } ) return sorted(results, key=itemgetter("title"))
def fix_core_behaviors_in_ftis(context): # The behaviors for IRichText and ILeadImage have been renamed. # All FTIs that use them must be updated accordingly # See plone/plone.app.contenttypes#480 types_tool = getToolByName(context, 'portal_types') to_replace = { 'plone.app.contenttypes.behaviors.richtext.IRichText': 'plone.app.contenttypes.behaviors.richtext.IRichTextBehavior', 'plone.app.contenttypes.behaviors.leadimage.ILeadImage': 'plone.app.contenttypes.behaviors.leadimage.ILeadImageBehavior', } ftis = types_tool.listTypeInfo() for fti in ftis: # Since we're handling dexterity behaviors, we only care about # dexterity FTIs if not IDexterityFTI.providedBy(fti): continue behaviors = [] change_needed = False for behavior in fti.behaviors: if behavior in to_replace: behavior = to_replace[behavior] change_needed = True behaviors.append(behavior) if change_needed: fti.behaviors = tuple(behaviors)
def restore_all_behaviors(): types_tool = api.portal.get_tool('portal_types') for fti_id in types_tool.listTypeTitles().keys(): fti = types_tool.get(fti_id) if IDexterityFTI.providedBy(fti): for r_beh in REPLACEMENT_BEHAVIORS: replace_behavior(fti, r_beh['new'], r_beh['old'], 'restore')
def test_install_dx_type_if_needed(self): from plone.app.contenttypes.migration.utils import installTypeIfNeeded tt = self.portal.portal_types tt.manage_delObjects('Document') tt.manage_addTypeInformation( 'Factory-based Type Information with dynamic views', id='Document') applyProfile( self.portal, 'plone.app.contenttypes:default', blacklisted_steps=['typeinfo']) fti = tt.getTypeInfo('Document') self.assertFalse(IDexterityFTI.providedBy(fti)) installTypeIfNeeded('Document') fti = tt.getTypeInfo('Document') self.assertTrue(IDexterityFTI.providedBy(fti))
def __call__(self, context): context = getattr(context, 'context', context) portal = getToolByName(context, 'portal_url').getPortalObject() items = [SimpleTerm('auto', 'auto', context.translate(_('label_default_portaltype_configuration', default=u'Default configuration (Content Type Registry).')))] archetype_tool = getToolByName(context, 'archetype_tool', None) if archetype_tool: flt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IFileContent)] ilt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IImageContent)] items.extend([SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in flt]) file_types = [t['portal_type'] for t in flt] items.extend([SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in ilt if t['portal_type'] not in file_types]) for fti in portal.portal_types.objectValues(): if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): try: schema = fti.lookupSchema() except ImportError: # this dexterity type was changed/removed in an improper way # no need to punish, just fail gracefully continue fields = getFieldsInOrder(schema) for fieldname, field in fields: if INamedFileField.providedBy(field) or INamedImageField.providedBy(field): items.append(SimpleTerm(fti.getId(), fti.getId(), fti.Title())) break return SimpleVocabulary(items)
def __call__(self): req = self.request if req.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if filedata is None: return filename = filedata.filename content_type = mimetypes.guess_type(filename)[0] or "" if not filedata: return # Determine if the default file/image types are DX or AT based ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(filename.lower(), '', '') or 'File' DX_BASED = False if HAS_DEXTERITY: pt = getToolByName(self.context, 'portal_types') if IDexterityFTI.providedBy(getattr(pt, type_)): factory = IDXFileFactory(self.context) DX_BASED = True else: factory = IATCTFileFactory(self.context) else: factory = IATCTFileFactory(self.context) obj = factory(filename, content_type, filedata) if DX_BASED: if 'File' in obj.portal_type: size = obj.file.getSize() content_type = obj.file.contentType elif 'Image' in obj.portal_type: size = obj.image.getSize() content_type = obj.image.contentType result = { "type": content_type, "size": size } else: try: size = obj.getSize() except AttributeError: size = obj.getObjSize() result = { "type": obj.getContentType(), "size": size } result.update({ 'url': obj.absolute_url(), 'name': obj.getId(), 'uid': IUUID(obj), 'filename': filename }) return json.dumps(result)
def __call__(self, context): context = getattr(context, 'context', context) portal = getToolByName(context, 'portal_url').getPortalObject() flt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IFileContent)] ilt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IImageContent)] items = [SimpleTerm('auto', 'auto', context.translate('label_default_portaltype_configuration', default=u'Default configuration (Content Type Registry).', domain='collective.quickupload')),] all_portal_types = [] for t in flt+ilt: portal_type = t['portal_type'] if portal_type not in all_portal_types: items.append(SimpleTerm(portal_type, portal_type, t['type_ui_info'])) all_portal_types.append(portal_type) for fti in portal.portal_types.objectValues(): if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): fields = getFieldsInOrder(fti.lookupSchema()) for fieldname, field in fields: if INamedFileField.providedBy(field) or INamedImageField.providedBy(field): items.append(SimpleTerm(fti.getId(), fti.getId(), fti.Title())) break return SimpleVocabulary(items)
def invalidate(self, fti): if fti is not None and not IDexterityFTI.providedBy(fti): # fti is a name, lookup fti = queryUtility(IDexterityFTI, name=fti) if fti is not None: invalidate_cache(fti) self.invalidations += 1
def add_versioning_behavior(self, fti): if not IDexterityFTI.providedBy(fti): return behaviors = list(fti.behaviors) if self.behavior_name not in behaviors: behaviors.append(self.behavior_name) fti.behaviors = behaviors
def installTypeIfNeeded(type_name): """Make sure the dexterity-fti is already installed. If not we create a empty dexterity fti and load the information from the fti in the profile. """ if type_name not in DEFAULT_TYPES: raise KeyError('{0} is not one of the default types'.format(type_name)) portal = getSite() tt = getToolByName(portal, 'portal_types') fti = tt.getTypeInfo(type_name) if IDexterityFTI.providedBy(fti): # The dx-type is already installed, so keep it. But this # might be an old dexterity type of Collection, in which case # it is better to replace it. if type_name != 'Collection': return if fti.klass == 'plone.app.contenttypes.content.Collection': # If the klass is fine, we are happy. return if fti: tt.manage_delObjects(type_name) tt.manage_addTypeInformation('Dexterity FTI', id=type_name) dx_fti = tt.getTypeInfo(type_name) ps = getToolByName(portal, 'portal_setup') profile_info = ps.getProfileInfo('profile-plone.app.contenttypes:default') profile_path = os.path.join(profile_info['path']) environ = DirectoryImportContext(ps, profile_path) parent_path = 'types/' importObjects(dx_fti, parent_path, environ)
def removeBehaviors(context): """Remove p.a.multilingual behaviors from p.a.contenttypes types.""" if context.readDataFile('plone.app.multilingual_uninstall.txt') is None: return portal = context.getSite() portal_types = getToolByName(portal, 'portal_types') behavior = 'plone.app.multilingual.dx.interfaces.IDexterityTranslatable' # plone.app.contenttype types typeNames = [ 'Document', 'File', 'Folder', 'Image', 'Link', 'News Item', ] for name in typeNames: type_ = portal_types.get(name) # safety first if not type_ or not IDexterityFTI.providedBy(type_): continue behaviors = list(type_.behaviors) behaviors.remove(behavior) type_.behaviors = tuple(behaviors)
def installTypeIfNeeded(type_name): """Make sure the dexterity-fti is already installed. If not we create a empty dexterity fti and load the information from the fti in the profile. """ if type_name not in DEFAULT_TYPES: raise KeyError("%s is not one of the default types" % type_name) portal = getSite() tt = getToolByName(portal, 'portal_types') fti = tt.getTypeInfo(type_name) if IDexterityFTI.providedBy(fti): # The dx-type is already installed, so keep it. But this # might be an old dexterity type of Collection, in which case # it is better to replace it. if type_name != 'Collection': return if fti.klass == 'plone.app.contenttypes.content.Collection': # If the klass is fine, we are happy. return if fti: tt.manage_delObjects(type_name) tt.manage_addTypeInformation('Dexterity FTI', id=type_name) dx_fti = tt.getTypeInfo(type_name) ps = getToolByName(portal, 'portal_setup') profile_info = ps.getProfileInfo('profile-plone.app.contenttypes:default') profile_path = os.path.join(profile_info['path']) environ = DirectoryImportContext(ps, profile_path) parent_path = 'types/' importObjects(dx_fti, parent_path, environ)
def ftiModified(object, event): """When an FTI is modified, re-sync and invalidate the schema, if necessary. """ if not IDexterityFTI.providedBy(event.object): return fti = event.object portal_type = fti.getId() mod = {} for desc in event.descriptions: if IDexterityFTIModificationDescription.providedBy(desc): mod[desc.attribute] = desc.oldValue # If the factory utility name was modified, we may get an orphan if one # was registered as a local utility to begin with. If so, remove the # orphan. if 'factory' in mod: old_factory = mod['factory'] site_manager = getGlobalSiteManager() # Remove previously registered factory, if no other type uses it. unregister_factory(old_factory, site_manager) # Register a new local factory if one doesn't exist already new_factory_utility = queryUtility(IFactory, name=fti.factory) if new_factory_utility is None: site_manager.registerUtility(DexterityFactory(portal_type), IFactory, fti.factory, info='plone.dexterity.dynamic') # Determine if we need to invalidate the schema at all if 'behaviors' in mod \ or 'schema' in mod \ or 'model_source' in mod \ or 'model_file' in mod \ or 'schema_policy' in mod: # Determine if we need to re-sync a dynamic schema if ((fti.model_source or fti.model_file) and ('model_source' in mod or 'model_file' in mod or 'schema_policy' in mod)): schemaName = portalTypeToSchemaName(portal_type) schema = getattr(plone.dexterity.schema.generated, schemaName) model = fti.lookupModel() sync_bases = 'schema_policy' in mod syncSchema(model.schema, schema, overwrite=True, sync_bases=sync_bases) notify(SchemaInvalidatedEvent(portal_type))
def remove_versioning_behavior(self, fti): if not IDexterityFTI.providedBy(fti): return behaviors = list(fti.behaviors) if self.behavior_name in behaviors: behaviors.remove(self.behavior_name) # TODO: remove locking if it wasn't set in first place fti.behaviors = behaviors
def ftiAdded(object, event): """When the FTI is created, install local components """ if not IDexterityFTI.providedBy(event.object): return register(event.object)
def ftiRemoved(object, event): """When the FTI is removed, uninstall local coponents """ if not IDexterityFTI.providedBy(event.object): return unregister(event.object)
def ftiModified(object, event): """When an FTI is modified, re-sync and invalidate the schema, if necessary. """ if not IDexterityFTI.providedBy(event.object): return fti = event.object portal_type = fti.getId() mod = {} for desc in event.descriptions: if IDexterityFTIModificationDescription.providedBy(desc): mod[desc.attribute] = desc.oldValue # If the factory utility name was modified, we may get an orphan if one # was registered as a local utility to begin with. If so, remove the # orphan. if 'factory' in mod: old_factory = mod['factory'] site = getUtility(ISiteRoot) site_manager = getSiteManager(site) # Remove previously registered factory, if no other type uses it. unregister_factory(old_factory, site_manager) # Register a new local factory if one doesn't exist already new_factory_utility = queryUtility(IFactory, name=fti.factory) if new_factory_utility is None: site_manager.registerUtility( DexterityFactory(portal_type), IFactory, fti.factory, info='plone.dexterity.dynamic' ) # Determine if we need to invalidate the schema at all if 'behaviors' in mod \ or 'schema' in mod \ or 'model_source' in mod \ or 'model_file' in mod \ or 'schema_policy' in mod: # Determine if we need to re-sync a dynamic schema if (fti.model_source or fti.model_file) \ and ('model_source' in mod or 'model_file' in mod or 'schema_policy' in mod): schemaName = portalTypeToSchemaName(portal_type) schema = getattr(plone.dexterity.schema.generated, schemaName) model = fti.lookupModel() sync_bases = 'schema_policy' in mod syncSchema(model.schema, schema, overwrite=True, sync_bases=sync_bases) notify(SchemaInvalidatedEvent(portal_type))
def getDexterityTypes(self): """ Returns a list of Dexterity FTIs. """ portal_types = getToolByName(self.context, 'portal_types') for fti in portal_types.listTypeInfo(): if IDexterityFTI.providedBy(fti): yield fti
def ensure_translatable(self, type_): types_tool = getToolByName(self.context, 'portal_types') fti = getattr(types_tool, type_) if IDexterityFTI.providedBy(fti): behaviors = list(fti.behaviors) behaviors.append('plone.translatable') behaviors = tuple(set(behaviors)) fti._updateProperty('behaviors', behaviors)
def __call__(self): portal_types = getToolByName(self.context, 'portal_types') for fti in portal_types.objectValues(): if IDexterityFTI.providedBy(fti) and fti.id in TYPES_TO_FIX: add_view_expr = "python:object.restrictedTraverse('plone_context_state').folder().absolute_url() + '/++add++%s'" % fti.getId() fti._setPropValue('add_view_expr', add_view_expr) return 'Success!'
def getDXFTIs(self): '''Returns the FTI's of all DX-Types (including default-types).''' results = [] portal = self.context ttool = getToolByName(portal, 'portal_types') for fti in ttool.listTypeInfo(): if IDexterityFTI.providedBy(fti): results.append({'id': fti.getId(), 'title': fti.Title()}) return results
def check_translatable_foldertype(self): from plone.dexterity.interfaces import IDexterityFTI from plone.app.multilingual.dx.interfaces import IDexterityTranslatable pt = getToolByName(self.context, 'portal_types') fti = getattr(pt, self.folder_type) if IDexterityFTI.providedBy(fti): behaviors = list(fti.behaviors) behaviors.append(IDexterityTranslatable.__identifier__) fti.behaviors = behaviors
def fti_modified(obj, event): """ When an FTI is modified, invalidate localrole fields list cache. """ return # cache is no more used because not necessary following timecall if not IDexterityFTI.providedBy(event.object): return cache_chooser = getUtility(ICacheChooser) thecache = cache_chooser('dexterity.localrolesfield.utils.get_localrole_fields') thecache.ramcache.invalidate('dexterity.localrolesfield.utils.get_localrole_fields')
def __call__(self): req = self.request if req.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if filedata is None: return filename = filedata.filename content_type = mimetypes.guess_type(filename)[0] or "" if not filedata: return # Determine if the default file/image types are DX or AT based ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(filename.lower(), '', '') or 'File' DX_BASED = False if HAS_DEXTERITY: pt = getToolByName(self.context, 'portal_types') if IDexterityFTI.providedBy(getattr(pt, type_)): factory = IDXFileFactory(self.context) DX_BASED = True else: factory = IATCTFileFactory(self.context) else: factory = IATCTFileFactory(self.context) obj = factory(filename, content_type, filedata) if DX_BASED: if 'File' in obj.portal_type: size = obj.file.getSize() content_type = obj.file.contentType elif 'Image' in obj.portal_type: size = obj.image.getSize() content_type = obj.image.contentType result = {"type": content_type, "size": size} else: try: size = obj.getSize() except AttributeError: size = obj.getObjSize() result = {"type": obj.getContentType(), "size": size} result.update({ 'url': obj.absolute_url(), 'name': obj.getId(), 'uid': IUUID(obj), 'filename': filename }) return json.dumps(result)
def fti_modified(obj, event): """ When an FTI is modified, invalidate localrole fields list cache. """ return # cache is no more used because not necessary following timecall if not IDexterityFTI.providedBy(event.object): return cache_chooser = getUtility(ICacheChooser) thecache = cache_chooser( 'dexterity.localrolesfield.utils.get_localrole_fields') thecache.ramcache.invalidate( 'dexterity.localrolesfield.utils.get_localrole_fields')
def add_versioning_behavior(self, fti): if not IDexterityFTI.providedBy(fti): return behaviors = list(fti.behaviors) if self.behavior_name not in behaviors: behaviors.append(self.behavior_name) # locking must be turned on for versioning support on the type locking = 'plone.app.lockingbehavior.behaviors.ILocking' if locking not in behaviors: behaviors.append(locking) fti.behaviors = behaviors
def remove_behavior(context): """Remove the lineage.themeselection behavior from portal_types types. """ key = 'lineage.themeselection.behaviors.IThemeSelection' types_tool = getToolByName(context, 'portal_types') for item in types_tool.values(): if IDexterityFTI.providedBy(item): if key in getattr(item, 'behaviors', ''): item.behaviors = tuple( it for it in types_tool.Folder.behaviors if it not in key ) logger.info("Removed {0} from {1}".format(key, item.id))
def ftiRenamed(object, event): """When the FTI is modified, ensure local components are still valid """ if not IDexterityFTI.providedBy(event.object): return if event.oldParent is None or event.newParent is None or event.oldName == event.newName: return unregister(event.object, event.oldName) register(event.object)
def demarshall(obj, message): types_tool = api.portal.get_tool('portal_types') fti = types_tool.get(obj.portal_type) if IDexterityFTI.providedBy(fti): # DX payload = message._payload message._payload = None initializeObjectFromSchemata(DublinCore(obj), [IDublinCore], message) message._payload = payload initializeObjectFromSchemata(obj, iterSchemata(obj), message) elif HAS_ARCHETYPES: # AT initializeObject(obj, iterFields(obj), message)
def demarshall(ob, message): types_tool = api.portal.get_tool('portal_types') fti = types_tool.get(ob.portal_type) if IDexterityFTI.providedBy(fti): # DX try: initializeObjectFromSchemata(ob, iterSchemata(ob), message) except Exception: raise # import pdb; pdb.set_trace() # initializeObjectFromSchemata(ob, iterSchemata(ob), message) elif HAS_ARCHETYPES: # AT initializeObject(ob, iterFields(ob), message)
def ensure_correct_class(ob): # TODO: Detect if class is changed into container type and initialize it types_tool = api.portal.get_tool('portal_types') fti = types_tool.get(ob.portal_type) if IDexterityFTI.providedBy(fti): module_name, class_name = fti.klass.rsplit('.', 1) module = importlib.import_module(module_name) klass = getattr(module, class_name) elif HAS_ARCHETYPES: key = '.'.join([fti.product, fti.id]) klass = _types.get(key, {}).get('klass', None) if klass is not None and ob.__class__ != klass: ob.__class__ = klass ob._p_changed = True
def add_content(self, typename, name, parent, **kwargs): kwargs['title'] = kwargs.get('title', name) tool = getToolByName(self.portal, 'portal_types') fti = tool.getTypeInfo(typename) if IDexterityFTI.providedBy(fti): o = createContent(typename, **kwargs) o.id = name parent._setObject(name, o) else: parent.invokeFactory(typename, name) o = parent[name] o.setTitle(kwargs.get('title')) o.reindexObject() return o
def _listTypesForInterface(context, iftype='file'): """ List of portal types that have File or Image interface @param portal: context @param iftype: Type of interface to query for, can be either 'file' or 'image' @return: ['Image', 'News Item'] """ archetype_tool = getToolByName(context, 'archetype_tool', None) types_tool = getToolByName(context, 'portal_types') all_types = [] if archetype_tool: if iftype == 'image': interface = IImageContent else: interface = IFileContent # plone4 try: all_types = [ tipe.getId() for tipe in archetype_tool.listPortalTypesWithInterfaces([interface]) ] # plone3 except: all_types = archetype_tool.listRegisteredTypes(inProject=True) all_types = [ tipe['portal_type'] for tipe in all_types if interface.isImplementedByInstancesOf(tipe['klass']) ] if HAS_DEXTERITY: if iftype == 'image': interface = INamedImageField else: interface = INamedFileField for fti in types_tool.objectValues(): if IDexterityFTI.providedBy(fti): fields = getFieldsInOrder(fti.lookupSchema()) for fieldname, field in fields: if interface.providedBy(field): all_types.append(fti.getId()) break # fix for bug in listRegisteredTypes which returns 2 'ATFolder' # when asking for IBaseFolder interface unik_types = dict.fromkeys(all_types).keys() return unik_types
def _listTypesForInterface(context, iftype='file'): """ List of portal types that have File or Image interface @param portal: context @param iftype: Type of interface to query for, can be either 'file' or 'image' @return: ['Image', 'News Item'] """ archetype_tool = getToolByName(context, 'archetype_tool', None) types_tool = getToolByName(context, 'portal_types') all_types = [] if archetype_tool: if iftype == 'image': interface = IImageContent else: interface = IFileContent #plone4 try: all_types = [ tipe.getId() for tipe in archetype_tool.listPortalTypesWithInterfaces([interface]) ] #plone3 except: all_types = archetype_tool.listRegisteredTypes(inProject=True) all_types = [ tipe['portal_type'] for tipe in all_types if interface.isImplementedByInstancesOf(tipe['klass']) ] if HAS_DEXTERITY: if iftype == 'image': interface = INamedImageField else: interface = INamedFileField for fti in types_tool.objectValues(): if IDexterityFTI.providedBy(fti): fields = getFieldsInOrder(fti.lookupSchema()) for fieldname, field in fields: if interface.providedBy(field): all_types.append(fti.getId()) break # fix for bug in listRegisteredTypes which returns 2 'ATFolder' # when asking for IBaseFolder interface unik_types = dict.fromkeys(all_types).keys() return unik_types
def marshall(ob): types_tool = api.portal.get_tool('portal_types') fti = types_tool.get(ob.portal_type) # noinspection PyUnresolvedReferences if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): # DX message = constructMessageFromSchemata(ob, iterSchemata(ob)) elif HAS_ARCHETYPES and hasattr(Acquisition.aq_base(ob), 'schema'): # AT message = constructMessage(ob, iterFields(ob)) else: # Other schemata = tuple(ob.__provides__.interfaces()) message = constructMessageFromSchemata(ob, schemata) return message
def get_mapped_types(self): """Returns the mapped types for this catalog """ pt = api.get_tool("portal_types") at = api.get_tool("archetype_tool") # Get all Archetypes which are mapped to this catalog at_types = [k for k, v in at.catalog_map.items() if self.id in v] # TODO: Discover the mapped catalogs for Dexterity types dx_ftis = filter(lambda fti: IDexterityFTI.providedBy(fti), pt.listTypeInfo()) dx_types = map(lambda fti: fti.getId(), dx_ftis) return at_types + dx_types
def getDexterityFolderTypes(): try: from plone.dexterity.interfaces import IDexterityFTI from plone.dexterity.utils import resolveDottedName except ImportError: return set([]) portal_types = getToolByName(portal, "portal_types") types = [fti for fti in portal_types.listTypeInfo() if IDexterityFTI.providedBy(fti)] ftypes = set([]) for _type in types: klass = resolveDottedName(_type.klass) if ISyndicatable.implementedBy(klass): ftypes.add(_type.getId()) return ftypes
def update(self): self.available = False if not HAS_ARCHETYPES: return self.context = aq_inner(self.context) replaced_types = [ 'ATFolder', 'ATDocument', 'ATFile', 'ATImage', 'ATNewsItem', 'ATLink', 'ATEvent', 'ATBlobImage', 'ATBlobFile', 'Collection' ] if self.context.meta_type not in replaced_types: return if not IBaseObject.providedBy(self.context): return context_fti = self.context.getTypeInfo() if IDexterityFTI.providedBy(context_fti): self.available = True
def add_content(self, typename, name, parent, **kwargs): kwargs['title'] = kwargs.get('title', name) tool = getToolByName(self.portal, 'portal_types') fti = tool.getTypeInfo(typename) if IDexterityFTI.providedBy(fti): o = createContent( typename, **kwargs ) o.id = name parent._setObject(name, o) else: parent.invokeFactory(typename, name) o = parent[name] o.setTitle(kwargs.get('title')) o.reindexObject() return o
def _infoDictForType(portal, ptype): """ UI type infos @param ptype: a portal type name @return: {'portal_type': xxx, 'type_ui_info': UI type info} """ portal_types = getToolByName(portal, 'portal_types') type_info = getattr(portal_types, ptype) title = type_info.Title() if HAS_DEXTERITY and IDexterityFTI.providedBy(type_info): product = type_info.klass else: product = type_info.product type_ui_info = ("%s (portal type: %s, product: %s)" % (portal.translate(title, default=title), ptype, product)) return {'portal_type': ptype, 'type_ui_info': type_ui_info}
def move_dotted_to_named_behaviors(context): """named behaviors are better then dotted behaviors > let's move them.""" from plone import api from plone.behavior.registration import lookup_behavior_registration from plone.dexterity.interfaces import IDexterityFTI ptt = api.portal.get_tool('portal_types') ftis = [fti for fti in ptt.objectValues() if IDexterityFTI.providedBy(fti)] for fti in ftis: behaviors = [] for behavior in fti.behaviors: behavior_registration = lookup_behavior_registration(behavior) named_behavior = behavior_registration.name if named_behavior: behaviors.append(named_behavior) if named_behavior == behavior: logger.info( 'Behavior "{behavior}" already named.'.format( behavior=behavior, ), ) else: logger.info( 'Moved "{dotted}" to "{named}"'.format( dotted=behavior, named=named_behavior, ), ) else: behaviors.append(behavior) logger.info( '"{dotted}" has no name registered. ' 'kept it dotted.'.format( dotted=behavior, ), ) fti.behaviors = tuple(behaviors) logger.info( 'Converted dotted behaviors of {ct} to named behaviors.'.format( ct=fti.title, ), ) logger.info('Done moving dotted to named behaviors.')
def create_file_from_request(self, name): context = self.context filedata = self.request.form.get(name, None) if not filedata: return filename = filedata.filename content_type = mimetypes.guess_type(filename)[0] or "" # Determine if the default file/image types are DX or AT based ctr = api.portal.get_tool('content_type_registry') type_ = ctr.findTypeName(filename.lower(), content_type, '') if not type_ == 'Image': type_ = 'File' pt = api.portal.get_tool('portal_types') if IDexterityFTI.providedBy(getattr(pt, type_)): obj = self.create_dx_file(filename, content_type, filedata, type_) self.post_factory(obj) notify(ObjectCreatedEvent(obj)) if hasattr(obj, 'file'): size = obj.file.getSize() content_type = obj.file.contentType elif hasattr(obj, 'image'): size = obj.image.getSize() content_type = obj.image.contentType else: return result = {"type": content_type, "size": size} else: from Products.ATContentTypes.interfaces import IATCTFileFactory obj = IATCTFileFactory(context)(filename, content_type, filedata) self.post_factory(obj) try: size = obj.getSize() except AttributeError: size = obj.getObjSize() result = {"type": obj.getContentType(), "size": size} result.update({ 'url': obj.absolute_url(), 'name': obj.getId(), 'UID': IUUID(obj), 'filename': filename }) return result
def _getDexterityFolderTypes(portal): try: from plone.dexterity.interfaces import IDexterityFTI from plone.dexterity.utils import resolveDottedName from Products.CMFPlone.interfaces.syndication import ISyndicatable except ImportError: return set([]) portal_types = getToolByName(portal, 'portal_types') types = [fti for fti in portal_types.listTypeInfo() if IDexterityFTI.providedBy(fti)] ftypes = set([]) for _type in types: klass = resolveDottedName(_type.klass) if ISyndicatable.implementedBy(klass): ftypes.add(_type.getId()) return ftypes