Beispiel #1
0
def RemoveAnnotations(portal_setup):
    plone = portal_setup.portal_url.getPortalObject()

    annotations = IAnnotations(plone)
    if annotations.has_key('publisher-queue'):
        del annotations['publisher-queue']
    if annotations.has_key('publisher-realms'):
        del annotations['publisher-realms']
    if annotations.has_key('publisher-dataFolder'):
        del annotations['publisher-dataFolder']

    savepoint(1)
Beispiel #2
0
    def getClearedCopyright(self):
        """ Get the clear copyright value from the object  """
        annotations = IAnnotations(self.context)
	if annotations.has_key('eduCommons.clearcopyright'):
            return annotations['eduCommons.clearcopyright']
        else:
	    return
Beispiel #3
0
def appendObjPosition(object):
    if not object.isTemporary():
        ecutil = queryUtility(IECUtility)
        if ecutil:
            parent = ecutil.FindECParent(object)
            if parent.Type() == 'Course':
                path = {'path':{'query':'/'.join(parent.getPhysicalPath())+'/'},}
                brains = object.portal_catalog.searchResults(path)
                if brains:
                    pos = [0,]
                    for brain in brains:
                        obj = brain.getObject()
                        annotations = IAnnotations(obj)
                        if annotations.has_key('eduCommons.objPositionInCourse'):
                            pos += [annotations['eduCommons.objPositionInCourse'],]
                    maxpos = max(pos)
                    if maxpos > 0:
                        maxpos += 1
                    else:
                        maxpos = 1
                else:
                    maxpos = 1
                
                annotations = IAnnotations(object)
                annotations['eduCommons.objPositionInCourse'] = maxpos

                zipobj = getattr(parent, parent.id + '.zip', None)
                if zipobj:
                    IAnnotations(zipobj)['eduCommons.objPositionInCourse'] = maxpos + 1
                    zipobj.reindexObject()
Beispiel #4
0
    def appendObjPosition(self,object):
        
        maxpos = 1

        ecutil = queryUtility(IECUtility)
        if ecutil:
            parent = ecutil.FindECParent(object)
            if parent.Type() == 'Course':
                path = {'path':{'query':'/'.join(parent.getPhysicalPath())+'/'},}
                brains = object.portal_catalog.searchResults(path)
                if brains:
                    pos = [0,]
                    for brain in brains:
                        obj = brain.getObject()
                        annotations = IAnnotations(obj)
                        if annotations.has_key('eduCommons.objPositionInCourse'):
                            pos += [annotations['eduCommons.objPositionInCourse'],]
                    maxpos = max(pos)
                    if maxpos > 0:
                        maxpos += 1
                    else:
                        maxpos = 1
                else:
                    maxpos = 1
                    
                annotations = IAnnotations(object)
                annotations['eduCommons.objPositionInCourse'] = maxpos
                
        return maxpos 
Beispiel #5
0
    def getAccessibilityCompliant(self):
        """ Get the Accessibility Compliant value from the object  """
        annotations = IAnnotations(self.context)
	if annotations.has_key('eduCommons.accessible'):
            return annotations['eduCommons.accessible']
        else:
	    return
Beispiel #6
0
 def cleanComments(self):
     """
     """
     annotations = IAnnotations(self.context)
     if annotations.has_key(self.key):
         del annotations[self.key]
     self._comments = None
    def migrate_ratings(self):
        """
      contentratings and twothumbs both use annotations. Just want to move 
      one to another. Here we say anything >= 3 rating is a thumbs up
      """

        from cioppino.twothumbs import rate as thumbrate

        transaction.begin()
        item = self.obj
        annotations = IAnnotations(item)
        if annotations:
            if annotations.has_key('contentratings.userrating.psc_stars'):
                ratings = annotations[
                    'contentratings.userrating.psc_stars'].all_user_ratings()
                annotations = thumbrate.setupAnnotations(item)
                for rating in ratings:
                    userid = rating.userid
                    value = rating._rating

                    if rating >= 3.0:
                        thumbrate.loveIt(item, rating.userid)
                    else:
                        thumbrate.hateIt(item, rating.userid)

        # we need to reindex th object anyways
        item.reindexObject()
        transaction.commit()
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     key = self.annotations_key
     if not annotations.has_key(key):
         annotations[key] = PersistentMapping()
     self.storage = annotations[key]
