def messageStructure(obj, aq_context=None, sub_mgr=None, full_message=False):
    """A mapping defining the data we want from brain objects for views"""
    if base_hasattr(obj, 'getURL'):
        url = obj.getURL()
        id = obj.getId
    else:
        url = obj.absolute_url()
        id = obj.getId()
    if aq_context is None:
        aq_context = obj

    from_id, from_addr = getAddressInfo(obj, sub_mgr)
    subject = escape(obj.subject) or '(No Subject)'
    struct = {'subject': obfct_de(subject),
              'brief_subject': obfct(subject[:40]) + \
                                     (len(subject) > 40 and ' ...' or ''),
              'mail_from': from_id and from_id or obfct(from_addr),
              'from_id': from_id,
              'date': format_date(obj.date, aq_context),
              'message_id': obj.message_id,
              'in_reply_to': obj.in_reply_to,
              'id': id,
              'url': url}
    if full_message:
        msg_obj = obj
        if not base_hasattr(msg_obj, 'body'):
            msg_obj = obj.getObject()
        struct['body'] = obfct_de(escape(msg_obj.body))
        struct['attachments'] = getAttachmentsForMessage(msg_obj)
    return struct
    def __call__(self):

        context = self.context
        data = {}
        data['document_id'] = context.id
        data['url'] = context.absolute_url()
        data['path'] = '/'.join(context.getPhysicalPath())
        data['uid'] = context.UID()
        if base_hasattr(context, 'title') and context.title:
            data['Title'] = context.title

        if base_hasattr(context, 'creators'):
            creator = context.creators[0]
            user = api.user.get(creator)
            if user:
                data['Author'] = user.getProperty('fullname', '') or creator
            else:
                data['Author'] = creator

        if base_hasattr(context, 'description') and context.description:
            description = context.description.replace('\n', ' ').strip()
            if description:
                data['Subject'] = data['Description'] = description

        if base_hasattr(context, 'subject') and context.subject:
            keywords = tuple([k.strip() for k in context.subject if k.strip()])
            data['Keywords'] = keywords

        fti = getUtility(IDexterityFTI, name=context.portal_type)
        schema = fti.lookupSchema()
        for name in getFieldNames(schema):
            #@TODO: ignore files
            data[name] = getattr(context, name, None)

        return data
Esempio n. 3
0
def is_active(brain_or_object):
    """Check if the workflow state of the object is 'inactive' or 'cancelled'.

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: False if the object is in the state 'inactive' or 'cancelled'
    :rtype: bool
    """
    if is_brain(brain_or_object):
        if base_hasattr(brain_or_object, 'inactive_state') and \
           brain_or_object.inactive_state == 'inactive':
            return False
        if base_hasattr(brain_or_object, 'cancellation_state') and \
           brain_or_object.cancellation_state == 'cancelled':
            return False
    obj = get_object(brain_or_object)
    wf = get_tool('portal_workflow')
    workflows = get_workflows_for(obj)
    if 'bika_inactive_workflow' in workflows \
            and wf.getInfoFor(obj, 'inactive_state') == 'inactive':
        return False
    if 'bika_cancellation_workflow' in workflows \
            and wf.getInfoFor(obj, 'cancellation_state') == 'cancelled':
        return False
    return True
Esempio n. 4
0
    def isExpired(content):
        """ Find out if the object is expired (copied from skin script) """

        expiry = None

        # NOTE: We also accept catalog brains as 'content' so that the
        # catalog-based folder_contents will work. It's a little
        # magic, but it works.

        # ExpirationDate should have an ISO date string, which we need to
        # convert to a DateTime

        # Try DC accessor first
        if base_hasattr(content, 'ExpirationDate'):
            expiry = content.ExpirationDate

        # Try the direct way
        if not expiry and base_hasattr(content, 'expires'):
            expiry = content.expires

        # See if we have a callable
        if safe_callable(expiry):
            expiry = expiry()

        # Convert to DateTime if necessary, ExpirationDate may return 'None'
        if expiry and expiry != 'None' and isinstance(expiry, basestring):
            expiry = DateTime(expiry)

        if isinstance(expiry, DateTime) and expiry.isPast():
            return 1
        return 0
Esempio n. 5
0
def is_active(brain_or_object):
    """Check if the workflow state of the object is 'inactive' or 'cancelled'.

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: False if the object is in the state 'inactive' or 'cancelled'
    :rtype: bool
    """
    if is_brain(brain_or_object):
        if base_hasattr(brain_or_object, 'inactive_state') and \
           brain_or_object.inactive_state == 'inactive':
            return False
        if base_hasattr(brain_or_object, 'cancellation_state') and \
           brain_or_object.cancellation_state == 'cancelled':
            return False
    obj = get_object(brain_or_object)
    wf = get_tool('portal_workflow')
    workflows = get_workflows_for(obj)
    if 'bika_inactive_workflow' in workflows \
            and wf.getInfoFor(obj, 'inactive_state') == 'inactive':
        return False
    if 'bika_cancellation_workflow' in workflows \
            and wf.getInfoFor(obj, 'cancellation_state') == 'cancelled':
        return False
    return True
Esempio n. 6
0
def _relativePath(context, row):
    # Walk through the tree
    obj = context
    values = row.values
    depthstr = ""
    if '::' in values:
        values, _depth = values.split('::', 1)
        depthstr = "::%s" % _depth
    for x in [r for r in values.split('/') if r]:
        if x == "..":
            if IPloneSiteRoot.providedBy(obj):
                break
            parent = aq_parent(obj)
            if parent:
                obj = parent
        else:
            if base_hasattr(obj, x):
                child = getattr(obj, x, None)
                if child and base_hasattr(child, "getPhysicalPath"):
                    obj = child

    row = Row(index=row.index,
              operator=row.operator,
              values='/'.join(obj.getPhysicalPath()) + depthstr)

    return _absolutePath(context, row)
