def render(self):
        context = self.context
        annotations = IAnnotations(context)
        status = annotations.get(STATUS_STORAGE_KEY, None)
        named_file = annotations.get(DATA_STORAGE_KEY, None)
        if status == TASK_IN_PROGRESS:
            return PORTAL_MESSAGE % {'statusid': 'info',
                                     'status': PMF(u"Info"),
                                     'msg': _(u"Processing document generation, please refresh the page...")}
        elif status == TASK_FAILED:
            return PORTAL_MESSAGE % {'statusid': 'warning',
                                     'status': PMF(u"Error"),
                                     'msg': _(u"Document generation failed, please retry or contact your administrator")}
        elif not status:
            return u""

        url = u"%s/getdocumentfusion" % context.absolute_url()
        title = translate(_(u"Get the generated file."), context=self.request)

        mtregistry = getToolByName(self.context, 'mimetypes_registry')
        file_name = named_file.filename
        mimetype = mtregistry.lookupExtension(file_name)
        icon_path = "%s/%s" % (self.portal_url, mimetype.icon_path)
        return u"""
        <div id="generated-pdf">
          <a href="%s" title="%s">
            <img src="%s" /> %s
          </a>
        </div>""" % (url, title, icon_path, file_name)
    def cropped_image(self, field, id_name):
        """Retuns html tag for the cropped image.

        :param field: Field name.
        :type field: str

        :param id_name: ID name.
        :type id_name: str
        """
        context = aq_inner(self.context)
        anno = IAnnotations(context)
        name = 'collective.cropimage.{0}'.format(field)
        data = anno[name][id_name] if anno.get(name) is not None and anno.get(name).get(id_name) is not None else None
        if data is not None:
            width = 'width:{0}px;'.format(data['w'])
            height = 'height:{0}px;'.format(data['h'])
            html = '<div class="crop" style="{0}{1}">'.format(width, height)
            clip = 'clip:rect({0}px {1}px {2}px {3}px);'.format(data['y1'], data['x2'], data['y2'], data['x1'])
            top = 'top:-{0}px;'.format(data['y1'])
            left = 'left:-{0}px;'.format(data['x1'])
            html += '<p style="{0}{1}{2}">'.format(clip, top, left)
            src = '{0}/{1}'.format(context.absolute_url(), field)
            title = context.Title()
            html += '<img src="{0}" alt="{1}" title="{1}" />'.format(src, title)
            html += '</p>'
            html += '</div>'
            return html
class Allocation(object):
    ''' adapter for IAllocation '''

    implements(IAllocation)
    adapts(ISession)

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

    @property
    def location(self):
        return self.annotation.get('allocation.location', '')

    @location.setter
    def location(self, value):
        self.annotation['allocation.location'] = value

    @property
    def start_date(self):
        return self.annotation.get('allocation.start_date', '')

    @start_date.setter
    def start_date(self, value):
        self.annotation['allocation.start_date'] = value

    @property
    def end_date(self):
        return self.annotation.get('allocation.end_date', '')

    @end_date.setter
    def end_date(self, value):
        self.annotation['allocation.end_date'] = value
    def check_if_mappings_are_persistent(self):
        check_result = 'PASSED'
        catalog = self.site.portal_catalog

        dossier_brains = catalog(object_provides=IDossierMarker.__identifier__)
        repo_brains = catalog(object_provides=IRepositoryFolder.__identifier__)

        all_brains = []
        all_brains.extend(dossier_brains)
        all_brains.extend(repo_brains)

        for brain in all_brains:
            obj = brain.getObject()
            url = obj.absolute_url()
            ann = IAnnotations(obj)

            if OLD_CODE_BASE:
                child_refs = ann.get(CHILD_REF_KEY)
                prefix_refs = ann.get(PREFIX_REF_KEY)
            else:
                child_refs = self.helper.get_new_mapping(CHILD_REF_KEY, obj)
                prefix_refs = self.helper.get_new_mapping(PREFIX_REF_KEY, obj)

            if child_refs:
                child_refs_persistent = is_persistent(child_refs)
                if not child_refs_persistent:
                    check_result = 'FAILED'
                    self.log("FAILED: child refs not persistent for %s" % url)

            if prefix_refs:
                prefix_refs_persistent = is_persistent(prefix_refs)
                if not prefix_refs_persistent:
                    check_result = 'FAILED'
                    self.log("FAILED: prefix refs not persistent for %s" % url)
        return check_result
Beispiel #5
0
    def selectedPacket(self):
        annotations = IAnnotations(self.context)
        packet_key = annotations.get(PACKETS_KEY + '.type')
        packet_fields = annotations.get(PACKETS_KEY + '.fields')
        packet_mapui = annotations.get(PACKETS_KEY + '.mapui')

        return dict(packet_key=packet_key, value=packet_fields.get(packet_mapui.get('codi')), element=packet_fields.get(packet_mapui.get('element')))