Beispiel #9
0
def appendObjPosition(object):
    if not object.isTemporary():
        ecutil = queryUtility(IECUtility)
        if ecutil:
            parent = ecutil.FindECParent(object)
            if parent.Type() == "Course":
                path = {"path": {"query": "/".join(parent.getPhysicalPath()) + "/"}}
                brains = object.portal_catalog.searchResults(path)
                if brains:
                    pos = [0]
                    for brain in brains:
                        obj = brain.getObject()
                        annotations = IAnnotations(obj)
                        if annotations.has_key("eduCommons.objPositionInCourse"):
                            pos += [annotations["eduCommons.objPositionInCourse"]]
                    maxpos = max(pos)
                    if maxpos > 0:
                        maxpos += 1
                    else:
                        maxpos = 1
                else:
                    maxpos = 1

                annotations = IAnnotations(object)
                annotations["eduCommons.objPositionInCourse"] = maxpos

                zipobj = getattr(parent, parent.id + ".zip", None)
                if zipobj:
                    IAnnotations(zipobj)["eduCommons.objPositionInCourse"] = maxpos + 1
                    zipobj.reindexObject()
Beispiel #10
0
    def _criteria(self):
        cache = IAnnotations(self.request)
        key = 'eea.facetednav.%s' % self.context.UID()

        if not cache.has_key(key):
            cache[key] = self.__criteria()

        return cache[key]
Beispiel #11
0
    def _criteria(self):
        cache = IAnnotations(self.request)
        key = 'eea.facetednav.%s' % self.context.UID()

        if not cache.has_key(key):
            cache[key] = self.__criteria()

        return cache[key]
Beispiel #12
0
 def hasComments(self):
     """
     """
     annotations = IAnnotations(self.context)
     if annotations.has_key(self.key):
         return True
     else:
         return False
Beispiel #13
0
 def __call__(self):
     """ """
     annotations = IAnnotations(self.context)
     if annotations.has_key(ANNOTATION_KEY):
         del annotations[ANNOTATION_KEY]
         return "CLEARED"
     else:
         return "NOTHING TO CLEAR"
Beispiel #14
0
def get_priority_sitemapxml(object, **kw):
    try:
        annotations = IAnnotations(object)
        if annotations.has_key('pSEO_priority_sitemapxml'):
            return annotations.get('pSEO_priority_sitemapxml', None)
    except:
        return None
    return None
Beispiel #15
0
 def __call__(self):
     """ """
     annotations = IAnnotations(self.context)
     if annotations.has_key(ANNOTATION_KEY):
         del annotations[ANNOTATION_KEY]
         return "CLEARED"
     else:
         return "NOTHING TO CLEAR"
Beispiel #16
0
    def getCachedValue(func, key, name):
        request = getRequest()

        cache = IAnnotations(request)

        if not cache.has_key(key):
            cache[key] = func(name)

        return cache[key]
 def modifications(self):
     """ Handle storage for the modification list """
     key = self.__class__.__name__
     if self._modifications is None:
         annotations = IAnnotations(self.context)
         if not annotations.has_key(key):
             annotations[key] = PersistentMapping()
         self._modifications = annotations[key]
     return self._modifications
Beispiel #18
0
    def getCachedValue(func, key, name):
        request = getRequest()

        cache = IAnnotations(request)

        if not cache.has_key(key):
            cache[key] = func(name)

        return cache[key]
Beispiel #19
0
 def __getattr__(self, key):
     """ """
     context = self.__dict__['context']
     if not IAnnotatable.providedBy(context):
         alsoProvides(context, IAnnotatable)
     annos = IAnnotations(context).get(ANNOTATION_KEY, {})
     if annos.has_key(key): 
         return annos[key]
     raise AttributeError
Beispiel #20
0
 def comments(self):
     """
     """
     if self._comments is None:
         annotations = IAnnotations(self.context)
         if not annotations.has_key(self.key):
             annotations[self.key] = OrderedPersistentDict()
         self._comments = annotations[self.key]
     return self._comments
Beispiel #21
0
    def __init__(self, context):

        self.context = context
        annotations = IAnnotations(context)

        if not annotations.has_key(KEY):
            annotations[KEY] = OOBTree()

        self.dates = annotations[KEY]
Beispiel #22
0
    def _storage(self):
        if self._store:
            return self._store

        annotation = IAnnotations(self.context)
        if annotation.has_key(self._key):
            self._store = annotation[self._key]
        else:
            annotation[self._key] = self._store = PersistentList()
        return self._store