def messageStructure(obj, aq_context=None, sub_mgr=None, full_message=False):
    """A mapping defining the data we want from brain objects for views"""
    if base_hasattr(obj, 'getURL'):
        url = obj.getURL()
        id = obj.getId
    else:
        url = obj.absolute_url()
        id= obj.getId()
    if aq_context is None:
        aq_context = obj

    from_id, from_addr = getAddressInfo(obj, sub_mgr)
    subject = escape(obj.subject) or '(No Subject)'
    struct = {'subject': obfct_de(subject),
              'brief_subject': obfct(subject[:40]) + \
                                     (len(subject) > 40 and ' ...' or ''),
              'mail_from': from_id and from_id or obfct(from_addr),
              'from_id': from_id,
              'date': format_date(obj.date, aq_context),
              'message_id': obj.message_id,
              'in_reply_to': obj.in_reply_to,
              'id': id,
              'url': url}
    if full_message:
        msg_obj = obj
        if not base_hasattr(msg_obj, 'body'):
            msg_obj = obj.getObject()
        struct['body'] = obfct_de(escape(msg_obj.body))
        struct['attachments'] = getAttachmentsForMessage(msg_obj)
    return struct
Esempio n. 8
0
    def _migrateStorage(self):
        # we're going to use an LOBTree for storage. we need to
        # consider the possibility that self is from an
        # older version that uses the native Archetypes storage
        # or the former IOBTree (<= 1.6.0b2 )
        # in the SavedFormInput field.
        updated = base_hasattr(self, '_inputStorage') and \
                  base_hasattr(self, '_inputItems') and \
                  base_hasattr(self, '_length')

        if not updated:
            try:
                saved_input = self.getSavedFormInput()
            except AttributeError:
                saved_input = []

            self._inputStorage = SavedDataBTree()
            i = 0
            self._inputItems = 0
            self._length = Length()

            if len(saved_input):
                for row in saved_input:
                    self._inputStorage[i] = row
                    i += 1
                self.SavedFormInput = []
                self._inputItems = i
                self._length.set(i)
Esempio n. 9
0
def _relativePath(context, row):
    # Walk through the tree
    obj = context
    values = row.values
    depthstr = ""
    if '::' in values:
        values, _depth = values.split('::', 1)
        depthstr = "::%s" % _depth
    for x in [r for r in values.split('/') if r]:
        if x == "..":
            if IPloneSiteRoot.providedBy(obj):
                break
            parent = aq_parent(obj)
            if parent:
                obj = parent
        else:
            if base_hasattr(obj, x):
                child = getattr(obj, x, None)
                if child and base_hasattr(child, "getPhysicalPath"):
                    obj = child

    row = Row(index=row.index,
              operator=row.operator,
              values='/'.join(obj.getPhysicalPath()) + depthstr)

    return _absolutePath(context, row)
Esempio n. 10
0
    def create_tasks_folder(self):
        if base_hasattr(self.portal['incoming-mail'], 'task-searches'):
            api.content.delete(obj=self.portal['incoming-mail']['task-searches'])
        if not base_hasattr(self.portal, 'tasks'):
            self.portal.invokeFactory("Folder", id='tasks', title=_(u"Tasks"))
            tsk_folder = getattr(self.portal, 'tasks')
            self.portal.moveObjectToPosition('tasks', self.portal.getObjectPosition('contacts'))
            # add task-searches
            col_folder = add_db_col_folder(tsk_folder, 'task-searches', _("Tasks searches"),
                                           _("Tasks"))
            alsoProvides(col_folder, INextPrevNotNavigable)
            alsoProvides(col_folder, ITaskDashboard)
            createTaskCollections(col_folder)
            createStateCollections(col_folder, 'task')
            configure_faceted_folder(col_folder, xml='im-task-searches.xml',
                                     default_UID=col_folder['all_tasks'].UID())
            # configure tasks faceted
            configure_faceted_folder(tsk_folder, xml='default_dashboard_widgets.xml',
                                     default_UID=col_folder['all_tasks'].UID())

            tsk_folder.setConstrainTypesMode(1)
            tsk_folder.setLocallyAllowedTypes(['task'])
            tsk_folder.setImmediatelyAddableTypes(['task'])
            self.portal.portal_workflow.doActionFor(tsk_folder, "show_internally")
            logger.info('tasks folder created')
Esempio n. 11
0
def migrateInternalV3(context):
    """For version 3 of the Subscriber content type, adds an index for the bounce number
    and some default attributes
    """
    site = context.getSite()
    ctool = getToolByName(site, 'portal_catalog')
    newsletterthemes = [s.getObject() for s in ctool(portal_type='NewsletterTheme')]
    for nl in newsletterthemes:
        catalog = nl[PG_CATALOG]
        if 'is_bouncing' not in catalog.indexes():
            catalog.addIndex('is_bouncing', 'FieldIndex')

        if not base_hasattr(nl, 'removeNoticeTemplate'):
            nl.removeNoticeTemplate = DEFAULT_REMOVE_NOTICE_TEMPLATE

        if not base_hasattr(nl, 'verp_prefix'):
            nl.verp_prefix = u""

        if not base_hasattr(nl, 'extra_filters'):
            nl.extra_filters = u""

        if not base_hasattr(nl, 'automatic_cleanup'):
            nl.automatic_cleanup = False

        if not base_hasattr(nl, 'removeNoticeMailSubject'):
            nl.automatic_cleanup = u"You have been automatically removed from this newsletter"

    logger.info('Migration of of content types to internal v3 done.')
Esempio n. 12
0
    def transformCustomer(self, mid, sid):
        """
        """
        # Not logged in
        if mid is None:
            return False

        # There is already a personalized customer    
        if base_hasattr(self.customers, mid) == True:
            return False

        # There is no session customer            
        if base_hasattr(self.sessions, sid) == False:
            return False

        session_customer = self.sessions[sid]
        ICopyManagement(session_customer).copyTo(self.customers, mid)
        
        # Set customer info
        customer = self.customers[mid]
        self._setCustomerInfo(customer)
        
        self.sessions.manage_delObjects([sid])

        return True