Beispiel #6
0
    def show(self):
        """ Removes all status messages (including HTML) and returns them 
            for display.
        """
        context = self.context
        annotations = IAnnotations(context)
        msgs = annotations.get(STATUSMESSAGEKEY,
                                context.cookies.get(STATUSMESSAGEKEY))
        msgs = msgs and adapter._decodeCookieValue(msgs) or []

        html_msgs = annotations.get(HTMLMESSAGEKEY,
                                context.cookies.get(HTMLMESSAGEKEY))
        html_msgs = html_msgs and adapter._decodeCookieValue(html_msgs) or []

        for msg in html_msgs:
            msg.message = literal(sanitize(msg.message, cleaner=msgcleaner, wrap=None))

        value = msgs + html_msgs
        
        # clear the existing cookie entries, except on responses that don't
        # actually render in the browser (really, these shouldn't render
        # anything so we shouldn't get to this message, but some templates
        # are sloppy).
        if self.context.response.getStatus() not in (301, 302, 304):
            context.cookies[STATUSMESSAGEKEY] = None
            context.response.expireCookie(STATUSMESSAGEKEY, path='/')
            annotations[STATUSMESSAGEKEY] = None

            context.cookies[HTMLMESSAGEKEY] = None
            context.response.expireCookie(HTMLMESSAGEKEY, path='/')
            annotations[HTMLMESSAGEKEY] = None
        
        return value
    def handle_layout(self):
        """
        This will check if the file does not have the
        document viewer display selected.

        In addition, if the currently selected display
        is for wc.pageturner, we'll clean out the annotations
        from that product. Additionally, we'll also look
        for wildcard.pdfpal related values.
        """
        current = self.context.getLayout()
        if current != 'documentviewer':
            self.context.layout = 'documentviewer'
        annotations = IAnnotations(self.context)
        # remove page turner related
        data = annotations.get('wc.pageturner', None)
        if data:
            del annotations['wc.pageturner']

        # remove pdfpal related
        field = self.context.getField('ocrText')
        if field:
            field.set(self.context, '')

        data = annotations.get('wildcard.pdfpal', None)
        if data:
            del annotations['wildcard.pdfpal']
class WorkflowState(object):
    state_key = "hurry.workflow.state"
    id_key = "hurry.workflow.id"

    def __init__(self, context):
        # XXX okay, I'm tired of it not being able to set annotations, so
        # we'll do this. Ugh.
        from zope.security.proxy import removeSecurityProxy
        self.context = removeSecurityProxy(context)
        self._annotations = IAnnotations(self.context)

    def initialize(self):
        wf_versions = component.queryUtility(IWorkflowVersions)
        if wf_versions is not None:
            self.setId(wf_versions.createVersionId())

    def setState(self, state):
        if state != self.getState():
            self._annotations[self.state_key] = state

    def setId(self, id):
        # XXX catalog should be informed (or should it?)
        self._annotations[self.id_key] = id

    def getState(self):
        return self._annotations.get(self.state_key, None)

    def getId(self):
        return self._annotations.get(self.id_key, None)
    def fix_dossier(self, dossier):
        intid = self.intid_utility.getId(dossier)
        parent = aq_parent(aq_inner(dossier))

        former_reference_number = IDossier(dossier).former_reference_number
        if not former_reference_number:
            print 'SKIPPED Dosier ({}{}) created at '.format(
                '/'.join(dossier.getPhysicalPath()), dossier.created())
            return
        former_prefix = former_reference_number.split('-')[-1].split('.')[-1]

        ref_mapping = IAnnotations(parent).get('dossier_reference_mapping')
        old_prefix = former_prefix
        new_prefix = ref_mapping.get('reference_prefix').get(intid)

        # check if former_reference_number is registered for current dossier
        if ref_mapping.get('reference_numbers').get(former_prefix) != intid:
            print 'Check failed'
            import pdb; pdb.set_trace()
        else:
            # free new prefix (remove it from the numbers list)
            ref_mapping['reference_numbers'].pop(new_prefix)

        # set old prefix as current
        ref_mapping['reference_prefix'][intid] = old_prefix.decode('utf-8')

        print '{} --> {} ({})'.format(new_prefix, old_prefix,
                                      '/'.join(dossier.getPhysicalPath()))

        self.reindex_dossier_and_children(dossier)
Beispiel #10
0
def addAnnotation(object, recipients):
    """ Add annotation after change state and send mail
    """
    KEY = 'genweb.rectorat.logMail'

    annotations = IAnnotations(object)

    if annotations is not None:

        logData = annotations.get(KEY, None)

        try:
            len(logData)
            # Get data and append values
            data = annotations.get(KEY)
        except:
            # If it's empty, initialize data
            data = []

        dateMail = datetime.now()
        username = api.user.get_current().id

        values = dict(dateMail=dateMail,
                      fromMail="Sessió convocada per: " + str(username),
                      toMail=', '.join(map(str, recipients)))

        data.append(values)
        annotations[KEY] = data
    def test_annotations_key_is_cleared(self):
        annotations = IAnnotations(self.document)
        self.assertEquals(TEST_USER_ID, annotations.get(CHECKIN_CHECKOUT_ANNOTATIONS_KEY))

        self.manager.checkin()

        self.assertEquals(None, annotations.get(CHECKIN_CHECKOUT_ANNOTATIONS_KEY))