Beispiel #23
0
class BaseStorage(object):

    adapts(INavigationRoot)
    implements(IDigestStorage)

    key = NotImplemented
    label = NotImplemented

    def __init__(self, context):
        self.annotations = IAnnotations(context)

    def purge_now(self):
        raise NotImplementedError

    def store_activity(self, subscriber, activity_key, info):
        value = PersistentDict(**info)
        key = '%s-digest' % self.key
        if not key in self.annotations:
            self.annotations[key] = OOBTree()

        if not subscriber in self.annotations[key]:
            self.annotations[key][subscriber] = PersistentDict()

        if activity_key not in self.annotations[key][subscriber]:
             self.annotations[key][subscriber][activity_key] = PersistentList()

        self.annotations[key][subscriber][activity_key].append(value)

    def pop(self):
        """Gets
        """
        key = '%s-digest' % self.key
        self.annotations['%s-digest-last-purge' % key] = DateTime()
        if not key in self.annotations:
            return {}

        activity = deepcopy(self.annotations[key])
        self.annotations[key] = PersistentDict()
        return activity

    def last_purge(self):
        key = '%s-digest-last-purge' % self.key
        if not self.annotations.has_key(key):
            return None
        else:
            return self.annotations[key]

    def purge_user(self, subscriber):
        key = '%s-digest' % self.key
        if key in self.annotations:
            if subscriber in self.annotations[key]:
                del self.annotations[key][subscriber]
Beispiel #24
0
class BaseStorage(object):

    adapts(INavigationRoot)
    implements(IDigestStorage)

    key = NotImplemented
    label = NotImplemented

    def __init__(self, context):
        self.annotations = IAnnotations(context)

    def purge_now(self):
        raise NotImplementedError

    def store_activity(self, subscriber, activity_key, info):
        value = PersistentDict(**info)
        key = '%s-digest' % self.key
        if not key in self.annotations:
            self.annotations[key] = OOBTree()

        if not subscriber in self.annotations[key]:
            self.annotations[key][subscriber] = PersistentDict()

        if activity_key not in self.annotations[key][subscriber]:
            self.annotations[key][subscriber][activity_key] = PersistentList()

        self.annotations[key][subscriber][activity_key].append(value)

    def pop(self):
        """Gets
        """
        key = '%s-digest' % self.key
        self.annotations['%s-digest-last-purge' % key] = DateTime()
        if not key in self.annotations:
            return {}

        activity = deepcopy(self.annotations[key])
        self.annotations[key] = PersistentDict()
        return activity

    def last_purge(self):
        key = '%s-digest-last-purge' % self.key
        if not self.annotations.has_key(key):
            return None
        else:
            return self.annotations[key]

    def purge_user(self, subscriber):
        key = '%s-digest' % self.key
        if key in self.annotations:
            if subscriber in self.annotations[key]:
                del self.annotations[key][subscriber]
    def get(self, name):
        # first check overrides if exists and is True
        overrides = getattr(self, '%s_override' % name, True)
        if not overrides:
            return None

        context = aq_inner(self.context)
        if not IAnnotatable.providedBy(self.context):
            return None
        annotations = IAnnotations(context)
        if annotations.has_key(PERSEO):
            return annotations[PERSEO].get(name, None)
        return None
Beispiel #26
0
    def addTitle(self):
        """Adds title to IFormatables
        """
        catalog = getToolByName(self.context, "portal_catalog")
        brains = catalog.searchResults(
            object_provides="easyshop.core.interfaces.catalog.IFormatable")

        for brain in brains:
            object = brain.getObject()
            annotations = IAnnotations(object)
            if annotations.has_key(KEY) == True:
                annotations[KEY]["title"] = "title"
                annotations[KEY]["chars"] = "0"
Beispiel #27
0
    def addTitle(self):
        """Adds title to IFormatables
        """
        catalog = getToolByName(self.context, "portal_catalog")
        brains = catalog.searchResults(
            object_provides = "easyshop.core.interfaces.catalog.IFormatable"
        )

        for brain in brains:
            object = brain.getObject()
            annotations = IAnnotations(object)
            if annotations.has_key(KEY) == True:
                annotations[KEY]["title"] = "title"
                annotations[KEY]["chars"] = "0"
def setup_metadata(obj):
    annotations = IAnnotations(obj, None)
    if not annotations.has_key('plumi.video_info'):
        annotations['plumi.video_info'] = PersistentMapping()
    video_info = annotations.get('plumi.video_info')

    filename = obj.video_file.getBlob().committed()
    if not filename:
        return

    metadata = extract(filename)
    try:
        video_info['width'] = metadata.get('width')
        video_info['height'] = metadata.get('height')
        video_info['aspect_ratio'] = video_info['width']/video_info['height']
    except (ValueError, AttributeError):
        logger.info('Could not get video dimensions')
    try:
        video_info['duration'] = metadata.get('duration')
    except (ValueError, AttributeError):
        logger.info('Could not get video duration')