Esempio n. 13
0
 def renderCell(self, item):
     img = suffix = msg = info = u''
     real_template = item
     if base_hasattr(item, 'pod_template_to_use'
                     ) and item.pod_template_to_use is not None:
         real_template = item.get_pod_template_to_use()
         suffix = u'_use'
         if item.pod_template_to_use in self.templates_voc:
             info = translate(u', from ${template}',
                              context=self.request,
                              domain='collective.documentgenerator',
                              mapping={
                                  'template':
                                  self.templates_voc.getTerm(
                                      item.pod_template_to_use).title
                              })
     elif base_hasattr(item, 'is_reusable') and item.is_reusable:
         suffix, info = u'_used', translate(
             u', is reusable template',
             context=self.request,
             domain='collective.documentgenerator')
     if real_template is None:
         img, msg = u'missing', u'Linked template deleted !'
     elif real_template.has_been_modified():
         img, msg = u'nok', u'Modified'
     else:
         img, msg = u'ok', u'Original'
     icon = ('++resource++collective.documentgenerator/{}{}.svg'.format(
         img, suffix), u'{}{}'.format(
             translate(msg,
                       context=self.request,
                       domain='collective.documentgenerator'), info))
     return u"<img class='svg-icon' title='{0}' src='{1}' />".format(
         safe_unicode(icon[1]).replace("'", "&#39;"),
         u"{0}/{1}".format(self.table.portal_url, icon[0]))
Esempio n. 14
0
 def _rename_own_organization(self):
     logger.info('Rename own-organization')
     if base_hasattr(self.portal.contacts, 'own-organization'):
         self.portal.contacts.manage_renameObject(
             'own-organization', 'plonegroup-organization')
     if not base_hasattr(self.portal.contacts, 'plonegroup-organization'):
         logger.error('ERROR!! own-organization not renamed')
Esempio n. 15
0
def migrateInternalV3(context):
    """For version 3 of the Subscriber content type, adds an index for the bounce number
    and some default attributes
    """
    if isNotPloneGazetteProfile(context):
        return

    site = context.getSite()
    ctool = getToolByName(site, 'portal_catalog')
    newsletterthemes = [
        s.getObject() for s in ctool(portal_type='NewsletterTheme')
    ]
    for nl in newsletterthemes:
        catalog = nl[PG_CATALOG]
        if 'is_bouncing' not in catalog.indexes():
            catalog.addIndex('is_bouncing', 'FieldIndex')

        if not base_hasattr(nl, 'removeNoticeTemplate'):
            nl.removeNoticeTemplate = DEFAULT_REMOVE_NOTICE_TEMPLATE

        if not base_hasattr(nl, 'verp_prefix'):
            nl.verp_prefix = u""

        if not base_hasattr(nl, 'extra_filters'):
            nl.extra_filters = u""

        if not base_hasattr(nl, 'automatic_cleanup'):
            nl.automatic_cleanup = False

        if not base_hasattr(nl, 'removeNoticeMailSubject'):
            nl.automatic_cleanup = u"You have been automatically removed from this newsletter"

    logger.info('Migration of of content types to internal v3 done.')
    def _migrateStorage(self):
        # we're going to use an LOBTree for storage. we need to
        # consider the possibility that self is from an
        # older version that uses the native Archetypes storage
        # or the former IOBTree (<= 1.6.0b2 )
        # in the SavedFormInput field.
        updated = base_hasattr(self, '_inputStorage') and \
                  base_hasattr(self, '_inputItems') and \
                  base_hasattr(self, '_length')

        if not updated:
            try:
                saved_input = self.getSavedFormInput()
            except AttributeError:
                saved_input = []

            self._inputStorage = SavedDataBTree()
            i = 0
            self._inputItems = 0
            self._length = Length()

            if len(saved_input):
                for row in saved_input:
                    self._inputStorage[i] = row
                    i += 1
                self.SavedFormInput = []
                self._inputItems = i
                self._length.set(i)
Esempio n. 17
0
 def compare(a, b):
     """ Sort
     """
     a_progress = (a[1].progress
                   if base_hasattr(a[1], 'progress') else 0)
     b_progress = (b[1].progress
                   if base_hasattr(b[1], 'progress') else 0)
     return cmp(a_progress, b_progress)
Esempio n. 18
0
        def compare(a, b):
            """ Sort
            """
            a_progress = ((a[1].progress if base_hasattr(a[1], 'progress') else
                           0) if hasProgress else self.guessProgress(a[0]))
            b_progress = ((b[1].progress if base_hasattr(b[1], 'progress') else
                           0) if hasProgress else self.guessProgress(b[0]))

            return cmp(a_progress, b_progress)
Esempio n. 19
0
    def __getitem__(self, id):
        # Zope's inner acquisition chain for objects returned by __getitem__
        # will be:
        #
        # portal -> portal_factory -> temporary_folder -> object
        #
        # What we really want is for the inner acquisition chain to be:
        #
        # intended_parent_folder -> portal_factory -> temporary_folder ->
        # object
        #
        # So we need to rewrap...
        portal_factory = aq_parent(aq_inner(self))
        intended_parent = aq_parent(portal_factory)

        # If the intended parent has an object with the given id, just do a
        # passthrough
        if hasattr(intended_parent, id):
            return getattr(intended_parent, id)

        # rewrap portal_factory
        portal_factory = aq_base(portal_factory).__of__(intended_parent)
        # rewrap self
        temp_folder = aq_base(self).__of__(portal_factory)

        if id in self:
            return (aq_base(self._getOb(id)).__of__(temp_folder)) \
                .__of__(intended_parent)
        else:
            type_name = self.getId()
            try:
                # We fake an archetype tool which returns no catalogs for the
                # object to be indexed in to avoid it showing up in the catalog
                # in the first place.
                self.archetype_tool = FauxArchetypeTool(
                    getToolByName(self, 'archetype_tool'))
                _createObjectByType(type_name, self, id)
            except ConflictError:
                raise
            except:
                # some errors from invokeFactory (AttributeError, maybe others)
                # get swallowed -- dump the exception to the log to make sure
                # developers can see what's going on
                log_exc(severity=logging.DEBUG)
                raise
            obj = self._getOb(id)

            # keep obj out of the catalog
            obj.unindexObject()

            # additionally keep it out of Archetypes UID and refs catalogs
            if base_hasattr(obj, '_uncatalogUID'):
                obj._uncatalogUID(obj)
            if base_hasattr(obj, '_uncatalogRefs'):
                obj._uncatalogRefs(obj)

            return (aq_base(obj).__of__(temp_folder)).__of__(intended_parent)