Beispiel #12
0
class License(object):
    """
        This class adds two Dublin Core Fields to content for storing the copyright
        license, and the holder of the copyright
    """
    implements(ILicense)

    def __init__(self, context):
        self.context = context
        self.annotations = IAnnotations(context)
        rightsLicense = self.annotations.get(RIGHTSLICENSE_KEY, None)
        if rightsLicense is None:
            self.annotations[RIGHTSLICENSE_KEY] = ['Site Default', 'None', 'None', 'None']
        rightsHolder = self.annotations.get(RIGHTSHOLDER_KEY, None)
        if rightsHolder is None:
            self.annotations[RIGHTSHOLDER_KEY] = '(site default)'

    def getRightsLicense(self):
        """ Get the contents of the DC.rights.license field. """
        return self.annotations[RIGHTSLICENSE_KEY]

    def setRightsLicense(self, ldata):
        """ Set the DC.rights.license field. """
        self.annotations[RIGHTSLICENSE_KEY] = ldata

    def getRightsHolder(self):
        """ Get the contents of the DC.rightsHolder field. """
        return self.annotations[RIGHTSHOLDER_KEY]

    def setRightsHolder(self, rhdata):
        """ Set the DC.rightsHolder field. """
        self.annotations[RIGHTSHOLDER_KEY] = rhdata

    license = property(fget=getRightsLicense, fset=setRightsLicense)
    def downvote(self, path):
        """ """
        user_rating = None
        s = getSite()
        rpath = '/'.join(s.getPhysicalPath()) + path.replace(s.absolute_url(), '')
        reply = self.context.restrictedTraverse(rpath)
        if not IAttributeAnnotatable.providedBy(reply):
            alsoProvides(reply, IAttributeAnnotatable)
        annotations = IAnnotations(reply)
        voters = annotations.get('opkode.rateablediscussion.voters', {})
        rating = annotations.get('opkode.rateablediscussion.rating', 0)
        pm = getToolByName(s, 'portal_membership')
        if pm.isAnonymousUser():
            return 
        pm = getToolByName(s, 'portal_membership')
        member = pm.getAuthenticatedMember()
        member_id = member.getId()
        if member_id not in voters:
            voters[member_id] = 'down'
            user_rating = 'down'
            annotations['opkode.rateablediscussion.voters'] = voters
            rating -= 1
            annotations['opkode.rateablediscussion.rating'] = rating
        elif voters.get(member_id) == 'up':
            # The voter is removing his vote, so let's delete him
            del voters[member_id]
            annotations['opkode.rateablediscussion.voters'] = voters
            rating -= 1
            annotations['opkode.rateablediscussion.rating'] = rating
        elif voters.get(member_id) == 'down':
            # The down arrow has already been clicked before
            user_rating = 'down'

        return json.dumps(
                    {'reply_rating': rating, 'user_rating':user_rating})
class Journalist(object):
    """Stores the extra fields in the anotation
    """
    implements(IJournalist)
    adapts(IPerson)

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

    @property
    def email(self):
        return self.annotation.get('s17.person.journalist_email', u"")

    @email.setter
    def email(self, value):
        self.annotation['s17.person.journalist_email'] = value

    @property
    def resume(self):
        return self.annotation.get('s17.person.resume', u"")

    @resume.setter
    def resume(self, value):
        self.annotation['s17.person.resume'] = value

    @property
    def signature(self):
        return self.annotation.get('s17.person.signature', u"")

    @signature.setter
    def signature(self, value):
        self.annotation['s17.person.signature'] = value
    def _update_AgentInfoPortlet_ProfilePage(self, folders, data):
        """Override Annotation for plone.mls.listing AgentInfo inside AgentProfilePages"""
        #get agents portrait/ avatar url
        avatar_url = self.membershiptool.getPersonalPortrait(id=self.userid).absolute_url()
        #get AgencyInfo
        agency = self.__AgencyInfo

        for folder in folders:

            if IAgentFolder.providedBy(folder) and ILocalAgencyInfo.providedBy(folder):
                #get annotations for this folder
                mls_ano = IAnnotations(folder).get("plone.mls.listing.localagencyinfo", None)

                if mls_ano is None:
                    #initialize Annotations
                    anno = IAnnotations(folder)
                    anno.get("plone.mls.listing.localagencyinfo", anno.setdefault("plone.mls.listing.localagencyinfo", {}))
                    mls_ano = IAnnotations(folder).get("plone.mls.listing.localagencyinfo", {})

                # set global Agency Info
                mls_ano['agency_name'] = agency.get('agency_name', u'Krain Real Estate')
                mls_ano['agency_logo_url'] = agency.get('agency_logo_url', u'')
                mls_ano['agency_office_phone'] = agency.get('agency_office_phone', u'')
                mls_ano['agency_website'] = agency.get('agency_website', u'')
                
                #Agent Info
                mls_ano['agent_name'] = data.get('fullname', u'')
                mls_ano['agent_office_phone'] = data.get('office_phone', u'')
                mls_ano['agent_cell_phone'] = data.get('cell_phone', u'')
                mls_ano['agent_email'] = data.get('email', u'')
                mls_ano['agent_avatar_url'] = avatar_url

                #force overrding of Any other agent
                mls_ano['force'] = 'selected'
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
Beispiel #17
0
    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 ContactInfo(object):
    ''' adapter for IContactInfo '''

    implements(IContactInfo)
    adapts(IPerson)

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

    @property
    def emails(self):
        return self.annotation.get('s17.person.emails', [])

    @emails.setter
    def emails(self, value):
        self.annotation['s17.person.emails'] = value

    @property
    def instant_messengers(self):
        return self.annotation.get('s17.person.instant_messengers', [])

    @instant_messengers.setter
    def instant_messengers(self, value):
        self.annotation['s17.person.instant_messengers'] = value

    @property
    def telephones(self):
        return self.annotation.get('s17.person.telephones', [])

    @telephones.setter
    def telephones(self, value):
        self.annotation['s17.person.telephones'] = value
