def move_repository_reference_mappings(self, obj): intids = getUtility(IIntIds) annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): repository_mapping = PersistentDict( {CHILD_REF_KEY: {}, PREFIX_REF_KEY: {}}) dossier_mapping = PersistentDict( {CHILD_REF_KEY: {}, PREFIX_REF_KEY: {}}) for number, intid in annotations.get(CHILD_REF_KEY).items(): try: child = intids.getObject(intid) except KeyError: # the object with this intid does not longer exist. continue if IDossierMarker.providedBy(child): dossier_mapping[CHILD_REF_KEY][number] = intid dossier_mapping[PREFIX_REF_KEY][intid] = number else: repository_mapping[CHILD_REF_KEY][number] = intid repository_mapping[PREFIX_REF_KEY][intid] = number # save mapping annotations[REPOSITORY_FOLDER_KEY] = repository_mapping annotations[DOSSIER_KEY] = dossier_mapping # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
class TilesPermissions(object): """ An adapter that will provide store permissions for a tile """ implements(ITilesPermissions) def __init__(self, context, request, tile): self.context = context self.request = request self.tile = tile self.annotations = IAnnotations(self.context) self.key = '{0}.{1}'.format(ANNOTATIONS_KEY_PREFIX, tile.id) def get_allowed_edit(self): permissions = dict(self.annotations.get(self.key, {})) return permissions.get('edit', ()) def set_allowed_edit(self, group_ids): permissions = dict(self.annotations.get(self.key, {})) if isinstance(group_ids, list): group_ids = tuple(group_ids) elif isinstance(group_ids, basestring): group_ids = (group_ids,) permissions['edit'] = group_ids self.annotations[self.key] = PersistentDict(permissions) def delete(self): self.annotations.pop(self.key, None) return
class TilesConfigurationScreen(object): """ An adapter that will provide the configuration screens functionality """ implements(ITilesConfigurationScreen) def __init__(self, context, request, tile): self.context = context self.request = request self.tile = tile self.annotations = IAnnotations(self.context) self.key = '{0}.{1}'.format(ANNOTATIONS_KEY_PREFIX, tile.id) def _set_default_configuration(self): defaults = {} tile_type = getUtility(ITileType, name=self.tile.__name__) fields = getFieldNamesInOrder(tile_type.schema) for name, field in getFieldsInOrder(tile_type.schema): order = unicode(fields.index(name)) # default configuration attributes for all fields defaults[name] = {'order': order, 'visibility': u'on'} if name == 'css_class': # css_class, set default defaults[name] = field.default if ITextLine.providedBy(field): # field is TextLine, we should add 'htmltag' defaults[name]['htmltag'] = u'h2' elif INamedBlobImageField.providedBy(field): # field is an image, we should add 'position' and 'imgsize' defaults[name]['position'] = u'left' defaults[name]['imgsize'] = u'mini 200:200' elif IInt.providedBy(field): defaults[name][name] = field.default elif IDatetime.providedBy(field): # field is Datetime, we should add 'format' defaults[name]['format'] = 'datetime' return defaults def get_configuration(self): data = dict(self.annotations.get(self.key, {})) if not data: # tile has no configuration; let's apply the default one data = self._set_default_configuration() return data def set_configuration(self, configuration): self.annotations[self.key] = PersistentDict(configuration) def delete(self): self.annotations.pop(self.key, None) return
class TilesConfigurationScreen(object): """ An adapter that will provide the configuration screens functionality """ def __init__(self, context, request, tile): self.context = context self.request = request self.tile = tile self.annotations = IAnnotations(self.context) self.key = '{0}.{1}'.format(ANNOTATIONS_KEY_PREFIX, tile.id) def _set_default_configuration(self): defaults = {} tile_type = getUtility(ITileType, name=self.tile.__name__) fields = getFieldNamesInOrder(tile_type.schema) for name, field in getFieldsInOrder(tile_type.schema): order = unicode(fields.index(name)) # default configuration attributes for all fields defaults[name] = {'order': order, 'visibility': u'on'} if name == 'css_class': # css_class, set default defaults[name] = field.default if ITextLine.providedBy(field): # field is TextLine, we should add 'htmltag' defaults[name]['htmltag'] = u'h2' elif INamedBlobImageField.providedBy(field): # field is an image, we should add 'position' and 'imgsize' defaults[name]['position'] = u'left' defaults[name]['imgsize'] = u'mini 200:200' elif IInt.providedBy(field): defaults[name][name] = field.default elif IDatetime.providedBy(field): # field is Datetime, we should add 'format' defaults[name]['format'] = 'datetime' return defaults def get_configuration(self): data = dict(self.annotations.get(self.key, {})) if not data: # tile has no configuration; let's apply the default one data = self._set_default_configuration() return data def set_configuration(self, configuration): self.annotations[self.key] = PersistentDict(configuration) def delete(self): self.annotations.pop(self.key, None) return
def move_dossier_mappings(self, obj): annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): dossier_mapping = PersistentDict( {CHILD_REF_KEY: annotations.get(CHILD_REF_KEY), PREFIX_REF_KEY: annotations.get(PREFIX_REF_KEY)}) annotations[DOSSIER_KEY] = dossier_mapping # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
def move_repository_reference_mappings(self, obj): intids = getUtility(IIntIds) annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): repository_mapping = PersistentDict({ CHILD_REF_KEY: PersistentDict(), PREFIX_REF_KEY: PersistentDict() }) dossier_mapping = PersistentDict({ CHILD_REF_KEY: PersistentDict(), PREFIX_REF_KEY: PersistentDict() }) for number, intid in annotations.get(CHILD_REF_KEY).items(): try: child = intids.getObject(intid) except KeyError: # the object with this intid does not longer exist. continue if IDossierMarker.providedBy(child): dossier_mapping[CHILD_REF_KEY][number] = intid dossier_mapping[PREFIX_REF_KEY][intid] = number else: repository_mapping[CHILD_REF_KEY][number] = intid repository_mapping[PREFIX_REF_KEY][intid] = number # save mapping annotations[REPOSITORY_FOLDER_KEY] = repository_mapping annotations[DOSSIER_KEY] = dossier_mapping # check new annotations if not is_persistent(annotations[REPOSITORY_FOLDER_KEY]): raise Exception( "The REPOSITORY_FOLDER_KEY mapping is not persistent for %s." % obj.Title()) if not is_persistent(annotations[DOSSIER_KEY]): raise Exception( "The DOSSIER_KEY mapping is not persistent for %s." % obj.Title()) # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
def init_stats(): """Setup stats storage. A simple OOBTree """ portal = api.portal.get() annotations = IAnnotations(portal) annotations.pop('org.bccvl.site.stats', None) if 'org.bccvl.site.stats' not in annotations: stats = PersistentDict() # per user stats stats['users'] = OOBTree() stats['datasets'] = DatasetStats() stats['experiments'] = ExperimentStats() stats['jobs'] = JobStats() annotations['org.bccvl.site.stats'] = stats
def cleanUp(self): numDelete = 0 users = IAnnotations(api.portal.get())[Survey.KEY] for userId in users.keys(): user = users.pop(userId) del user numDelete += 1 return numDelete
def move_dossier_mappings(self, obj): annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): dossier_mapping = PersistentDict( {CHILD_REF_KEY: annotations.get(CHILD_REF_KEY), PREFIX_REF_KEY: annotations.get(PREFIX_REF_KEY)}) annotations[DOSSIER_KEY] = dossier_mapping # check new annotations if not is_persistent(annotations[DOSSIER_KEY]): raise Exception( "The DOSSIER_KEY mapping is not persistent for %s." % obj.Title()) # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
def move_repository_root_mappings(self, obj): annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): repo_mapping = PersistentDict( {CHILD_REF_KEY: annotations.get(CHILD_REF_KEY), PREFIX_REF_KEY: annotations.get(PREFIX_REF_KEY)}) annotations[REPOSITORY_FOLDER_KEY] = repo_mapping # check new annotations if not is_persistent(annotations[REPOSITORY_FOLDER_KEY]): raise Exception( "The REPOSITORY_FOLDER_KEY mapping is not persistent for %s." % obj.Title()) # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
def uninstall(portal, reinstall=False): """Remove slideshow_folder_view from display list, reset folder display""" if reinstall: return logger = logging.getLogger("collective.easyslideshow") pt = portal.portal_types pc = getToolByName(portal, 'portal_catalog') brains = pc.searchResults(portal_type='Folder') # remove annotations and interfaces for brain in brains: folder = brain.getObject() if folder.getProperty("layout") is not None: if folder.layout == "slideshow_folder_view": folder.layout = "folder_listing" noLongerProvides(folder, p4ainterfaces.ISubtyped) noLongerProvides(folder, essinterfaces.ISlideshowFolder) annotations = IAnnotations(folder) if annotations.get('easyslideshow.slideshowmanager.props'): annotations.pop('easyslideshow.slideshowmanager.props') psD = annotations.get('p4a.subtyper.DescriptorInfo') if psD and psD.get('descriptor_name')\ and psD['descriptor_name'] == 'collective.easyslideshow.slideshow': annotations.pop('p4a.subtyper.DescriptorInfo') # remove portlet-assignments allbrains = pc() for brain in allbrains: item = brain.getObject() for column in ['plone.leftcolumn', 'plone.rightcolumn']: manager = getUtility(IPortletManager, name=column) try: assignments = getMultiAdapter((item, manager), IPortletAssignmentMapping) except ComponentLookupError, e: logger.error("Ignoring broken portlet: %s" % str(e)) if assignments: for key in assignments.keys(): if key.startswith('slideshow-portlet'): del assignments[key]
def uninstall(portal, reinstall=False): """Remove slideshow_folder_view from display list, reset folder display""" if reinstall: return logger = logging.getLogger("collective.easyslideshow") pt = portal.portal_types pc = getToolByName(portal, 'portal_catalog') brains = pc.searchResults(portal_type='Folder') # remove annotations and interfaces for brain in brains: folder = brain.getObject() if folder.getProperty("layout") is not None: if folder.layout == "slideshow_folder_view": folder.layout = "folder_listing" noLongerProvides(folder, p4ainterfaces.ISubtyped) noLongerProvides(folder, essinterfaces.ISlideshowFolder) annotations = IAnnotations(folder) if annotations.get('easyslideshow.slideshowmanager.props'): annotations.pop('easyslideshow.slideshowmanager.props') psD = annotations.get('p4a.subtyper.DescriptorInfo') if psD and psD.get('descriptor_name')\ and psD['descriptor_name'] == 'collective.easyslideshow.slideshow': annotations.pop('p4a.subtyper.DescriptorInfo') # remove portlet-assignments allbrains = pc() for brain in allbrains: item = brain.getObject() for column in ['plone.leftcolumn', 'plone.rightcolumn']: manager = getUtility(IPortletManager, name=column) try: assignments = getMultiAdapter((item, manager), IPortletAssignmentMapping) except ComponentLookupError, e: logger.error("Ignoring broken portlet: %s" % str(e)) if assignments: for key in assignments.keys(): if key.startswith('slideshow-portlet'): del assignments[key]
def move_dossier_mappings(self, obj): annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): dossier_mapping = PersistentDict({ CHILD_REF_KEY: annotations.get(CHILD_REF_KEY), PREFIX_REF_KEY: annotations.get(PREFIX_REF_KEY) }) annotations[DOSSIER_KEY] = dossier_mapping # check new annotations if not is_persistent(annotations[DOSSIER_KEY]): raise Exception( "The DOSSIER_KEY mapping is not persistent for %s." % obj.Title()) # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
def move_repository_root_mappings(self, obj): annotations = IAnnotations(obj) if annotations and annotations.get(CHILD_REF_KEY): repo_mapping = PersistentDict({ CHILD_REF_KEY: annotations.get(CHILD_REF_KEY), PREFIX_REF_KEY: annotations.get(PREFIX_REF_KEY) }) annotations[REPOSITORY_FOLDER_KEY] = repo_mapping # check new annotations if not is_persistent(annotations[REPOSITORY_FOLDER_KEY]): raise Exception( "The REPOSITORY_FOLDER_KEY mapping is not persistent for %s." % obj.Title()) # drop old mapings annotations.pop(CHILD_REF_KEY) annotations.pop(PREFIX_REF_KEY)
class ListSource(object): classProvides(ISectionBlueprint) implements(ISection) def __init__(self, transmogrifier, name, options, previous): self.previous = previous self.items = IAnnotations(transmogrifier).setdefault(LISTKEY, {}).setdefault(name, []) def __iter__(self): for item in self.previous: yield item while self.items: appended = self.items.pop(0) yield appended
class ListSource(object): classProvides(ISectionBlueprint) implements(ISection) def __init__(self, transmogrifier, name, options, previous): self.previous = previous self.items = IAnnotations(transmogrifier).setdefault(LISTKEY, {}).setdefault( name, []) def __iter__(self): for item in self.previous: yield item while self.items: appended = self.items.pop(0) yield appended
class PloneKeyczarCrypter(BaseCrypter): """ depends on keyczar-python to imeplement Plone Crypter. """ def __init__(self, context): self.context = context self.enableLog = aq_inner(self.context).enableLog self.anno = IAnnotations(self.context) if not self.anno.has_key(LOGGING_KEY): self.anno[LOGGING_KEY] = [] if not self.anno.has_key(KEYCZAR_ANNO_KEYS): self.anno[KEYCZAR_ANNO_KEYS] = {} if not self.anno.has_key(KEYCZAR_ANNO_META): # create one with default settings. self.createKeyset() self.addPrimaryKey() def log(self, message): """ logging the keys management. """ if not self.enableLog: # log not enabled! just return return # preparing the logging message. fmtMessage = '%s - %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), message) # logging as reverse order. self.anno[LOGGING_KEY].insert(0, fmtMessage) def clearLogs(self): self.anno[LOGGING_KEY] = [] def getLogs(self): """ return all logs if have. """ return self.anno[LOGGING_KEY] def keysAmount(self): """ return the total amount of keys. """ return len(self.anno[KEYCZAR_ANNO_KEYS]) def writeAnnotations(self, keyczar): # update the key storage. self.anno[KEYCZAR_ANNO_META] = str(keyczar.metadata) for v in keyczar.versions: self.anno[KEYCZAR_ANNO_KEYS][v.version_number] = str(keyczar.GetKey(v)) def createKeyset(self, asymmetric=keyinfo.RSA_PRIV): """ create a new keyset and save to the annotation """ name = 'PloneCrypter' # only using the encrypt/decrypt purpose for now. purpose = keyinfo.DECRYPT_AND_ENCRYPT kmd = KeyMetadata(name, purpose, asymmetric) self.anno[KEYCZAR_ANNO_META] = str(kmd) def addPrimaryKey(self): """ add a new key as primary key. """ keyczar = GenericKeyczar(AnnotationReader(self.context)) status = keyinfo.PRIMARY size = None keyczar.AddVersion(status, size) self.writeAnnotations(keyczar) self.log("Added a new key as primary key; we have %s keys in total!" \ % len(keyczar.versions)) def removeOldestKey(self): """ remove the oldest key from the chain. """ # find out the oldest key, # the key with smallest version number will be the oldest key. versions = self.anno[KEYCZAR_ANNO_KEYS].keys() versions.sort() oldest_version = versions[0] keyczar = GenericKeyczar(AnnotationReader(self.context)) # suppose the oldest key is in active status keyczar.Demote(oldest_version) keyczar.Revoke(oldest_version) self.writeAnnotations(keyczar) self.anno[KEYCZAR_ANNO_KEYS].pop(oldest_version) self.log("Removed the oldest key: %s; we have %s keys in total!" \ % (oldest_version, len(keyczar.versions) -1)) def clearKeys(self): """ remove the key metadata and destroy all keys. """ keyczar = GenericKeyczar(AnnotationReader(self.context)) for v in keyczar.versions: self.anno[KEYCZAR_ANNO_KEYS].pop(v.version_number) self.anno.pop(KEYCZAR_ANNO_META) self.log("Retired / Removed all %s keys!" % len(keyczar.versions)) self.createKeyset() self.addPrimaryKey() def encrypt(self, message): crypter = Crypter(AnnotationReader(self.context)) return crypter.Encrypt(message) def decrypt(self, message): crypter = Crypter(AnnotationReader(self.context)) return crypter.Decrypt(message)
class PloneKeyczarCrypter(BaseCrypter): """ depends on keyczar-python to imeplement Plone Crypter. """ def __init__(self, context): self.context = context self.metaKey = '%s.%s' % (KEYCZAR_ANNO_KEY, 'meta') self.anno = IAnnotations(self.context) if not self.anno.has_key(self.metaKey): # create one with default settings. self.createKeyset() self.addPrimaryKey() def createKeyset(self, asymmetric=keyinfo.RSA_PRIV): """ create a new keyset and save to the annotation """ name = 'PloneCrypter' # only using the encrypt/decrypt purpose for now. purpose = keyinfo.DECRYPT_AND_ENCRYPT kmd = KeyMetadata(name, purpose, asymmetric) self.anno[self.metaKey] = str(kmd) def addPrimaryKey(self): """ add a new key as primary key. """ keyczar = GenericKeyczar(AnnotationReader(self.context)) status = keyinfo.PRIMARY size = None keyczar.AddVersion(status, size) # update the key storage. self.anno[self.metaKey] = str(keyczar.metadata) for v in keyczar.versions: keyKey = '%s.%s' % (KEYCZAR_ANNO_KEY, str(v.version_number)) self.anno[keyKey] = str(keyczar.GetKey(v)) def clearKeys(self): """ remove the key metadata and destroy all keys. """ keyczar = GenericKeyczar(AnnotationReader(self.context)) for v in keyczar.versions: keyKey = '%s.%s' % (KEYCZAR_ANNO_KEY, str(v.version_number)) self.anno.pop(keyKey) self.anno.pop(self.metaKey) def encrypt(self, message): crypter = Crypter(AnnotationReader(self.context)) return crypter.Encrypt(message) def decrypt(self, message): crypter = Crypter(AnnotationReader(self.context)) return crypter.Decrypt(message)