Esempio n. 20
0
    def _setupStorage(self):
        set_up =  base_hasattr(self, '_inputStorage') and \
                  base_hasattr(self, '_inputItems') and \
                  base_hasattr(self, '_length')

        if not set_up:
            self._inputStorage = SavedDataBTree()
            self._inputItems = 0
            self._length = Length()
    def _initStorage(self, clear=False):
        inited = base_hasattr(self, '_inputStorage') and \
                 base_hasattr(self, '_inputItems') and \
                 base_hasattr(self, '_length')

        if not inited or clear:
            self._inputStorage = LOBTree()
            self._inputItems = 0
            self._length = Length()
Esempio n. 22
0
    def __call__(self):
        """
        """
        context = self.context
        response = context.REQUEST.response
        homeFolder=context.portal_membership.getHomeFolder()
        view_url = context.absolute_url()
        if not homeFolder:
            context.plone_utils.addPortalMessage(
                _(u'Can\'t access home folder. Favorite is not added.'),
                'error')
            return response.redirect(view_url)

        if not base_hasattr(homeFolder, 'Favorites'):
            homeFolder.invokeFactory(
                'Folder',
                id='Favorites',
                title='Favorites')
            addable_types = ['Link']
            favs = homeFolder.Favorites
            if base_hasattr(favs, 'setConstrainTypesMode'):
                favs.setConstrainTypesMode(1)
                favs.setImmediatelyAddableTypes(addable_types)
                favs.setLocallyAllowedTypes(addable_types)
                favs.manage_addProperty(
                    'layout',
                    'favorites_view',
                    type='string')

        targetFolder = homeFolder.Favorites
        new_id='fav_' + str(int(context.ZopeTime()))
        myPath=context.portal_url.getRelativeUrl(context)
        fav_id = targetFolder.invokeFactory(
            'Link',
            id=new_id,
            title=context.TitleOrId(),
            remote_url=myPath)
        if fav_id:
            favorite = getattr(targetFolder, fav_id, None)
        else:
            favorite = getattr(targetFolder, new_id, None)

        if favorite:
            favorite.reindexObject()

            msg = _(
                u'${title} has been added to your Favorites.',
                mapping={
                    u'title': context.title_or_id().decode('utf-8') or None})
            context.plone_utils.addPortalMessage(msg)
        else:
            msg = _(
                u'There was a problem adding ${title} to your Favorites.',
                mapping={u'title': context.title_or_id().decode('utf-8')})

        return response.redirect(view_url)
Esempio n. 23
0
 def migrate_tasks(self):
     for brain in self.catalog(portal_type='task'):
         obj = brain.getObject()
         # replace userid by organization
         if not obj.enquirer or obj.enquirer not in self.registry[ORGANIZATIONS_REGISTRY]:
             if base_hasattr(obj.aq_parent, 'treating_groups') and obj.aq_parent.treating_groups:
                 obj.enquirer = obj.aq_parent.treating_groups
             elif base_hasattr(obj.aq_parent, 'assigned_group') and obj.aq_parent.assigned_group:
                 obj.enquirer = obj.aq_parent.assigned_group
             modified(obj)
Esempio n. 24
0
    def itemsSaved(self):
        """Download the saved data
        """

        if base_hasattr(self, '_length'):
            return self._length()
        elif base_hasattr(self, '_inputItems'):
            return self._inputItems
        else:
            return len(self.SavedFormInput)
    def itemsSaved(self):
        # """Download the saved data
        # """

        if base_hasattr(self, '_length'):
            return self._length()
        elif base_hasattr(self, '_inputItems'):
            return self._inputItems
        else:
            return len(self.SavedFormInput)
Esempio n. 26
0
        def compare(a, b):
            """ Sort
            """
            a_progress = ((a[1].progress
                           if base_hasattr(a[1], 'progress') else  0) if
                          hasProgress else self.guessProgress(a[0]))
            b_progress = ((b[1].progress
                           if base_hasattr(b[1], 'progress') else 0) if
                          hasProgress else self.guessProgress(b[0]))

            return cmp(a_progress, b_progress)
Esempio n. 27
0
 def updateWidgets(self):
     super(CustomAddForm, self).updateWidgets()
     TaskUpdateWidgets(self)
     # Set parent assigned group as default value
     if base_hasattr(self.context, 'treating_groups') and self.context.treating_groups:
         self.widgets['ITask.assigned_group'].value = self.context.treating_groups
     elif base_hasattr(self.context, 'assigned_group') and self.context.assigned_group:
         self.widgets['ITask.assigned_group'].value = self.context.assigned_group
     # Set current user as enquirer and hide it
     userid = api.user.get_current().getId()
     if userid != 'admin':
         self.widgets['ITask.enquirer'].value = userid
Esempio n. 28
0
 def updateTranslatedPaths(obj, path=None):
     if (base_hasattr(obj, 'indexObject') and
         safe_callable(obj.indexObject) and
         base_hasattr(obj, 'getPhysicalPath') and
         safe_callable(obj.getPhysicalPath)):
         try:
             path = '/'.join(obj.getPhysicalPath())
             catalog._catalog.updateTanslatedPaths(obj, path)
             results.append('Updated %s' % path)
             transaction.commit()
         except:
             pass