def uninstall(context, reinstall=False):
    if not reinstall:
        portal = getSite()
        portal_actions = getToolByName(portal, 'portal_actions')
        object_buttons = portal_actions.object

        # remove actions
        actions_to_remove = ('documentviewer_settings',
                             'documentviewer_convert')
        for action in actions_to_remove:
            if action in object_buttons.objectIds():
                object_buttons.manage_delObjects([action])

        catalog = getToolByName(portal, 'portal_catalog')
        objs = catalog(object_provides=IFileContent.__identifier__)
        settings = GlobalSettings(portal)

        # remove annotations and reset view
        for obj in objs:
            obj = obj.getObject()
            if obj.getLayout() == 'documentviewer':
                obj.layout = ''
            annotations = IAnnotations(obj)
            data = annotations.get('collective.documentviewer', None)
            if data:
                del annotations['collective.documentviewer']
            # delete files associated with it...
            storage_dir = storage.getResourceDirectory(gsettings=settings,
                obj=obj)
            if os.path.exists(storage_dir):
                shutil.rmtree(storage_dir)

        # remove view
        types = getToolByName(portal, 'portal_types')
        filetype = types['File']
        methods = list(filetype.view_methods)
        if 'documentviewer' in methods:
            methods.remove('documentviewer')
            filetype.view_methods = tuple(methods)

        # remove pdf album view
        for portal_type in GROUP_VIEW_DISPLAY_TYPES:
            if portal_type in types.objectIds():
                _type = types[portal_type]
                methods = list(_type.view_methods)
                if 'dvpdf-group-view' in methods:
                    methods.remove('dvpdf-group-view')
                    _type.view_methods = tuple(set(methods))

        # remove control panel
        pcp = getToolByName(context, 'portal_controlpanel')
        pcp.unregisterConfiglet('documentviewer')
        pcp.unregisterConfiglet('documentviewer-jobs')

        # remove global settings annotations
        annotations = IAnnotations(portal)
        data = annotations.get('collective.documentviewer', None)
        if data:
            del annotations['collective.documentviewer']
def uninstall(context, reinstall=False):
    if not reinstall:
        portal = getSite()
        portal_actions = getToolByName(portal, 'portal_actions')
        object_buttons = portal_actions.object

        # remove actions
        actions_to_remove = ('documentviewer_settings',
                             'documentviewer_convert')
        for action in actions_to_remove:
            if action in object_buttons.objectIds():
                object_buttons.manage_delObjects([action])

        catalog = getToolByName(portal, 'portal_catalog')
        objs = catalog(object_provides=IFileContent.__identifier__)
        settings = GlobalSettings(portal)

        # remove annotations and reset view
        for obj in objs:
            obj = obj.getObject()
            if obj.getLayout() == 'documentviewer':
                obj.layout = ''
            annotations = IAnnotations(obj)
            data = annotations.get('collective.documentviewer', None)
            if data:
                del annotations['collective.documentviewer']
            # delete files associated with it...
            storage_dir = storage.getResourceDirectory(gsettings=settings,
                                                       obj=obj)
            if os.path.exists(storage_dir):
                shutil.rmtree(storage_dir)

        # remove view
        types = getToolByName(portal, 'portal_types')
        filetype = types['File']
        methods = list(filetype.view_methods)
        if 'documentviewer' in methods:
            methods.remove('documentviewer')
            filetype.view_methods = tuple(methods)

        # remove pdf album view
        for portal_type in GROUP_VIEW_DISPLAY_TYPES:
            if portal_type in types.objectIds():
                _type = types[portal_type]
                methods = list(_type.view_methods)
                if 'dvpdf-group-view' in methods:
                    methods.remove('dvpdf-group-view')
                    _type.view_methods = tuple(set(methods))

        # remove control panel
        pcp = getToolByName(context, 'portal_controlpanel')
        pcp.unregisterConfiglet('documentviewer')
        pcp.unregisterConfiglet('documentviewer-jobs')

        # remove global settings annotations
        annotations = IAnnotations(portal)
        data = annotations.get('collective.documentviewer', None)
        if data:
            del annotations['collective.documentviewer']
Beispiel #21
0
    def copy_meta(self):
        # XXX disable working copy support
        return json.dumps({
            'newId': self.request.get('metaId'),
            'success': True,
            'locked': False
        })
        _id = self.request.get('metaId')
        copy_id = self.get_working_copy_meta_id()
        annotations = IAnnotations(self.context)
        data = annotations.get(TILE_ANNOTATIONS_KEY_PREFIX + '.' + _id)
        if not data:
            data = PersistentDict()

        if ('locked' in data and self.request.get(
                'override', '').lower() not in ('y', 'yes', '1', 'true', 't')
                and api.user.get_current().getId() != data['locked']['user']):
            return json.dumps({
                'locked': True,
                'success': False,
                'lock_data': data['locked']
            })

        if TILE_ANNOTATIONS_KEY_PREFIX + '.' + copy_id in annotations:
            # cut out, we're good, resume existing
            return json.dumps({
                'newId': copy_id,
                'success': True,
                'locked': False
            })

        version_key = self.get_working_copy_key()
        tile_mapping = {}
        new_tiles = []
        for tile in data.get('tiles', []):
            # make copies of all the tiles
            tile_id = tile['id']
            copy_tile_id = '{}-{}'.format(tile_id, version_key)
            tile_data = annotations.get(TILE_ANNOTATIONS_KEY_PREFIX + '.' +
                                        tile_id)
            if tile_data:
                annotations[TILE_ANNOTATIONS_KEY_PREFIX + '.' +
                            copy_tile_id] = deepcopy(tile_data)
            new_tile_info = deepcopy(tile)
            new_tile_info['id'] = copy_tile_id
            new_tiles.append(new_tile_info)
            tile_mapping[tile_id] = copy_tile_id

        new_data = PersistentDict(dict(data))
        new_data.update({'tiles': new_tiles, 'mapping': tile_mapping})
        data.update({
            'locked': {
                'when': DateTime().ISO8601(),
                'user': api.user.get_current().getId()
            }
        })
        annotations[TILE_ANNOTATIONS_KEY_PREFIX + '.' + copy_id] = new_data

        return json.dumps({'newId': copy_id, 'success': True, 'locked': False})