Beispiel #29
0
    def compiled_data(self):

        cache = IAnnotations(self.request)
        key = self.cache_key

        if not cache.has_key(key):

            _ = {}

            for i in self._data:
                if not i.get('product_status', None) == u'Approved':
                    continue
                for k in self.keys:
                    if not _.has_key(k):
                        _[k] = {}
                    v = i.get(k, None)
                    if v:
                        _[k][v] = i

            cache[key] = _

        return cache[key]
Beispiel #30
0
    def _getClickdatesObjects(self):
        """returns all objects with clickdates annotation
        """
        catalog = getToolByName(self.context, "portal_catalog")

        # beware: index 'object_provides' is not available in Plone 2.1 and 2.5!
        # Please provide the index by hand or programmatically. You can
        # use the code from Plone 3.x (CatalogTool)
        #
        # XXX 2011-09-06 bislang wurden hier nur die journalpaper geholt.
        brains = catalog(object_provides=
                         "zbw.ejClickdates.interfaces.IClickdatesAnnotatable",
                         sort_on="created",
                         sort_order="descending")
        result = []
        for brain in brains:
            obj = brain.getObject(
            )  # optimize! clickdates sollten in irgendeiner Form in den catalog.
            annotations = IAnnotations(obj)
            if annotations.has_key(ANNOTATION):
                result.append(obj)

        return result
Beispiel #31
0
    def __new__(cls, context):
        instance = super(NameFromCreation, cls).__new__(cls)
        site = getUtility(ISiteRoot)
        storage = IAnnotations(site, {})
        cdate = context.creation_date
        current_date = "%d%s%s" % (cdate.year(), cdate.mm(), cdate.dd())

        if not storage.has_key(ANNOTATION_DATE_ID):
            storage[ANNOTATION_DATE_ID] = current_date
            dateid = current_date
        else:
            dateid = storage.get(ANNOTATION_DATE_ID)

        if dateid != current_date:
            dateid = current_date
            storage[ANNOTATION_DATE_ID] = current_date
            nextid = 1
        else:
            nextid = storage.get(ANNOTATION_NEXT_ID, 1)

        storage[ANNOTATION_NEXT_ID] = nextid + 1

        instance.title = '%s%s' % (dateid, str(nextid).zfill(2))
        return instance
Beispiel #32
0
    def __new__(cls, context):
        instance = super(NameFromCreated, cls).__new__(cls)
        site = getUtility(ISiteRoot)
        storage = IAnnotations(site, {})
        cdate = context.creation_date
        current_date = "%d%s%s" % (cdate.year() , cdate.mm() , cdate.dd())

        if not storage.has_key(ANNOTATION_DATE_ID):
            storage[ANNOTATION_DATE_ID] = current_date
            dateid = current_date
        else:
            dateid = storage.get(ANNOTATION_DATE_ID)

        if dateid != current_date:
            dateid = current_date
            storage[ANNOTATION_DATE_ID] = current_date
            nextid = 1
        else:
            nextid = storage.get(ANNOTATION_NEXT_ID , 1)

        storage[ANNOTATION_NEXT_ID] = nextid + 1

        instance.title = '%s%s' % (dateid , str(nextid).zfill(2))
        return instance
Beispiel #33
0
def DeployedAdapter(site):
    """ returns DeployedStore of site """
    annotations = IAnnotations(site)
    if not annotations.has_key(ANNOTATION_KEY):
        annotations[ANNOTATION_KEY] = DeployedStore()
    return annotations[ANNOTATION_KEY]
 def ruleset_data(self):
     storage = IAnnotations(self)
     if not storage.has_key(RULESET_DATA_ANNOTATIONS_KEY):
         storage[RULESET_DATA_ANNOTATIONS_KEY] = PersistentDict()
     return storage[RULESET_DATA_ANNOTATIONS_KEY]
Beispiel #35
0
def SynchroAdapter(site):
    """ returns SynchroStore of site """
    annotations = IAnnotations(site)
    if not annotations.has_key(ANNOTATION_KEY):
        annotations[ANNOTATION_KEY] = SynchroStore()
    return annotations[ANNOTATION_KEY]
Beispiel #36
0
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)
 def relations(self):
     storage = IAnnotations(self)
     if not storage.has_key(RELATIONS_ANNOTATIONS_KEY):
         storage[RELATIONS_ANNOTATIONS_KEY] = relations.RelationContainer()
     return storage[RELATIONS_ANNOTATIONS_KEY]
 def enabled(self):
     context = self.context
     annotations = IAnnotations(context)
     return annotations.has_key(ANN_CUSTOMMENU_KEY)
 def getSavedCustomizations(self):
     context = self.context
     annotations = IAnnotations(context)
     if annotations.has_key(ANN_CUSTOMMENU_KEY):
         return annotations[ANN_CUSTOMMENU_KEY]
     return ({'inherit': True}, [])
Beispiel #40
0
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)