Esempio n. 29
0
def v2(context):
    for (name, fti) in getUtilitiesFor(IDexterityFTI):
        if not base_hasattr(fti, 'localroleconfig'):
            continue
        logger.info("FTI '%s' => Copying static_config: '%s'" % (name, fti.localroleconfig))
        if not base_hasattr(fti, 'localroles'):
            setattr(fti, 'localroles', PersistentMapping())
        fti.localroles['static_config'] = {}
        for state_key, state_dic in fti.localroleconfig.items():
            fti.localroles['static_config'][state_key] = {}
            for principal, roles in state_dic.items():
                fti.localroles['static_config'][state_key][principal] = {'roles': roles}
        delattr(fti, 'localroleconfig')
Esempio n. 30
0
    def addMail(self, mailString, force_id=False):
        """ Store mail in date based folder archive.
            Returns created mail.  See IMailingList interface.
        """
        archive = aq_get(self, self.getValueFor('storage'), None)

        # no archive available? then return immediately
        if archive is None:
            return None

        (header, body) = splitMail(mailString)

        # if 'keepdate' is set, get date from mail,
        if self.getValueFor('keepdate'):
            assert header.get("date") is not None
            time = DateTime(header.get("date"))
        # ... take our own date, clients are always lying!
        else:
            time = DateTime()

        # now let's create the date-path (yyyy/mm)
        year  = str(time.year()) # yyyy
        month = str(time.mm())   # mm
        title = "%s %s"%(time.Month(), year)

        # do we have a year folder already?
        if not base_hasattr(archive, year):
            self.addMailBoxerFolder(archive, year, year, btree=False)
        yearFolder=getattr(archive, year)

        # do we have a month folder already?
        if not base_hasattr(yearFolder, month):
            self.addMailBoxerFolder(yearFolder, month, title)
        mailFolder=getattr(yearFolder, month)

        subject = header.get('subject', _('No Subject'))
        sender = header.get('from',_('Unknown'))

        # search a free id for the mailobject
        id = time.millis()
        while base_hasattr(mailFolder, str(id)):
            if force_id:
                raise AssertionError("ID %s already exists on folder %s" % (id, mailFolder))
            id = id + 1
        id = str(id)

        self.addMailBoxerMail(mailFolder, id, sender, subject, time,
                              mailString)
        mailObject = getattr(mailFolder, id)

        return mailObject
    def addMail(self, mailString, force_id=False):
        """ Store mail in date based folder archive.
            Returns created mail.  See IMailingList interface.
        """
        archive = aq_get(self, self.getValueFor('storage'), None)

        # no archive available? then return immediately
        if archive is None:
            return None

        (header, body) = splitMail(mailString)

        # if 'keepdate' is set, get date from mail,
        if self.getValueFor('keepdate'):
            assert header.get("date") is not None
            time = DateTime(header.get("date"))
        # ... take our own date, clients are always lying!
        else:
            time = DateTime()

        # now let's create the date-path (yyyy/mm)
        year  = str(time.year()) # yyyy
        month = str(time.mm())   # mm
        title = "%s %s"%(time.Month(), year)

        # do we have a year folder already?
        if not base_hasattr(archive, year):
            self.addMailBoxerFolder(archive, year, year, btree=False)
        yearFolder=getattr(archive, year)

        # do we have a month folder already?
        if not base_hasattr(yearFolder, month):
            self.addMailBoxerFolder(yearFolder, month, title)
        mailFolder=getattr(yearFolder, month)

        subject = header.get('subject', 'No Subject')
        sender = header.get('from','Unknown')

        # search a free id for the mailobject
        id = time.millis()
        while base_hasattr(mailFolder, str(id)):
            if force_id:
                raise AssertionError("ID %s already exists on folder %s" % (id, mailFolder))
            id = id + 1
        id = str(id)

        self.addMailBoxerMail(mailFolder, id, sender, subject, time,
                              mailString)
        mailObject = getattr(mailFolder, id)

        return mailObject
Esempio n. 32
0
def get_id(brain_or_object):
    """Get the Plone ID for this object

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: Plone ID
    :rtype: string
    """
    if is_brain(brain_or_object):
        if base_hasattr(brain_or_object, "getId"):
            return brain_or_object.getId
        if base_hasattr(brain_or_object, "id"):
            return brain_or_object.id
    return get_object(brain_or_object).getId()
def v2(context):
    for (name, fti) in getUtilitiesFor(IDexterityFTI):
        for (fname, field) in get_localrole_fields(fti):
            if not base_hasattr(fti, fname):
                continue
            logger.info("FTI '%s' => Copying old field config '%s': '%s'" % (name, fname, getattr(fti, fname)))
            if not base_hasattr(fti, 'localroles'):
                setattr(fti, 'localroles', PersistentMapping())
            fti.localroles[fname] = {}
            for state_key, state_dic in getattr(fti, fname).items():
                fti.localroles[fname][state_key] = {}
                for principal, roles in state_dic.items():
                    fti.localroles[fname][state_key][principal] = {'roles': roles}
            delattr(fti, fname)
Esempio n. 34
0
 def updateWidgets(self, prefix=None):
     super(CustomAddForm, self).updateWidgets(prefix=prefix)
     TaskUpdateWidgets(self)
     # Set parent assigned group as default value
     if base_hasattr(self.context,
                     'treating_groups') and self.context.treating_groups:
         self.widgets[
             'ITask.assigned_group'].value = self.context.treating_groups
         self.widgets['ITask.enquirer'].value = self.context.treating_groups
     elif base_hasattr(self.context,
                       'assigned_group') and self.context.assigned_group:
         self.widgets[
             'ITask.assigned_group'].value = self.context.assigned_group
         self.widgets['ITask.enquirer'].value = self.context.assigned_group