Beispiel #22
0
 def _get_field_type(self):
     portal = getSite()
     anno = IAnnotations(portal)
     name = 'sllintra.content.field_type'
     if anno.get(name) is None:
         anno[name] = PersistentDict()
     field_type = anno.get(name)
     return field_type.get(self.field.getName(), 'select')
Beispiel #23
0
    def selectedPacket(self):
        annotations = IAnnotations(self.context)
        packet_key = annotations.get(PACKETS_KEY + '.type')
        packet_fields = annotations.get(PACKETS_KEY + '.fields')
        packet_mapui = annotations.get(PACKETS_KEY + '.mapui')

        return dict(packet_key=packet_key,
                    value=packet_fields.get(packet_mapui.get('codi')),
                    element=packet_fields.get(packet_mapui.get('element')))
Beispiel #24
0
 def _get_change_data(self):
     """If request defines change_data, use it, else return a dummy dict.
     """
     cd = IAnnotations(common.get_request()).get("change_data")
     if cd is None:
         cd = {}
     cd.setdefault("note", cd.get("note", ""))
     cd.setdefault("date_active", cd.get("date_active", None))
     return cd
def uninstall_storages(portal):
    annotations = IAnnotations(portal)
    if annotations.get(STORAGE_KEY):
        LOGGER.info("*** UNINSTALL collective.logbook Logstorage ***")
        del annotations[STORAGE_KEY]

    if annotations.get(INDEX_KEY):
        LOGGER.info("*** UNINSTALL collective.logbook Indexstorage ***")
        del annotations[INDEX_KEY]
Beispiel #26
0
 def _get_change_data(self):
     """If request defines change_data, use it, else return a dummy dict.
     """
     cd = IAnnotations(common.get_request()).get("change_data")
     if cd is None:
         cd = {}
     cd.setdefault("note", cd.get("note", ""))
     cd.setdefault("date_active", cd.get("date_active", None))
     return cd
    def delete_all_errors(self):
        """ see ILogBookStorage
        """
        annotations = IAnnotations(self.portal)
        if annotations.get(STORAGE_KEY):
            del annotations[STORAGE_KEY]

        if annotations.get(INDEX_KEY):
            del annotations[INDEX_KEY]
    def test_annotations_key_is_cleared(self):
        annotations = IAnnotations(self.document)
        self.assertEquals(
            TEST_USER_ID, annotations.get(CHECKIN_CHECKOUT_ANNOTATIONS_KEY))

        self.manager.checkin()

        self.assertEquals(
            None, annotations.get(CHECKIN_CHECKOUT_ANNOTATIONS_KEY))
class MonitorConfigurationAdapter(SchemaAdapterBase, object):
    """Stores the monitor configuration
    """

    adapts(IPloneSiteRoot)
    implements(IMonitorConfigurationSchema)

    def __init__(self, context):
        super(MonitorConfigurationAdapter, self).__init__(self)
        self.annotations = IAnnotations(context)
        self.storage = self.annotations.get(ANNOTATIONS_KEY, None)
        if not isinstance(self.storage, PersistentDict):
            self.annotations[ANNOTATIONS_KEY] = PersistentDict()
            self.storage = self.annotations.get(ANNOTATIONS_KEY)

    def is_enabled(self):
        return self.storage.get('enabled', False) and True or False

    def set_enabled(self, value):
        self.storage['enabled'] = value and True or False

    enabled = property(is_enabled, set_enabled)

    def get_receivers_plain(self):
        return self.storage.get('receivers', '')

    def get_receivers(self):
        """Get receivers as list
        """
        data = self.storage.get('receivers', '')
        if data:
            return data.split('\n')
        else:
            return []

    def set_receivers_plain(self, value):
        self.storage['receivers'] = value

    receivers = property(get_receivers_plain, set_receivers_plain)

    def get_threshold(self):
        return self.storage.get('threshold', 100)

    def set_threshold(self, value):
        self.storage['threshold'] = int(value)

    threshold = property(get_threshold, set_threshold)

    def get_max_extraction_duration_seconds(self):
        return self.storage.get('max_extraction_duration_seconds', 3 * 60)

    def set_max_extraction_duration_seconds(self, value):
        self.storage['max_extraction_duration_seconds'] = int(value)

    max_extraction_duration_seconds = property(get_max_extraction_duration_seconds,
                                               set_max_extraction_duration_seconds)
Beispiel #30
0
 def get_image(self, name=None):
     imagedict = IAnnotations(
         self.context).get(self._annotation)
     if not imagedict:
         return
     image = imagedict.get(name or 'original')
     if not image and name in self._sizes:
         image = self._resize(imagedict.get('original'), name)
         imagedict[name] = image
     return image
Beispiel #31
0
 def getLanguage(self, langs, env):
     annotations = IAnnotations(env, None)
     if annotations:
         lang = annotations.get(DEFAULT_LANGUAGE_KEY)
         if lang is None:
             annotations[DEFAULT_LANGUAGE_KEY] = get_default_language()
         lang = annotations.get(DEFAULT_LANGUAGE_KEY)
     else:
         lang = get_default_language()
     return lang
 def get_cached_pdf(self):
     """Return cached pdf if the key is still valid, otherwise None."""
     annotation = IAnnotations(self.context)
     new_key = self.cache_key
     old_key = annotation.get(CACHEKEY)
     if new_key == old_key:
         logger.info("PDF cache hit for %s.", self.context.absolute_url())
         return annotation.get(PDFCACHE)
     logger.info("PDF cache miss for %s.", self.context.absolute_url())
     return None