Esempio n. 35
0
    def changeOwnershipOf(self, object, userid, recursive=0, REQUEST=None):
        """Changes the ownership of an object."""
        membership = getToolByName(self, 'portal_membership')
        acl_users = getattr(self, 'acl_users')
        user = acl_users.getUserById(userid)
        if user is None:
            # The user could be in the top level acl_users folder in
            # the Zope root, in which case this should find him:
            user = membership.getMemberById(userid)
            if user is None:
                raise KeyError(
                    'Only retrievable users in this site can be made owners.')
            # Be careful not to pass MemberData to changeOwnership
            user = user.getUser()
        object.changeOwnership(user, recursive)

        def fixOwnerRole(object, user_id):
            # Get rid of all other owners
            owners = object.users_with_local_role('Owner')
            for o in owners:
                roles = list(object.get_local_roles_for_userid(o))
                roles.remove('Owner')
                if roles:
                    object.manage_setLocalRoles(o, roles)
                else:
                    object.manage_delLocalRoles([o])
            # Fix for 1750
            roles = list(object.get_local_roles_for_userid(user_id))
            roles.append('Owner')
            object.manage_setLocalRoles(user_id, roles)

        fixOwnerRole(object, user.getId())
        if base_hasattr(object, 'reindexObject'):
            object.reindexObject()

        if recursive:
            catalog_tool = getToolByName(self, 'portal_catalog')
            purl = getToolByName(self, 'portal_url')
            _path = purl.getRelativeContentURL(object)
            subobjects = [
                b.getObject() for b in catalog_tool(path={
                    'query': _path,
                    'level': 1
                })
            ]
            for obj in subobjects:
                fixOwnerRole(obj, user.getId())
                if base_hasattr(obj, 'reindexObject'):
                    obj.reindexObject()
    def __call__(self):

        context = self.context
        data = {}
        data['document_id'] = context.id
        data['url'] = context.absolute_url()
        data['path'] = '/'.join(context.getPhysicalPath())
        data['uid'] = context.UID()
        if base_hasattr(context, 'title') and context.title:
            data['Title'] = context.title

        if base_hasattr(context, 'creators'):
            creator = context.creators[0]
            user = api.user.get(creator)
            if user:
                data['Author'] = user.getProperty('fullname', '') or creator
            else:
                data['Author'] = creator

        if base_hasattr(context, 'description') and context.description:
            description = context.description.replace('\n', ' ').strip()
            if description:
                data['Subject'] = data['Description'] = description

        if base_hasattr(context, 'subject') and context.subject:
            keywords = tuple([k.strip() for k in context.subject if k.strip()])
            data['Keywords'] = keywords

        fti = getUtility(IDexterityFTI, name=context.portal_type)
        fields = get_fields(fti)

        for name in fields:
            try:
                renderer = getMultiAdapter(
                    (fields[name], self.context, self.request),
                    interface=IExportable,
                    name=name)
            except ComponentLookupError:
                renderer = getMultiAdapter(
                    (fields[name], self.context, self.request),
                    interface=IExportable)

            render = renderer.render(self.context)
            if type(render) is datetime.date:
                render = render.strftime("%Y-%m-%d")
            data[name] = render

        return data
def v13(context):
    catalog = api.portal.get_tool('portal_catalog')
    brains = catalog.unrestrictedSearchResults(object_provides=IContactContent.__identifier__)
    for brain in brains:
        obj = brain.getObject()
        if base_hasattr(obj, 'is_created'):
            delattr(obj, 'is_created')
Esempio n. 38
0
    def related_items(self):
        context = aq_inner(self.context)
        res = ()

        # Archetypes
        if base_hasattr(context, 'getRawRelatedItems'):
            catalog = getToolByName(context, 'portal_catalog')
            related = context.getRawRelatedItems()
            if not related:
                return ()
            brains = catalog(UID=related)
            if brains:
                # build a position dict by iterating over the items once
                positions = dict([(v, i) for (i, v) in enumerate(related)])
                # We need to keep the ordering intact
                res = list(brains)

                def _key(brain):
                    return positions.get(brain.UID, -1)

                res.sort(key=_key)

        # Dexterity
        if HAS_RELATIONFIELD and IRelatedItems.providedBy(context):
            related = context.relatedItems
            if not related:
                return ()
            res = self.related2brains(related)

        return res
Esempio n. 39
0
    def decoratorFactory(self, node):
        ct = getToolByName(self.context, 'portal_catalog')
        oldnode = super(CategoryWidgetStrategy, self).decoratorFactory(node)
        oldnode['uid'] = node['item'].UID

        # Determine the number of blog entries for each category.
        # Also take translations of categories into account.
        # TODO: This will perform badly with a large number of categories
        # We could optimize this by always storing a reference to the
        # canonical category instead of the corresponding translation.
        obj = node['item'].getObject()
        count = 0
        if base_hasattr(obj, 'getTranslations'):
            for translation in obj.getTranslations(
                    review_state=False).values():
                count += len(
                    ct(
                        getCategoryUids=translation.UID(),
                        portal_type='BlogEntry',
                        Language='all',
                    ))
        else:
            count = len(
                ct(
                    getCategoryUids=obj.UID(),
                    portal_type='BlogEntry',
                    Language='all',
                ))

        oldnode['count_refs'] = count
        return oldnode
Esempio n. 40
0
def getObjSize(obj):
    """ Helper method for catalog based folder contents.

    >>> from Products.CMFPlone.CatalogTool import getObjSize

    >>> getObjSize(self.folder)
    '1 kB'
    """
    smaller = SIZE_ORDER[-1]

    if base_hasattr(obj, 'get_size'):
        size = obj.get_size()
    else:
        size = 0

    # if the size is a float, then make it an int
    # happens for large files
    try:
        size = int(size)
    except (ValueError, TypeError):
        pass

    if not size:
        return '0 %s' % smaller

    if isinstance(size, (int, long)):
        if size < SIZE_CONST[smaller]:
            return '1 %s' % smaller
        for c in SIZE_ORDER:
            if size/SIZE_CONST[c] > 0:
                break
        return '%.1f %s' % (float(size/float(SIZE_CONST[c])), c)
    return size
Esempio n. 41
0
def _createDashboardCollections(folder, collections):
    """
        create some dashboard collections in searches folder
    """
    wfTool = api.portal.get_tool('portal_workflow')
    for i, dic in enumerate(collections):
        if not dic.get('id'):
            continue
        if not base_hasattr(folder, dic['id']):
            folder.invokeFactory("DashboardCollection",
                                 dic['id'],
                                 title=dic['tit'],
                                 query=dic['query'],
                                 tal_condition=dic['cond'],
                                 roles_bypassing_talcondition=dic['bypass'],
                                 customViewFields=dic['flds'],
                                 showNumberOfItems=dic['count'],
                                 sort_on=dic['sort'],
                                 sort_reversed=dic['rev'],
                                 b_size=30,
                                 limit=0)
            collection = folder[dic['id']]
            if "show_internally" in wfTool.getTransitionsFor(collection):
                wfTool.doActionFor(collection, "show_internally")
            if 'subj' in dic:
                collection.setSubject(dic['subj'])
                collection.reindexObject(['Subject'])
            collection.setLayout('tabular_view')
        if folder.getObjectPosition(dic['id']) != i:
            folder.moveObjectToPosition(dic['id'], i)
Esempio n. 42
0
def add(container, obj, rename=True):
    """Add an object to a container."""
    id_ = getattr(aq_base(obj), "id", None)

    # Archetypes objects are already created in a container thus we just fire
    # the notification events and rename the object if necessary.
    if base_hasattr(obj, "_at_rename_after_creation"):
        notify(ObjectAddedEvent(obj, container, id_))
        notifyContainerModified(container)
        if obj._at_rename_after_creation and rename:
            obj._renameAfterCreation(check_auto_id=True)
        return obj
    else:
        if rename:
            chooser = INameChooser(container)
            # INameFromTitle adaptable objects should not get a name
            # suggestion. NameChooser would prefer the given name instead of
            # the one provided by the INameFromTitle adapter.
            suggestion = None
            name_from_title = INameFromTitle(obj, None)
            if name_from_title is None:
                suggestion = obj.Title()
            id_ = chooser.chooseName(suggestion, obj)
            obj.id = id_
        new_id = container._setObject(id_, obj)
        # _setObject triggers ObjectAddedEvent which can end up triggering a
        # content rule to move the item to a different container. In this case
        # look up the object by UUID.
        try:
            return container._getOb(new_id)
        except AttributeError:
            uuid = IUUID(obj)
            return uuidToObject(uuid)
Esempio n. 43
0
def plumi4to41(context, logger=None):
    # add html5 field to transcode.star registry
    registry = getUtility(IRegistry)
    html5_field = Field.Choice(title = u'Choose video embed method',
                               description=u"Choose if you would like to use just the HTML5 video tag, or Flash (Flowplayer) or if you would like to use HTML5 with Flowplayer as failback for browsers that don't support the HTML5 video tag",
                               values = ['HTML5 video tag', 'HTML5 Flash fallback', 'Flash - Flowplayer'],
                               default = "HTML5 Flash fallback",
                              )
    html5_record = Record(html5_field)
    registry.records['collective.transcode.star.interfaces.ITranscodeSettings.html5'] = html5_record

    #update user favorite folders
    users = context.acl_users.getUsers()
    pm = context.portal_membership
    addable_types = ['Link']
    for user in users:
        mf =  pm.getHomeFolder(user.getId())
        try:
            favs = mf.Favorites
            if base_hasattr(favs, 'setConstrainTypesMode'):
                favs.setConstrainTypesMode(1)
                favs.setImmediatelyAddableTypes(addable_types)
                favs.setLocallyAllowedTypes(addable_types)
        except:
            pass
Esempio n. 44
0
def getObjSize(obj):
    """ Helper method for catalog based folder contents.
    """
    smaller = SIZE_ORDER[-1]

    if base_hasattr(obj, 'get_size'):
        size = obj.get_size()
    else:
        size = 0

    # if the size is a float, then make it an int
    # happens for large files
    try:
        size = int(size)
    except (ValueError, TypeError):
        pass

    if not size:
        return '0 %s' % smaller

    if isinstance(size, (int, long)):
        if size < SIZE_CONST[smaller]:
            return '1 %s' % smaller
        for c in SIZE_ORDER:
            if size / SIZE_CONST[c] > 0:
                break
        return '%.1f %s' % (float(size / float(SIZE_CONST[c])), c)
    return size
Esempio n. 45
0
    def delete_ad_hoc_template_field(self):
        for container in self.objects(
                {'portal_type': 'opengever.meeting.committeecontainer'},
                'Delete ad-hoc templates'):

            if base_hasattr(container, 'ad_hoc_template'):
                delattr(container, 'ad_hoc_template')
Esempio n. 46
0
 def calculate_parents_value(self, field, p_fields):
     """ Calculate parents_... field on direct parent """
     obj = self.context
     parent = obj.aq_parent
     new_value = []
     for dic in p_fields:
         if dic['p_if'].providedBy(parent):
             if base_hasattr(parent, field) and getattr(parent, field):
                 new_value += [val for val in getattr(parent, field) if val not in new_value]
             # we add parent field value
             parent_value = base_hasattr(parent, dic['at']) and getattr(parent, dic['at']) or None
             if parent_value:
                 if not isinstance(parent_value, (list, tuple)):
                     parent_value = [parent_value]
                 new_value += [val for val in parent_value if val not in new_value]
     return new_value
Esempio n. 47
0
 def __getattr__(self, name):
     if not base_hasattr(self.context.fti, 'localroles') \
             or name not in self.context.fti.localroles \
             or not isinstance(self.context.fti.localroles[name], dict):
         raise AttributeError
     value = self.context.fti.localroles[name]
     return self.convert_to_list(value)
    def manage_afterAdd(self, item, container, **kw):
        """Setup properties and sub-objects"""
        # Only run on add, not rename, etc.
        if not base_hasattr(self, 'mqueue'):
            setMailBoxerProperties(self, self.REQUEST, kw)
            # Setup the default checkMail validator chain
            setDefaultValidatorChain(self)

            # Add Archive
            archive = zapi.createObject('listen.ArchiveFactory', self.storage,
                                        title=u'List Archive')
            item._setObject(self.storage, archive)

            # Add moderation queue
            mqueue = zapi.createObject('listen.QueueFactory', self.mailqueue,
                                       title=u'Moderation queue')
            item._setObject(self.mailqueue, mqueue)

            ttool = getToolByName(self, 'portal_types', None)
            if ttool is not None:
                # If the archive/queue are CMF types then we must finish
                # constructing them.
                fti = ttool.getTypeInfo(mqueue)
                if fti is not None:
                    fti._finishConstruction(mqueue)
                fti = ttool.getTypeInfo(archive)
                if fti is not None:
                    fti._finishConstruction(archive)
        MailBoxer.manage_afterAdd(self, self.REQUEST, kw)