class NotifierConfigurationAdapter(SchemaAdapterBase, object):
    """Stores the notifier configuration
    """

    adapts(IPloneSiteRoot)
    implements(INotifierConfigurationSchema)

    def __init__(self, context):
        super(NotifierConfigurationAdapter, self).__init__(self)
        self.annotations = IAnnotations(context)
        self.storage = self.annotations.get(ANNOTATIONS_KEY, None)
        if not isinstance(self.storage, PersistentDict):
            self.annotations[ANNOTATIONS_KEY] = PersistentDict()
            self.storage = self.annotations.get(ANNOTATIONS_KEY)

    def is_enabled(self):
        return self.storage.get('enabled', False) and True or False

    def set_enabled(self, value):
        self.storage['enabled'] = value and True or False

    enabled = property(is_enabled, set_enabled)

    def get_detailed_report(self):
        return self.storage.get('detailed_report', False) and True or False

    def set_detailed_report(self, value):
        self.storage['detailed_report'] = value and True or False

    detailed_report = property(get_detailed_report, set_detailed_report)

    def get_interval(self):
        return self.storage.get('interval', 'daily')

    def set_interval(self, value):
        self.storage['interval'] = value

    interval = property(get_interval, set_interval)

    def get_receivers_plain(self):
        return self.storage.get('receivers', '')

    def get_receivers(self):
        """Get receivers as list
        """
        data = self.storage.get('receivers', '')
        if data:
            return data.split('\n')
        else:
            return []

    def set_receivers_plain(self, value):
        self.storage['receivers'] = value

    receivers = property(get_receivers_plain, set_receivers_plain)
Beispiel #34
0
 def get_dv_images(self, obj):
     images = []
     annot = IAnnotations(obj).get('collective.documentviewer', '')
     if not annot or not annot['successfully_converted'] or not annot.get('blob_files', None):
         return []
     files = annot.get('blob_files', {})
     for page in range(1, annot['num_pages']+1):
         img = 'large/dump_%d.%s' % (page, annot['pdf_image_format'])
         blob = files[img]
         images.append(blob.open())
     return images
Beispiel #35
0
    def selectedPacket(self):
        if self.isAlreadyConfigured():
            annotations = IAnnotations(self.context)
            packet_key = annotations.get(PACKETS_KEY + '.type')
            packet_fields = annotations.get(PACKETS_KEY + '.fields')
            packet_mapui = annotations.get(PACKETS_KEY + '.mapui')
            selected = dict(packet_key=packet_key, value=packet_fields.get(packet_mapui.get('codi')), element=packet_fields.get(packet_mapui.get('element')))
        else:
            selected = {'packet_key': '', 'value': '', 'element': ''}

        return selected
Beispiel #36
0
 def migrate(self, old, new):
     source_annotations = IAnnotations(old)
     settings = source_annotations.get(ANNOTATION_KEY, None)
     if settings is not None:
         target_annotations = IAnnotations(new)
         if target_annotations.get(ANNOTATION_KEY, None) is not None:
             logger.error('DocumentViewer settings exist on %s' %
                          new.absolute_url())
             return
         target_annotations[ANNOTATION_KEY] = settings
         logger.info('DocumentViewer settings migrated for %s' %
                     new.absolute_url())
 def migrate(self, old, new):
     source_annotations = IAnnotations(old)
     settings = source_annotations.get(ANNOTATION_KEY, None)
     if settings is not None:
         target_annotations = IAnnotations(new)
         if target_annotations.get(ANNOTATION_KEY, None) is not None:
             logger.error('DocumentViewer settings exist on %s' %
                          new.absolute_url())
             return
         target_annotations[ANNOTATION_KEY] = settings
         logger.info('DocumentViewer settings migrated for %s' %
                     new.absolute_url())
Beispiel #38
0
    def __init__(self,context):
        self.context = removeSecurityProxy(context)
        annotations = IAnnotations(self.context)
        facetag_data = annotations.get(FACETAG_KEY)
        facetag_inherit = annotations.get(FACETAG_INHERIT_KEY)
        if facetag_data is None:
            facetag_data = annotations[FACETAG_KEY] = PersistentList()
        if facetag_inherit is None:
            facetag_inherit = annotations[FACETAG_INHERIT_KEY] = True

        self.facetag_data = facetag_data
        self.facetag_inherit = facetag_inherit
Beispiel #39
0
    def __init__(self, context):
        self.context = removeSecurityProxy(context)
        annotations = IAnnotations(self.context)
        facetag_data = annotations.get(FACETAG_KEY)
        facetag_inherit = annotations.get(FACETAG_INHERIT_KEY)
        if facetag_data is None:
            facetag_data = annotations[FACETAG_KEY] = PersistentList()
        if facetag_inherit is None:
            facetag_inherit = annotations[FACETAG_INHERIT_KEY] = True

        self.facetag_data = facetag_data
        self.facetag_inherit = facetag_inherit
 def onSuccess(self, fields, request):
     context = get_context(self)
     annotations = IAnnotations(context)
     singleSubmission = annotations.get(CEFPSS, False)
     voters = annotations.get(CEFPSV, [])
     if not api.user.is_anonymous():
         auth_user = api.user.get_current()
         if singleSubmission and auth_user.id in voters:
             return False
         voters.append(auth_user.id)
         annotations[CEFPSV] = voters
     super(PollSaveData, self).onSuccess(fields, request)
Beispiel #41
0
 def _get_change_data(self):
     """If request defines change_data, use it, else return a dummy dict.
     """
     try:
         cd = IAnnotations(common.get_request()).get("change_data")
         assert cd is not None, "change_data dict is None."
     except (TypeError, AssertionError):
         # Could not adapt... under testing, the "request" is a 
         # participation that has no IAnnotations.
         cd = {}
     cd.setdefault("note", cd.get("note", ""))
     cd.setdefault("date_active", cd.get("date_active", None))
     return cd
    def test_annotations(self):
        obj = self.portal.get('my-dx')
        annotations = IAnnotations(obj)
        self.assertEqual(annotations.get('foo'), {
            'bar': [1, 2, 'three'],
            'baz': True
        })

        self.assertFalse(isinstance({}, PersistentMapping))
        self.assertTrue(isinstance(annotations.get('foo'), PersistentMapping))

        self.assertFalse(isinstance({}, PersistentList))
        self.assertTrue(
            isinstance(annotations.get('foo').get('bar'), PersistentList))
    def test_store_services(self):
        """ Test saving embedly services to site annotation """
        portal = self.layer['portal']
        storage = IAnnotations(portal)
        self.assertEqual(storage.get('collective.embedly.services'), None)
        # update_services()
        view = portal.unrestrictedTraverse("@@update_embedly_services")
        view.__of__(portal)()

        res = urllib2.urlopen('http://api.embed.ly/1/services/python')
        list_exp = []
        for service in json.loads(res.read()):
            list_exp.append('|'.join(service.get('regex', [])))
        self.assertEqual(storage.get('collective.embedly.services'), '|'.join(list_exp))
Beispiel #44
0
    def selectedPacket(self):
        if self.isAlreadyConfigured():
            annotations = IAnnotations(self.context)
            packet_key = annotations.get(PACKETS_KEY + '.type')
            packet_fields = annotations.get(PACKETS_KEY + '.fields')
            packet_mapui = annotations.get(PACKETS_KEY + '.mapui')
            selected = dict(packet_key=packet_key,
                            value=packet_fields.get(packet_mapui.get('codi')),
                            element=packet_fields.get(
                                packet_mapui.get('element')))
        else:
            selected = {'packet_key': '', 'value': '', 'element': ''}

        return selected
Beispiel #45
0
        def memogetter(url, api_key):
            annotations = IAnnotations(getSite())
            cache = annotations.get(self.propname, _marker)
            if cache is _marker:
                annotations[self.propname] = dict()
                cache = annotations.get(self.propname)

            key = get_oembed_cache_key(func.__name__, url, api_key)
            val = cache.get(key, _marker)
            if val is _marker:
                val = func(url, api_key)
                if val:
                    cache[key] = val
                    annotations[self.propname] = cache
            return val
Beispiel #46
0
    def allowSingleSubmission(self):
        try:
            if not api.user.is_anonymous():
                if self.context.Type() == 'EasyForm':
                    annotations = IAnnotations(self.context)
                    singleSubmission = annotations.get(CEFPSS, False)

                    voters = annotations.get(CEFPSV, [])
                    auth_user = api.user.get_current()
                    if singleSubmission and auth_user.id in voters:
                        return True

        except:
            return False
        return False
Beispiel #47
0
    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)