Esempio n. 49
0
 def set_text(text):
     if base_hasattr(doc, 'setText'):
         # Archetypes
         doc.setText(text)
     else:
         # Dexterity
         doc.text = RichTextValue(text)
Esempio n. 50
0
 def display(self, field):
     """ Display budget fields and annotations """
     AK = SUMMARIZED_FIELDS[field]
     b_c = a_c = u_c = 0
     bret = ['Budget fields']
     cret = ['Budget annotations']
     path = '/'.join(self.context.getPhysicalPath())
     lpath = len(path)
     pt = ('pstsubaction', 'pstaction', 'operationalobjective',
           'strategicobjective')
     for brain in self.context.portal_catalog(portal_type=pt,
                                              path=path,
                                              sort_on='path'):
         obj = brain.getObject()
         if base_hasattr(obj, field) and getattr(obj, field):
             b_c += 1
             bret.append("{}: {} = {}".format(
                 object_link(
                     obj, content=brain.getPath()[lpath:]).encode('utf-8'),
                 brain.UID, getattr(obj, field)))
         obj_annotations = IAnnotations(obj)
         if AK in obj_annotations and obj_annotations[AK]:
             a_c += 1
             u_c += len([
                 uid for uid in obj_annotations[AK]
                 if obj_annotations[AK][uid]
             ])
             cret.append("{}: {}".format(
                 object_link(
                     obj, content=brain.getPath()[lpath:]).encode('utf-8'),
                 obj_annotations[AK]))
     sep = '<br />\n'
     return sep.join(['b:{}, a:{}, u:{}'.format(b_c, a_c, u_c), ''] + bret +
                     [''] + cret)
Esempio n. 51
0
    def create_or_modify_content(self, tus_upload):
        metadata = tus_upload.metadata()
        filename = metadata.get("filename", "")
        content_type = metadata.get("content-type", "application/octet-stream")
        mode = metadata.get("mode", "create")
        fieldname = metadata.get("fieldname")

        if mode == "create":
            type_ = metadata.get("@type")
            if type_ is None:
                ctr = getToolByName(self.context, "content_type_registry")
                type_ = ctr.findTypeName(filename.lower(), content_type,
                                         "") or "File"

            obj = create(self.context, type_)
        else:
            obj = self.context

        if not fieldname:
            info = IPrimaryFieldInfo(obj, None)
            if info is not None:
                fieldname = info.fieldname
            elif base_hasattr(obj, "getPrimaryField"):
                field = obj.getPrimaryField()
                fieldname = field.getName()

        if not fieldname:
            return self.error("Bad Request", "Fieldname required", 400)

        # Acquisition wrap temporarily for deserialization
        temporarily_wrapped = False
        if IAcquirer.providedBy(obj) and not safe_hasattr(obj, "aq_base"):
            obj = obj.__of__(self.context)
            temporarily_wrapped = True

        # Update field with file data
        deserializer = queryMultiAdapter((obj, self.request),
                                         IDeserializeFromJson)
        if deserializer is None:
            return self.error(
                "Not Implemented",
                f"Cannot deserialize type {obj.portal_type}",
                501,
            )
        try:
            deserializer(data={fieldname: tus_upload}, create=mode == "create")
        except DeserializationError as e:
            return self.error("Deserialization Error", str(e), 400)

        if temporarily_wrapped:
            obj = aq_base(obj)

        if mode == "create":
            if not getattr(deserializer, "notifies_create", False):
                notify(ObjectCreatedEvent(obj))
            obj = add(self.context, obj)

        tus_upload.close()
        tus_upload.cleanup()
        self.request.response.setHeader("Location", obj.absolute_url())
Esempio n. 52
0
 def Title(self):
     if self.incomingmail:
         return _(u"Incoming mail")
     elif base_hasattr(self, 'signed') and self.signed:
         return _(u"Signed version")
     else:
         return self.title
Esempio n. 53
0
    def related_items(self):
        context = aq_inner(self.context)
        res = ()

        # Archetypes
        if base_hasattr(context, 'getRawRelatedItems'):
            catalog = getToolByName(context, 'portal_catalog')
            related = context.getRawRelatedItems()
            if not related:
                return ()
            brains = catalog(UID=related)
            if brains:
                # build a position dict by iterating over the items once
                positions = dict([(v, i) for (i, v) in enumerate(related)])
                # We need to keep the ordering intact
                res = list(brains)

                def _key(brain):
                    return positions.get(brain.UID, -1)
                res.sort(key=_key)

        # Dexterity
        if has_relationfield_installed:
            if IRelatedItems.providedBy(context):
                related = context.relatedItems
                if not related:
                    return ()
                res = [self.rel2brain(rel) for rel in related]

        return res
Esempio n. 54
0
    def indexObject(obj, path):

        if (base_hasattr(obj, 'indexObject') and
            safe_callable(obj.indexObject)):

            try:
                obj.indexObject()

                annotions = IAnnotations(obj)
                catalog = getToolByName(obj, 'portal_catalog', None)
                if ANNOTATION_KEY in annotions:
                    conversation = annotions[ANNOTATION_KEY]
                    conversation = conversation.__of__(obj)
                    for comment in conversation.getComments():
                        try:
                            comment = comment.__of__(conversation)
                            if catalog:
                                catalog.indexObject(comment)
                        except StopIteration: # pragma: no cover
                            pass

            except TypeError:
                # Catalogs have 'indexObject' as well, but they
                # take different args, and will fail
                pass
 def set_text(text):
     if base_hasattr(doc, 'setText'):
         # Archetypes
         doc.setText(text)
     else:
         # Dexterity
         doc.text = RichTextValue(text)