Beispiel #48
0
    def download_translation(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        registry = getUtility(IRegistry)
        base_url = registry.get("tgate.tgate_server_url")
        username = registry.get("tgate.tgate_server_username")
        password = registry.get("tgate.tgate_server_password")

        client = TGateClient(base_url, username, password)
        annotated = IAnnotations(self.context)
        document_id = annotated.get(KEY, None)
        if document_id:
            response = client.download_document(document_id)
            if response.get("status") == "success":
                text = response.get("data", {}).get("contents", "")
                self._make_field_from_html_document(
                    text, data.get("field_to_translate")
                )
                messages = IStatusMessage(self.request)
                messages.add(_(u"Translation downloaded correctly"), "info")
                return self.request.response.redirect(self.context.absolute_url())

        messages = IStatusMessage(self.request)
        messages.add(_(u"Error when downloading the translation"), "error")
        return self.request.response.redirect(self.context.absolute_url())
    def test_annotations(self):
        foo = self.portal.get('foo')
        intranet = foo.get('intranet')

        annotations = IAnnotations(intranet)
        self.assertEqual(annotations.get('foo'), {
            'bar': [1, 2, 'three'],
            'baz': True
        })

        self.assertFalse(isinstance({}, PersistentMapping))
        self.assertTrue(isinstance(annotations.get('foo'), PersistentMapping))

        self.assertFalse(isinstance({}, PersistentList))
        self.assertTrue(
            isinstance(annotations.get('foo').get('bar'), PersistentList))
Beispiel #50
0
    def __init__(self, context, request):
        """self:zope.app.pagetemplate.simpleviewclass.SimpleViewClass -> 
                    templates/workspace-index.pt
           context:bungeni.core.content.Section
        """
        LD = IAnnotations(request)["layer_data"]
        assert interfaces.IWorkspaceSectionLayer.providedBy(request)
        assert LD.get("workspaces") is not None
        super(WorkspaceSectionView, self).__init__(context, request)
        cls_name = self.__class__.__name__
        # NOTE: Zope morphs this class's name to "SimpleViewClass from ..."
        log.debug("%s.__init__ %s context=%s url=%s" %
                  (cls_name, self, self.context, request.getURL()))

        # transfer layer data items, for the view/template
        self.user_id = LD.user_id
        self.user_group_ids = LD.user_group_ids
        self.government_id = LD.government_id  # may be None
        self.ministries = LD.ministries  # may be None
        if self.ministries:
            # then, ONLY if an ancestor container is actually a Ministry,
            # this must be a MinisterWorkspace
            if misc.get_parent_with_interface(self,
                                              model_interfaces.IMinistry):
                interface.alsoProvides(self, interfaces.IMinisterWorkspace)

        # roles are function of the context, so always recalculate
        roles = common.get_context_roles(self.context)
        for role_id in roles:
            iface = self.role_interface_mapping.get(role_id)
            if iface is not None:
                interface.alsoProvides(self, iface)
        log.debug("%s.__init__ %s" % (cls_name, debug.interfaces(self)))
def localPortletAssignmentMappingAdapter(context, manager):
    """This is pretty much the same code of the original one from

    `plone.app.portlets.assignable.localPortletAssignmentMappingAdapter`

    but it changes the assignment klass with `Mapping`.

    This is needed in order to use our custom view '+'
    for adding the portlet.
    """
    annotations = IAnnotations(context)
    local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
    if local is None:
        local = annotations[CONTEXT_ASSIGNMENT_KEY] = OOBTree()

    portlets = local.get(manager.__name__, None)
    if portlets is None:
        portlets = local[manager.__name__] = Mapping(manager=manager.__name__,
                                                     category=CONTEXT_CATEGORY)

    # XXX: For graceful migration
    if not getattr(portlets, '__manager__', ''):
        portlets.__manager__ = manager.__name__

    if not getattr(portlets, '__category__', ''):
        portlets.__category__ = CONTEXT_CATEGORY

    return portlets
Beispiel #52
0
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(self.context)
     self.__mapping = annotations.get(self.ANNO_KEY, None)
     if self.__mapping is None:
         self.__mapping = PersistentList()
         annotations[self.ANNO_KEY] = self.__mapping
Beispiel #53
0
def upgrade_executed_jobs_storage(portal_setup):
    """The executed jobs storage has changed from PersistentList
    to IOBTree storage, so we need to migrate the storage.

    """
    portal = portal_setup.portal_url.getPortalObject()
    queue = IQueue(portal)
    annotations = IAnnotations(portal)

    if 'publisher-executed' not in annotations:
        # No data to migrate.
        return

    # get jobs directly from the annotations - accessing with
    # queue methods is not possible yet
    jobs = list(annotations.get('publisher-executed', []))

    # drop the current list
    del annotations['publisher-executed']

    # add every single job with the new methods
    for job in jobs:
        queue.append_executed_job(job)

    # check if it worked
    assert len(jobs) == queue.get_executed_jobs_length()
def remove_thumbnail(context):
    annotations = IAnnotations(context)
    has_collective_videolink_data = annotations.get(
        'collective.videolink.data', {})
    if 'thumbnail' in has_collective_videolink_data:
        del annotations['collective.videolink.data']['thumbnail']
    return context
Beispiel #55
0
def purge(event):
    """
    Asynchronously send PURGE requests.
    this is mostly copied from plone.cachingpurging
    """
    request = event.request

    annotations = IAnnotations(request, None)
    if annotations is None:
        return

    paths = annotations.get(KEY, None)
    if paths is None:
        return

    registry = queryUtility(IRegistry)
    if registry is None:
        return

    settings = registry.forInterface(ICachePurgingSettings, check=False)
    if not settings.enabled:
        return

    if paths:
        urls = []
        cf = cloudflare.get()
        if cf.enabled:
            for path in paths:
                urls.extend(cf.getUrlsToPurge(path))

            CastlePurger.purgeAsync(urls, cf)
Beispiel #56
0
 def get_number(self, obj):
     ann = IAnnotations(obj)
     if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann.keys():
         generator = getAdapter(obj, ISequenceNumberGenerator)
         value = generator.generate()
         ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = value
     return ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY)
class SyncStampUtility(object):
    """Global utility that handles persistent storage of the LDAP sync stamp.
    """

    SYNC_STAMP_KEY = 'sync_stamp'

    def get_context(self, context):
        """Helper to get the context, even if no context is given.
        """
        if not context or not IPloneSiteRoot.providedBy(context):
            context = api.portal.get()

        return context

    def get_sync_stamp(self, context=None):
        """Return the sync stamp (time stamp of last LDAP synchronisation).
        """
        context = self.get_context(context)
        self.annotations = IAnnotations(context)
        return self.annotations.get('sync_stamp')

    def set_sync_stamp(self, stamp, context=None):
        """Update sync stamp with the given value.
        """
        context = self.get_context(context)
        self.annotations = unprotected_write(IAnnotations(context))
        self.annotations['sync_stamp'] = stamp
        logger.info("Stored sync_stamp %s in annotations" % stamp)
Beispiel #58
0
def purge(event):
    """Asynchronously send PURGE requests
    """

    request = event.request

    annotations = IAnnotations(request, None)
    if annotations is None:
        return

    paths = annotations.get(KEY, None)
    if paths is None:
        return

    registry = queryUtility(IRegistry)
    if registry is None:
        return

    if not isCachePurgingEnabled(registry=registry):
        return

    purger = queryUtility(IPurger)
    if purger is None:
        return

    settings = registry.forInterface(ICachePurgingSettings, check=False)
    for path in paths:
        for url in getURLsToPurge(path, settings.cachingProxies):
            purger.purgeAsync(url)
    def get_journal_data(self):
        if IAnnotationsJournalizable.providedBy(self.context):
            annotations = IAnnotations(self.context)
            data = annotations.get(JOURNAL_ENTRIES_ANNOTATIONS_KEY, [])
            return deepcopy(data)

        return []