Esempio n. 1
0
    def test_migrate_archetypes_page_to_dexterity(self):
        self.grant('Manager')

        page = create(Builder('page')
                      .titled('The Page')
                      .having(text='<p>Some Text</p>')
                      .in_state('published'))

        self.assertTrue(IBaseObject.providedBy(page))
        self.assertFalse(IDexterityContent.providedBy(page))
        self.assertEqual('The Page', page.Title())
        self.assertEqual('<p>Some Text</p>', page.getText())
        self.assertEqual('published', self.review_state(page))

        self.install_profile('plone.app.contenttypes:default')
        InplaceMigrator('Document').migrate_object(page)

        page = self.portal.get('the-page')
        self.assertFalse(IBaseObject.providedBy(page))
        self.assertTrue(IDexterityContent.providedBy(page))
        self.assertEqual(('', 'plone', 'the-page'), page.getPhysicalPath())
        self.assertEqual('The Page', page.Title())
        self.assertIsInstance(page.text, RichTextValue)
        self.assertEqual('<p>Some Text</p>', page.text.output)
        self.assertEqual('published', self.review_state(page))
Esempio n. 2
0
    def test_migrate_constrain_types(self):
        self.grant('Manager')
        self.maxDiff = None

        folder = create(Builder('folder').titled('The Folder'))
        self.set_constraintypes_config(
            folder,
            {'mode': ENABLED,
             'locally allowed': ['Folder', 'Document', 'File'],
             'immediately addable': ['Folder', 'Document']})

        self.assertTrue(IBaseObject.providedBy(folder))
        self.assertFalse(IDexterityContent.providedBy(folder))
        self.assertDictEqual(
            {'mode': ENABLED,
             'locally allowed': {'Folder', 'Document', 'File'},
             'immediately addable': {'Folder', 'Document'}},
            self.get_constraintypes_config(folder))

        self.install_profile('plone.app.contenttypes:default')
        InplaceMigrator('Folder').migrate_object(folder)

        folder = self.portal.get('the-folder')
        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertDictEqual(
            {'mode': ENABLED,
             'locally allowed': {'Folder', 'Document', 'File'},
             'immediately addable': {'Folder', 'Document'}},
            self.get_constraintypes_config(folder))
Esempio n. 3
0
    def test_migrate_constrain_types(self):
        self.grant('Manager')
        self.maxDiff = None

        folder = create(Builder('folder').titled(u'The Folder'))
        self.set_constraintypes_config(
            folder, {
                'mode': ENABLED,
                'locally allowed': ['Folder', 'Document', 'File'],
                'immediately addable': ['Folder', 'Document']
            })

        self.assertTrue(IBaseObject.providedBy(folder))
        self.assertFalse(IDexterityContent.providedBy(folder))
        self.assertDictEqual(
            {
                'mode': ENABLED,
                'locally allowed': {'Folder', 'Document', 'File'},
                'immediately addable': {'Folder', 'Document'}
            }, self.get_constraintypes_config(folder))

        self.install_profile('plone.app.contenttypes:default')
        InplaceMigrator('Folder').migrate_object(folder)

        folder = self.portal.get('the-folder')
        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertDictEqual(
            {
                'mode': ENABLED,
                'locally allowed': {'Folder', 'Document', 'File'},
                'immediately addable': {'Folder', 'Document'}
            }, self.get_constraintypes_config(folder))
Esempio n. 4
0
    def test_migrate_dexterity_folder_to_dexterity(self):
        self.grant('Manager')
        self.install_profile('plone.app.contenttypes:default')

        creation_date = datetime(2015, 11, 29, 10, 45)
        modification_date = datetime(2016, 1, 2, 9, 30)
        effective_date = datetime(2016, 2, 2, 2, 30)
        expires_date = datetime(2016, 3, 3, 3, 30)

        with dx_content_builders_registered():
            with freeze(creation_date):
                folder = create(Builder('folder')
                                .titled(u'The Folder')
                                .having(description=u'The Description',
                                        exclude_from_nav=True,
                                        subjects=(u'One', u'Two'),
                                        effective=effective_date,
                                        expires=expires_date)
                                .in_state('pending'))

        with freeze(modification_date):
            folder.reindexObject()  # update modification date

        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertEqual(('', 'plone', 'the-folder'), folder.getPhysicalPath())
        self.assertEqual('The Folder', folder.Title())
        self.assertEqual('The Description', folder.Description())
        self.assertEqual(True, folder.exclude_from_nav)
        self.assertEqual(('One', 'Two'), folder.Subject())
        self.assertEqual(todt(creation_date), todt(folder.created()))
        self.assertEqual(todt(modification_date), todt(folder.modified()))
        self.assertEqual(todt(effective_date), todt(folder.effective()))
        self.assertEqual(todt(expires_date), todt(folder.expires()))
        self.assertEqual('pending', self.review_state(folder))

        old_catalog_indexdata = self.get_catalog_indexdata_for(folder)

        InplaceMigrator('Folder').migrate_object(folder)

        folder = self.portal.get('the-folder')
        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertEqual(('', 'plone', 'the-folder'), folder.getPhysicalPath())
        self.assertEqual('The Folder', folder.Title())
        self.assertEqual('The Description', folder.Description())
        self.assertEqual(True, folder.exclude_from_nav)
        self.assertEqual(('One', 'Two'), folder.Subject())
        self.assertEqual(todt(creation_date), todt(folder.created()))
        self.assertEqual(todt(modification_date), todt(folder.modified()))
        self.assertEqual(todt(effective_date), todt(folder.effective()))
        self.assertEqual(todt(expires_date), todt(folder.expires()))
        self.assertEqual('pending', self.review_state(folder))

        self.maxDiff = None
        self.assertDictEqual(old_catalog_indexdata,
                             self.get_catalog_indexdata_for(folder))
Esempio n. 5
0
    def test_migrate_dexterity_folder_to_dexterity(self):
        self.grant('Manager')
        self.install_profile('plone.app.contenttypes:default')

        creation_date = datetime(2015, 11, 29, 10, 45)
        modification_date = datetime(2016, 1, 2, 9, 30)
        effective_date = datetime(2016, 2, 2, 2, 30)
        expires_date = datetime(2016, 3, 3, 3, 30)

        with dx_content_builders_registered():
            with freeze(creation_date):
                folder = create(
                    Builder('folder').titled(u'The Folder').having(
                        description=u'The Description',
                        exclude_from_nav=True,
                        subjects=(u'One', u'Two'),
                        effective=effective_date,
                        expires=expires_date).in_state('pending'))

        with freeze(modification_date):
            folder.reindexObject()  # update modification date

        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertEqual(('', 'plone', 'the-folder'), folder.getPhysicalPath())
        self.assertEqual('The Folder', folder.Title())
        self.assertEqual('The Description', folder.Description())
        self.assertEqual(True, folder.exclude_from_nav)
        self.assertEqual(('One', 'Two'), folder.Subject())
        self.assertEqual(todt(creation_date), todt(folder.created()))
        self.assertEqual(todt(modification_date), todt(folder.modified()))
        self.assertEqual(todt(effective_date), todt(folder.effective()))
        self.assertEqual(todt(expires_date), todt(folder.expires()))
        self.assertEqual('pending', self.review_state(folder))

        old_catalog_indexdata = self.get_catalog_indexdata_for(folder)

        InplaceMigrator('Folder').migrate_object(folder)

        folder = self.portal.get('the-folder')
        self.assertFalse(IBaseObject.providedBy(folder))
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertEqual(('', 'plone', 'the-folder'), folder.getPhysicalPath())
        self.assertEqual('The Folder', folder.Title())
        self.assertEqual('The Description', folder.Description())
        self.assertEqual(True, folder.exclude_from_nav)
        self.assertEqual(('One', 'Two'), folder.Subject())
        self.assertEqual(todt(creation_date), todt(folder.created()))
        self.assertEqual(todt(modification_date), todt(folder.modified()))
        self.assertEqual(todt(effective_date), todt(folder.effective()))
        self.assertEqual(todt(expires_date), todt(folder.expires()))
        self.assertEqual('pending', self.review_state(folder))

        self.maxDiff = None
        self.assertDictEqual(old_catalog_indexdata,
                             self.get_catalog_indexdata_for(folder))
Esempio n. 6
0
 def afterRetrieveModifier(self, obj, repo_clone, preserve=()):
     """Restore relations from the working copy."""
     if (IDexterityContent.providedBy(obj)
             and IDexterityContent.providedBy(repo_clone)):
         for schemata in iterSchemata(obj):
             for name, field in getFields(schemata).items():
                 if (IRelationChoice.providedBy(field)
                         or IRelationList.providedBy(field)):
                     field.set(field.interface(repo_clone),
                               field.query(field.interface(obj)))
     return [], [], {}
 def afterRetrieveModifier(self, obj, repo_clone, preserve=()):
     """Restore relations from the working copy."""
     if (
         IDexterityContent.providedBy(obj) and
         IDexterityContent.providedBy(repo_clone)
     ):
         for schemata in iterSchemata(obj):
             for name, field in getFields(schemata).items():
                 if (IRelationChoice.providedBy(field) or
                         IRelationList.providedBy(field)):
                     field.set(field.interface(repo_clone),
                               field.query(field.interface(obj)))
     return [], [], {}
Esempio n. 8
0
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem(u'vorwaerts', _(u'vorwaerts')),
            VocabItem(u'rueckwaerts', _(u'rueckwaerts')),
            VocabItem(u'brutto', _(u'brutto')),
            VocabItem(u'netto', _(u'netto')),
            VocabItem(u'nass', _(u'nass')),
            VocabItem(u'trocken', _(u'trocken')),
            VocabItem(u'Messergebnisse', _(u'Messergebnisse')),
            VocabItem(u'Ueberblick', _(u'Ueberblick')),
            VocabItem(u'Soll-Ist-Vergleich', _(u'Soll-Ist-Vergleich'))
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=item.token.encode('utf'),
                    title=item.value,
                )
            )
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 9
0
def restore_backrefs(portal, obj):
    """Restore backreferences stored in the attribute _backrefs.
    """
    intids = getUtility(IIntIds)
    uid_catalog = getToolByName(portal, 'uid_catalog')
    try:
        backrefobjs = [uuidToObject(uuid) for uuid in obj._backrefs]
        for backrefobj in backrefobjs:
            # Dexterity and
            if IDexterityContent.providedBy(backrefobj):
                relitems = getattr(backrefobj, 'relatedItems', None)
                if not relitems:
                    backrefobj.relatedItems = PersistentList()
                elif not isinstance(obj.relatedItems, PersistentList):
                    backrefobj.relatedItems = PersistentList(obj.relatedItems)
                to_id = intids.getId(obj)
                backrefobj.relatedItems.append(RelationValue(to_id))

            # Archetypes
            elif IATContentType.providedBy(backrefobj):
                # reindex UID so we are able to set the reference
                path = '/'.join(obj.getPhysicalPath())
                uid_catalog.catalog_object(obj, path)
                backrefobj.setRelatedItems(obj)
            logger.info('Restored BackRelation from %s to %s' %
                        (backrefobj, obj))
    except AttributeError:
        pass
 def _hasFiles(self, obj, fields):
     # If file is empty then do nothing
     if IDexterityContent.providedBy(obj):
         fileSize = sum([f[1].getSize() for f in fields])
     else:
         fileSize = sum([len(f.get(obj).data) for f in fields])
     return fileSize != 0
Esempio n. 11
0
 def __call__(self, field_name):
     """Load appy_pod.html into context's p_field_name XHTML field."""
     plone_utils = api.portal.get_tool('plone_utils')
     file_path = path.join(path.dirname(__file__), 'appy_pod.html')
     data = open(file_path, 'r')
     filled = False
     if IDexterityContent.providedBy(self.context):
         # dexterity
         portal_types = api.portal.get_tool('portal_types')
         fti = portal_types[self.context.portal_type]
         schema = fti.lookupSchema()
         field = schema.get(field_name)
         if field and isinstance(field, RichText):
             setattr(self.context, field_name, RichTextValue(data.read()))
             filled = True
     else:
         # Archetypes
         field = self.context.getField(field_name)
         if field and field.widget.getName() == 'RichWidget':
             field.getMutator(self.context)(data.read(), content_type='text/html')
             filled = True
     data.close()
     if filled:
         plone_utils.addPortalMessage("Field '{0}' has been filled.".format(field_name))
     else:
         plone_utils.addPortalMessage(
             "Field named '{0}' is not a field to store XHTML content!".format(field_name),
             type="error")
     self.request.RESPONSE.redirect(self.context.absolute_url())
Esempio n. 12
0
def _delete_at_example_content(portal):
    all_content = portal.portal_catalog()
    if all_content:
        expected = [
            'front-page',
            'news',
            'aggregator',
            'events',
            'aggregator',
            'Members'
        ]
        if not [i.id for i in all_content] == expected:
            return
        to_delete = ['front-page', 'news', 'events', 'Members']
        for i in to_delete:
            obj = portal[i]
            if IDexterityContent.providedBy(obj):
                return
            modification_date = obj.modification_date.utcdatetime()
            creation_date = obj.creation_date.utcdatetime()
            delta = modification_date - creation_date
            if delta >= timedelta(seconds=1):
                return
        # None of the default content is dexterity and has been modified.
        portal.manage_delObjects(to_delete)
Esempio n. 13
0
 def __call__(self):
     """Make sure all content objects use the proper base classes.
        Instances before version 1.0b1 had no base-class.
        To update them call @@fix_base_classes on your site-root.
     """
     out = ""
     portal_types = [
         ("Document", Document),
         ("Event", Event),
         ("File", File),
         ("Folder", Folder),
         ("Image", Image),
         ("Link", Link),
         ("News Item", NewsItem),
     ]
     catalog = getToolByName(self.context, "portal_catalog")
     for portal_type, portal_type_class in portal_types:
         results = catalog.searchResults(portal_type=portal_type)
         for brain in results:
             obj = brain.getObject()
             if IDexterityContent.providedBy(obj):
                 object_class_name = obj.__class__.__name__
                 target_class_name = portal_type_class.__name__
                 if not object_class_name == target_class_name:
                     obj.__class__ = portal_type_class
                     out += "Make %s use %s\n as base class." % (obj.Title(), portal_type_class.__name__)
     return out
def find_content_with_wrong_language(content):
    """log non-default content with different languages than their parents
    Used to make sure we cleaned up everything.
    In part stolen and adapted from
    plone.app.multilingual.browser.migrator.moveContentToProperRLF.findContent
    """
    # only handle portal content
    from plone.dexterity.interfaces import IDexterityContent
    from Products.Archetypes.interfaces import IBaseObject
    from Acquisition import aq_base
    from Acquisition import aq_parent
    try:
        from Products.LinguaPlone.interfaces import ITranslatable
    except ImportError:
        from plone.app.multilingual.interfaces import ITranslatable

    if not IDexterityContent.providedBy(content)\
            and not IBaseObject.providedBy(content)\
            and not IPloneSiteRoot.providedBy(content):
        return
    if hasattr(aq_base(content), 'objectIds'):
        for id in content.objectIds():
            find_content_with_wrong_language(getattr(content, id))
    if ITranslatable.providedBy(content):
        # The content parent has the same language?
        if not IPloneSiteRoot.providedBy(aq_parent(content)) \
           and aq_parent(content).Language() != content.Language():
            log.info('Obj %s (%s) not same language as parent (%s)' %
                     (content.absolute_url_path(), content.Language(),
                      aq_parent(content).Language()))  # noqa: E501
Esempio n. 15
0
    def __iter__(self):
        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]

            if HAS_PAM:
                if not pathkey:
                    # not enough info
                    yield item; continue

                obj = self.context.unrestrictedTraverse(str(item[pathkey]).lstrip('/'), None)

                if obj is None:
                    # path doesn't exist
                    yield item; continue

                if item.get('_translations', False):
                    lang_info = []
                    for lang in item['_translations']:
                        target_obj = self.context.unrestrictedTraverse(str('{}{}'.format(lang, item['_translations'][lang])).lstrip('/'), None)
                        if target_obj and (IBaseObject.providedBy(target_obj) or IDexterityContent.providedBy(target_obj)):
                            lang_info.append((target_obj, lang),)
                    try:
                        self.link_translations(lang_info)
                    except IndexError:
                        continue

            yield item
 def getATTypesWithoutFTI(self):
     """Returns a list of the id's of archetypes-types that are
        not registered in portal_types but still have instances.
     """
     results = []
     all_registered_types = [i['id'] for i in self.getATFTIs()]
     catalog = getToolByName(self.context, 'portal_catalog')
     for meta_type in catalog.uniqueValuesFor('meta_type'):
         # querying for meta_type will only return at-types
         brain = catalog(meta_type=meta_type, sort_limit=1)[0]
         try:
             obj = brain.getObject()
         except (KeyError, NotFound):
             continue
         if IDexterityContent.providedBy(obj):
             continue
         if not IBaseObject.providedBy(obj):
             # Discussion items are neither AT not DX
             continue
         typename = brain.portal_type
         if typename not in all_registered_types:
             results.append({'id': typename,
                             'title': typename,
                             'removed': True})
     return results
def importKeywords(context):
    """Create a document with an empty body to setup all keywords"""
    keywords = context.readDataFile("keywords.txt")
    if keywords is None:
        return

    keywords = to_str(keywords)
    keywordlist = [i for i in keywords.split("\n") if i]
    if len(keywordlist) < 1:
        return

    site = context.getSite()
    id = "keywords"
    doc = getattr(site, id, None)

    if doc is None:
        site.invokeFactory("Document", id, title="Keywords")
        doc = getattr(site, id)

    doc.setSubject(keywordlist)
    if hasattr(IDexterityContent, "providedBy") and IDexterityContent.providedBy(doc):
        doc.exclude_from_nav = True
    else:
        doc.setExcludeFromNav(True)
    doc.reindexObject()
    doc.unmarkCreationFlag()
Esempio n. 18
0
 def get_field_values(self, old_object):
     if IBaseObject.providedBy(old_object):
         return self.get_at_field_values(old_object)
     elif IDexterityContent.providedBy(old_object):
         return self.get_dx_field_values(old_object)
     else:
         raise NotImplementedError('Only AT and DX is supported.')
Esempio n. 19
0
    def getMenuItems(self, context, request):
        if not IDexterityContent.providedBy(context):
            return []

        items = getTranslationActionItems(context, request)

        # 6. Add link to language controlpanel.
        site = getToolByName(context, name="portal_url").getPortalObject()
        mt = getToolByName(context, "portal_membership")
        if mt.checkPermission(ManagePortal, site):
            items.append({
                "title": _(u"title_language_settings",
                           default=u"Language settings..."),
                "description": _(u"description_language_settings",
                                 default=u""),
                "action": site.absolute_url() + "/@@language-controlpanel",
                "selected": False,
                "icon": None,
                "extra": {"id": "_language_settings",
                          "separator": None,
                          "class": ""},
                "submenu": None,
            })

        return items
def set_plain_description(obj, evt):  # pylint: disable=W0613
    """
    if obj has "rich_description" field, we have to:
    1. strip html tags from rich_description
    2. set description with cleaned text
    """
    portal = getUtility(IPloneSiteRoot)
    ard_prefs = IRichDescriptionForm(portal)
    if ard_prefs.richdescription_properties is not None:
        portal_type = getattr(obj, 'portal_type', None)
        if portal_type in ard_prefs.allowed_types:
            rich_description = ''
            if IDexterityContent.providedBy(obj):
                adapts = IRichDescriptionBehavior(obj, None)
                if adapts:
                    rich_description = adapts.rich_description.output
            else:
                field = obj.getField('rich_description')
                if field:
                    rich_description = field.get(obj)

            plain_text = ''
            if rich_description:
                transforms = getToolByName(portal, 'portal_transforms')
                data = transforms.convert('html_to_text', rich_description)
                plain_text = data.getData()
            plain_text = plain_text.strip()
            plain_text = plain_text.replace('\n', ' ').replace('\r', '')
            obj.setDescription(plain_text)
            obj.reindexObject(idxs=['Description'])
Esempio n. 21
0
    def update(self):
        schemas = [self.form.schema]

        if IDexterityContent.providedBy(self.context):
            fti = getUtility(IDexterityFTI, name=self.context.portal_type)
            for name in fti.behaviors:
                behavior = queryUtility(IBehavior, name=name)
                if behavior and behavior.interface.extends(model.Schema):
                    schemas.append(behavior.interface)

        directives = []
        for schema in schemas:
            directives += mergedTaggedValueList(schema, DEPENDENCY_KEY)

        dependencies = {}
        for directive in directives:
            dependencies.setdefault(directive.name, []).append(directive)

        todo = collections.deque([self.form])
        while todo:
            group = todo.pop()
            if hasattr(group, "groups"):
                todo.extendleft(group.groups)
            for (name, field) in group.fields.items():
                depends = dependencies.get(name, None)
                if depends is None:
                    continue
                field.field._dependencies = depends
Esempio n. 22
0
    def __call__(self, context):
        # An award moves through multiple states. Releases over time can update
        # the status of an award.
        # https://standard.open-contracting.org/latest/en/schema/codelists/#award-status

        items = [
            VocabItem(u'pending', _(u'Pending')),
            VocabItem(u'active', _(u'Active')),
            VocabItem(u'cancelled', _(u'Cancelled')),
            VocabItem(u'uncessfull', _(u'Unsuccessful')),
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=str(item.token),
                    title=item.value,
                ))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem("pagare", _("Pagare")),
            VocabItem("iscriversi", _("Iscriversi")),
            VocabItem("richiedere", _("Richiedere")),
            VocabItem("leggere", _("Leggere")),
            VocabItem("attivare", _("Attivare")),
            VocabItem("autorizzare", _("Autorizzare")),
            VocabItem("delegare", _("Delegare")),
            VocabItem("informare", _("Informare")),
            VocabItem("accettare", _("Accettare")),
        ]
        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(value=item.token,
                           token=str(item.token),
                           title=item.value))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 24
0
def getProjectSpace(context):
    """
      Return the projectspace object, context is an element in a projectspace
    """
    # MUST BE ANALYZED BECAUSE it's called many time at view or edit
    # if context is None, we have to find it in request
    if context is None:
        portal = getSite()
        if 'PUBLISHED' not in portal.REQUEST:
            # This happen in rare situation (e.g. contentree widget search)
            context = portal.REQUEST['PARENTS'][-1]
        elif hasattr(portal.REQUEST['PUBLISHED'], 'context'):
            context = portal.REQUEST['PUBLISHED'].context
        else:
            context = portal.REQUEST['PARENTS'][0]
    # when editing dexterity fields in configuration, like on operationalobjective
    if ITypeSchemaContext.providedBy(context):
        return api.content.find(object_provides=IProjectSpace.__identifier__)[0].getObject()
    # sometimes, for inline validation for example on addView, context is not the object
    # but a Form of different kind, the real object is the form.context
    if not IDexterityContent.providedBy(context):
        context = context.context
    parent = context
    while not IProjectSpace.providedBy(parent) and parent.portal_type != 'Plone Site':
        parent = parent.aq_inner.aq_parent
    return parent
Esempio n. 25
0
def create_object(context, portal_type, data):
    """ """
    title = get_text_line()
    if data.get('type_in_title'):
        pt = api.portal.get_tool('portal_types')
        title = '%s: %s' % (
            pt.getTypeInfo(portal_type).title,
            title
        )
    data['title'] = title
    unique_id = generate_unique_id(context, title, portal_type)
    args = {'id': unique_id}
    if portal_type in ['Image', 'File']:
        myfile = StringIO(decodestring(
            'R0lGODlhAQABAPAAAPj8+AAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='))
        ext = portal_type == 'Image' and 'gif' or 'dat'
        myfile.filename = '.'.join((get_text_line().split(' ')[-1], ext))
        args.update({'file': myfile})

    new_id = context.invokeFactory(portal_type, **args)
    obj = context[new_id]

    if IDexterityContent.providedBy(obj):
        populate_dexterity(obj, data)
    else:
        populate_archetype(obj, data)

    if data.get('publish', True):
        wftool = api.portal.get_tool('portal_workflow')
        try:
            wftool.doActionFor(obj, 'publish')
        except WorkflowException, e:
            log.warn(e)
Esempio n. 26
0
 def __call__(self):
     """Make sure all content objects use the proper base classes.
     Instances before version 1.0b1 had no base-class.
     To update them call @@fix_base_classes on your site-root.
     """
     out = ""
     portal_types = [
         ('Document', Document),
         ('File', File),
         ('Folder', Folder),
         ('Image', Image),
         ('Link', Link),
         ('News Item', NewsItem),
     ]
     catalog = getToolByName(self.context, "portal_catalog")
     query = {}
     if HAS_MULTILINGUAL and 'Language' in catalog.indexes():
         query['Language'] = 'all'
     for portal_type, portal_type_class in portal_types:
         query['portal_type'] = portal_type
         results = catalog(query)
         for brain in results:
             obj = brain.getObject()
             if IDexterityContent.providedBy(obj):
                 object_class_name = obj.__class__.__name__
                 target_class_name = portal_type_class.__name__
                 if not object_class_name == target_class_name:
                     obj.__class__ = portal_type_class
                     out += "Make %s use %s\n as base class." % (
                         obj.Title(),
                         portal_type_class.__name__,
                     )
     return out
Esempio n. 27
0
def create_object(context, portal_type, data):
    """ """
    title = get_text_line()
    unique_id = generate_unique_id(context, title, portal_type)

    args = dict(id=unique_id)
    if portal_type in ['Image', 'File']:
        myfile = StringIO(decodestring('R0lGODlhAQABAPAAAPj8+AAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='))
        ext =  portal_type == 'Image' and 'gif' or 'dat'
        myfile.filename = '.'.join((get_text_line().split(' ')[-1], ext))
        args.update({'file':myfile})

    new_id= context.invokeFactory(portal_type, **args)
    obj = context[new_id]

    if IDexterityContent.providedBy(obj):
        if shasattr(obj, 'title'):
            obj.title = title
        populate_dexterity_type(obj, data)
    else:
        obj.setTitle(title)
        populate_archetype(obj, data)

    if data.get('publish', True):
        wftool = getToolByName(context, 'portal_workflow')
        try:
            wftool.doActionFor(obj, 'publish')
        except WorkflowException, e:
            log.warn(e)
Esempio n. 28
0
    def _setfile(self, obj):
        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityImage(obj):
                return self.errorMessage(
                    _("The content-type '%s' has no image-field!" % metatype))
        else:
            form = self.context.REQUEST
            if not 'uploadfile' in form:
                return self.errorMessage("Could not find file in request")
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, form['uploadfile'])
            from Products.Archetypes.event import ObjectInitializedEvent
            notify(ObjectInitializedEvent(obj))

        if not obj:
            return self.errorMessage("Could not upload the file")

        obj.reindexObject()

        if self.utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return path
Esempio n. 29
0
 def __call__(self):
     """Make sure all content objects use the proper base classes.
     Instances before version 1.0b1 had no base-class.
     To update them call @@fix_base_classes on your site-root.
     """
     out = ''
     portal_types = [
         ('Document', Document),
         ('File', File),
         ('Folder', Folder),
         ('Image', Image),
         ('Link', Link),
         ('News Item', NewsItem),
     ]
     catalog = getToolByName(self.context, 'portal_catalog')
     query = {}
     for portal_type, portal_type_class in portal_types:
         query['portal_type'] = portal_type
         results = catalog(query)
         for brain in results:
             try:
                 obj = brain.getObject()
             except (KeyError, NotFound):
                 logger.exception('Can not resolve object from brain.')
                 continue
             if IDexterityContent.providedBy(obj):
                 object_class_name = obj.__class__.__name__
                 target_class_name = portal_type_class.__name__
                 if not object_class_name == target_class_name:
                     obj.__class__ = portal_type_class
                     out += 'Make {0} use {1}\n as base class.'.format(
                         obj.Title(),
                         portal_type_class.__name__,
                     )
     return out
Esempio n. 30
0
    def getMenuItems(self, context, request):
        if not IDexterityContent.providedBy(context):
            return []

        items = getTranslationActionItems(context, request)

        # 6. Add link to language controlpanel.
        site = getToolByName(context, name="portal_url").getPortalObject()
        mt = getToolByName(context, "portal_membership")
        if mt.checkPermission(ManagePortal, site):
            items.append({
                "title":
                _(u"title_language_settings", default=u"Language settings..."),
                "description":
                _(u"description_language_settings", default=u""),
                "action":
                site.absolute_url() + "/@@language-controlpanel",
                "selected":
                False,
                "icon":
                None,
                "extra": {
                    "id": "_language_settings",
                    "separator": None,
                    "class": ""
                },
                "submenu":
                None,
            })

        return items
    def _getFields(self, obj, fieldNames):
        # If no fieldNames have been defined as transcodable,
        # then use the primary field
        # TODO: check if they are actually file fields

        fields = []
        if IDexterityContent.providedBy(obj):
            if not fieldNames:
                try:
                    primary = IPrimaryFieldInfo(obj)
                    fields = [(primary.fieldname, primary.field)]
                except TypeError:
                    log.error('No field specified and no primary field.')
            else:
                for f in fieldNames:
                    try:
                        fields.append((f, getattr(obj, f)))
                    except AttributeError:
                        log.error('No field %s on object %s.' % (f, obj))
        else:
            if not fieldNames:
                fields = [obj.getPrimaryField()]
            else:
                fields = [obj.getField(f) for f in fieldNames]
        return fields
    def __call__(self, context):

        results = []
        group_properties = dict()
        groups = api.group.get_groups()

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        for group in groups:
            group_id = group.getId()
            group_properties[group_id] = {
                "title": group.getGroupTitleOrName(),
                "email": group.getProperty("email"),
            }
        results = [(id, property["title"])
                   for id, property in group_properties.items()]

        # run registered group filter:
        for subscriber in subscribers([self], IReceiversGroupFilter):
            results = subscriber.filter(results)

        # create a list of SimpleTerm items:
        terms = []
        for item in results:
            terms.append(
                SimpleTerm(value=item[0], token=item[0], title=item[1]))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 33
0
    def test_migrate_ownership_no_IOwner(self):
        john = create(
            Builder('user').named('John', 'Doe').with_roles('Manager'))
        peter = create(
            Builder('user').named('Peter', 'Pan').with_roles('Manager'))

        login(self.portal, john.getId())
        folder = create(Builder('folder').titled(u'The Folder'))
        folder.changeOwnership(peter.getUser())

        self.assertTrue(IBaseObject.providedBy(folder))
        self.assertEqual('john.doe', folder.Creator())
        self.assertEqual('peter.pan', folder.getOwner().getId())

        self.grant('Manager')
        self.install_profile('plone.app.contenttypes:default')

        # The creators list behaves differently when the dublin core
        # behavior is used.
        self.portal.portal_types['Folder'].behaviors = tuple(
            name for name in self.portal.portal_types['Folder'].behaviors
            if not (name == 'plone.dublincore' or 'IDublinCore' in name
                    or name == 'plone.ownership' or 'IOwnership' in name))
        with self.login(SITE_OWNER_NAME):
            InplaceMigrator(
                'Folder',
                options=IGNORE_UNMAPPED_FIELDS).migrate_object(folder)

        folder = self.portal.get('the-folder')
        self.assertTrue(IDexterityContent.providedBy(folder))
        self.assertEqual('john.doe', folder.Creator())
        self.assertEqual('peter.pan', folder.getOwner().getId())
Esempio n. 34
0
    def update(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        count = 0
        query = {}
        if HAS_MULTILINGUAL and 'Language' in catalog.indexes():
            query['Language'] = 'all'

        for brain in catalog(query):
            try:
                obj = brain.getObject()
            except (AttributeError, NotFound, KeyError):
                msg = "Catalog inconsistency: {} not found!"
                logger.error(msg.format(brain.getPath()), exc_info=1)
                continue
            method = None
            if IBaseObject.providedBy(obj):
                method = modifiedArchetype
            elif IDexterityContent.providedBy(obj):
                method = modifiedDexterity
            if method:
                try:
                    method(obj, 'dummy event parameter')
                    count += 1
                except Exception:
                    msg = "Error updating linkintegrity-info for {}."
                    logger.error(msg.format(obj.absolute_url()), exc_info=1)
        return count
Esempio n. 35
0
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem(u'Topic 1', _(u'Topic 1')),
            VocabItem(u'Topic 2', _(u'Topic 2')),
            VocabItem(u'Topic 3', _(u'Topic 3')),
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=str(item.token),
                    title=item.value,
                ))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
 def download_original(self):
     if IDexterityContent.providedBy(self.context):
         return '%s/@@download/%s' % (self.context.absolute_url(),
                                      self.fieldname)
     else:
         return '%s/at_download/%s' % (self.context.absolute_url(),
                                       self.fieldname)
Esempio n. 37
0
def _getValue(ob, field, field_name, convert_to_str=True):
    # Check for the attribute without acquisition.  If it's there,
    # grab it *with* acquisition, so things like ComputedAttribute
    # will work
    if IDexterityContent.providedBy(ob) and field:
        value = getattr(ob, field, None)
    elif field and safe_hasattr(aq_base(ob), field):
        value = getattr(ob, field)
    elif safe_hasattr(aq_base(ob), 'getField'):
        # Archetypes with an adapter extended schema needs special handling
        field = ob.getField(field_name)
        if field is None:
            raise AttributeError(field)
        value = field.getAccessor(ob)
    else:
        raise AttributeError(field)

    # Handle case where the field is a method
    try:
        value = value()
    except (AttributeError, TypeError):
        pass

    if convert_to_str:
        # If this is some object, convert it to a string
        try:
            if isinstance(value, Acquisition.Implicit):
                value = str(value)
        except TypeError:
            pass

    return value
Esempio n. 38
0
    def __iter__(self):
        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]

            if HAS_PAM:
                if not pathkey:
                    # not enough info
                    yield item; continue

                obj = self.context.unrestrictedTraverse(str(item[pathkey]).lstrip('/'), None)

                if obj is None:
                    # path doesn't exist
                    yield item; continue

                if item.get('_translations', False):
                    lang_info = []
                    for lang in item['_translations']:
                        target_obj = self.context.unrestrictedTraverse(str('{}{}'.format(lang, item['_translations'][lang])).lstrip('/'), None)
                        if target_obj and (IBaseObject.providedBy(target_obj) or IDexterityContent.providedBy(target_obj)):
                            lang_info.append((target_obj, lang),)
                    try:
                        self.link_translations(lang_info)
                    except IndexError:
                        continue

            yield item
Esempio n. 39
0
    def __call__(self, context):
        crop_brains = api.content.find(
            portal_type='Crop',
            sort_on='sortable_title',
        )
        items = []
        for brain in crop_brains:
            items.append(VocabItem(brain.id, brain.Title))

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=str(item.token),
                    title=item.value,
                ))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
    def __call__(self, context):
        items = []

        registry = getUtility(IRegistry)
        output_templates = registry.get(
            "Products.EasyNewsletter.output_templates")
        for key, value in output_templates.items():
            items.append(VocabItem(key, value))
        if not len(items):
            items.append(
                VocabItem(
                    "output_default",
                    _("enl_label_default_output_template",
                      "Default output template"),
                ))

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(value=item.token,
                           token=str(item.token),
                           title=item.value))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 41
0
 def action(self, obj):
     if IDexterityContent.providedBy(obj):
         self.dx_action(obj)
     else:
         if self.effectiveDate:
             try:
                 obj.setEffectiveDate(DateTime(self.effectiveDate))
             except AttributeError:
                 pass
         if self.expirationDate:
             try:
                 obj.setExpirationDate(DateTime(self.expirationDate))
             except AttributeError:
                 pass
         if self.copyright:
             try:
                 obj.setRights(self.copyright)
             except AttributeError:
                 pass
         if self.contributors:
             try:
                 obj.setContributors(self.contributors)
             except AttributeError:
                 pass
         if self.creators:
             try:
                 obj.setCreators(self.creators)
             except AttributeError:
                 pass
         if self.exclude:
             try:
                 obj.setExcludeFromNav(self.exclude == 'yes')
             except AttributeError:
                 pass
     obj.reindexObject()
    def getSetter(self, obj, indexName):
        """Gets the setter function for the field based on the index name.

        Returns None if it can't get the function
        """
        fieldName = self.fieldNameForIndex(indexName)
        field = None
        if IComment.providedBy(obj):
            #Discussion
            field = getattr(obj, 'getField', None)
        else:
            #Archetype
            field = getattr(aq_base(obj), 'getField', None)
        # Archetypes:
        if field:
            fieldObj = field(fieldName) or field(fieldName.lower())
            if not fieldObj and fieldName.startswith('get'):
                fieldName = fieldName.lstrip('get_')
                fieldName = fieldName[0].lower() + fieldName[1:]
                fieldObj = obj.getField(fieldName)
            if fieldObj is not None:
                return fieldObj.getMutator(obj)
            return None
        # DefaultDublinCoreImpl:
        setterName = 'set' + indexName
        if getattr(aq_base(obj), setterName, None) is not None:
            return getattr(obj, setterName)
        # Dexterity
        if IDexterityContent.providedBy(obj):
            if fieldName.startswith('get'):
                fieldName = fieldName.lstrip('get_')
                fieldName = fieldName[0].lower() + fieldName[1:]
            return lambda value: setattr(obj, fieldName, value)

        return None
    def create_object(self, context, portal_type):
        """ """
        request = self.request
        url = BASE_URL + '/1/short'
        response = urllib.urlopen(url).read()
        title = StripMarkup(response.decode('utf-8')).split('.')[1]
        id = INameChooser(context).chooseName(title, context)
        try:
            id = context.invokeFactory(portal_type, id=id)
        except BadRequest:
            id += '%f' % time.time()
            id = context.invokeFactory(portal_type, id=id)

        obj = context[id]

        if IDexterityContent.providedBy(obj):
            if shasattr(obj, 'title'):
                obj.title = title
                self.populate_dexterity_type(obj)
        else:
            obj.setTitle(title)
            self.populate_archetype(obj)

        if request.get('publish', True):
            wftool = getToolByName(context, 'portal_workflow')
            try:
                wftool.doActionFor(obj, 'publish')
            except WorkflowException, e:
                log.error(e)
Esempio n. 44
0
 def __call__(self, field_name):
     """Load appy_pod.html into context's p_field_name XHTML field."""
     plone_utils = api.portal.get_tool('plone_utils')
     file_path = path.join(path.dirname(__file__), 'appy_pod.html')
     data = open(file_path, 'r')
     filled = False
     if IDexterityContent.providedBy(self.context):
         # dexterity
         portal_types = api.portal.get_tool('portal_types')
         fti = portal_types[self.context.portal_type]
         schema = fti.lookupSchema()
         field = schema.get(field_name)
         if field and isinstance(field, RichText):
             setattr(self.context, field_name, RichTextValue(data.read()))
             filled = True
     else:
         # Archetypes
         field = self.context.getField(field_name)
         if field and field.widget.getName() == 'RichWidget':
             field.getMutator(self.context)(data.read(),
                                            content_type='text/html')
             filled = True
     data.close()
     if filled:
         plone_utils.addPortalMessage(
             "Field '{0}' has been filled.".format(field_name))
     else:
         plone_utils.addPortalMessage(
             "Field named '{0}' is not a field to store XHTML content!".
             format(field_name),
             type="error")
     self.request.RESPONSE.redirect(self.context.absolute_url())
Esempio n. 45
0
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem(u'ONMON', _(u'ONMON')),
            VocabItem(u'LADA', _(u'LADA')),
            VocabItem(u'EURDEP', _(u'EURDEP'))
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=item.token.encode('utf'),
                    title=item.value,
                )
            )
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 46
0
 def __init__(self, context, feed):
     super(DexterityItem, self).__init__(context, feed)
     self.dexterity = IDexterityContent.providedBy(context)
     try:
         self.primary = IPrimaryFieldInfo(self.context, None)
     except TypeError:
         self.primary = None
Esempio n. 47
0
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem(u'fine-art', _(u'Fine Art College')),
            VocabItem(u'design', _(u'College of Design')),
            VocabItem(u'comm', _(u'College of Communications')),
            VocabItem(u'performing', _(u'College of Performing Art')),
            VocabItem(u'human', _(u'College of Humanities')),
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=str(item.token),
                    title=item.value,
                ))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 48
0
 def __call__(self):
     """Make sure all content objects use the proper base classes.
     Instances before version 1.0b1 had no base-class.
     To update them call @@fix_base_classes on your site-root.
     """
     out = ''
     portal_types = [
         ('Document', Document),
         ('File', File),
         ('Folder', Folder),
         ('Image', Image),
         ('Link', Link),
         ('News Item', NewsItem),
     ]
     catalog = getToolByName(self.context, 'portal_catalog')
     query = {}
     for portal_type, portal_type_class in portal_types:
         query['portal_type'] = portal_type
         results = catalog(query)
         for brain in results:
             try:
                 obj = brain.getObject()
             except (KeyError, NotFound):
                 logger.exception('Can not resolve object from brain.')
                 continue
             if IDexterityContent.providedBy(obj):
                 object_class_name = obj.__class__.__name__
                 target_class_name = portal_type_class.__name__
                 if not object_class_name == target_class_name:
                     obj.__class__ = portal_type_class
                     out += 'Make {0} use {1}\n as base class.'.format(
                         obj.Title(),
                         portal_type_class.__name__,
                     )
     return out
Esempio n. 49
0
def set_text(obj):
    if IDexterityContent.providedBy(obj):
        obj.text = RichTextValue(
            LOREMIPSUM_HTML_10_PARAGRAPHS, "text/html", "text/x-html-safe"
        )
    else:
        obj.setText(LOREMIPSUM_HTML_10_PARAGRAPHS)
Esempio n. 50
0
    def update(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        count = 0
        query = {}
        if HAS_MULTILINGUAL and 'Language' in catalog.indexes():
            query['Language'] = 'all'

        for brain in catalog(query):
            try:
                obj = brain.getObject()
            except (AttributeError, NotFound, KeyError):
                msg = "Catalog inconsistency: {} not found!"
                logger.error(msg.format(brain.getPath()), exc_info=1)
                continue
            method = None
            if IBaseObject.providedBy(obj):
                method = modifiedArchetype
            elif IDexterityContent.providedBy(obj):
                method = modifiedDexterity
            if method:
                try:
                    method(obj, 'dummy event parameter')
                    count += 1
                except Exception:
                    msg = "Error updating linkintegrity-info for {}."
                    logger.error(msg.format(obj.absolute_url()), exc_info=1)
        return count
Esempio n. 51
0
def restore_backrefs(portal, obj):
    """Restore backreferences stored in the attribute _backrefs.
    """
    intids = getUtility(IIntIds)
    uid_catalog = getToolByName(portal, 'uid_catalog')
    try:
        backrefobjs = [uuidToObject(uuid) for uuid in obj._backrefs]
        for backrefobj in backrefobjs:
            # Dexterity and
            if IDexterityContent.providedBy(backrefobj):
                relitems = getattr(backrefobj, 'relatedItems', None)
                if not relitems:
                    backrefobj.relatedItems = PersistentList()
                elif not isinstance(obj.relatedItems, PersistentList):
                    backrefobj.relatedItems = PersistentList(
                        obj.relatedItems
                    )
                to_id = intids.getId(obj)
                backrefobj.relatedItems.append(RelationValue(to_id))

            # Archetypes
            elif IATContentType.providedBy(backrefobj):
                # reindex UID so we are able to set the reference
                path = '/'.join(obj.getPhysicalPath())
                uid_catalog.catalog_object(obj, path)
                backrefobj.setRelatedItems(obj)
            logger.info(
                'Restored BackRelation from %s to %s' % (backrefobj, obj))
    except AttributeError:
        pass
Esempio n. 52
0
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem(u'pending', _(u'Pending')),
            VocabItem(u'active', _(u'Active')),
            VocabItem(u'cancelled', _(u'Cancelled')),
            VocabItem(u'terminated', _(u'Terminated')),
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(
                    value=item.token,
                    token=str(item.token),
                    title=item.value,
                ))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 53
0
 def safe_call(self):
     content = self.context
     if IDexterityContent.providedBy(content):
         uid = IUUID(content)
     else:
         uid = content.UID()
     return uid
Esempio n. 54
0
 def __init__(self, context, feed):
     super(DexterityItem, self).__init__(context, feed)
     self.dexterity = IDexterityContent.providedBy(context)
     try:
         self.primary = IPrimaryFieldInfo(self.context, None)
     except TypeError:
         self.primary = None
    def __call__(self, context):
        # Just an example list of content for our vocabulary,
        # this can be any static or dynamic data, a catalog result for example.
        items = [
            VocabItem("sony-a7r-iii", _("Sony Aplha 7R III")),
            VocabItem("canon-5d-iv", _("Canon 5D IV")),
            VocabItem("pippo", _("Pippo")),
            VocabItem("pluto", _("Pluto")),
            VocabItem("paperino", _("Paperino")),
            VocabItem("giovanni", _("Giovanni")),
        ]

        # Fix context if you are using the vocabulary in DataGridField.
        # See https://github.com/collective/collective.z3cform.datagridfield/issues/31:  # NOQA: 501
        if not IDexterityContent.providedBy(context):
            req = getRequest()
            context = req.PARENTS[0]

        # create a list of SimpleTerm items:
        terms = []
        for item in items:
            terms.append(
                SimpleTerm(value=item.token,
                           token=str(item.token),
                           title=item.value))
        # Create a SimpleVocabulary from the terms list and return it:
        return SimpleVocabulary(terms)
Esempio n. 56
0
    def update(self):
        schemas = [self.form.schema]

        if IDexterityContent.providedBy(self.context):
            fti = component.getUtility(
                IDexterityFTI,
                name=self.context.portal_type)
            for name in fti.behaviors:
                behavior = component.queryUtility(IBehavior, name=name)
                if behavior and behavior.interface.extends(Schema):
                    schemas.append(behavior.interface)

        directives = []
        for schema in schemas:
            directives += mergedTaggedValueList(schema, DEPENDENCY_KEY)

        dependencies = {}
        for directive in directives:
            dependencies.setdefault(directive.name, []).append(directive)

        todo=collections.deque([self.form])
        while todo:
            group=todo.pop()
            if hasattr(group, "groups"):
                todo.extendleft(group.groups)
            for (name, field) in group.fields.items():
                depends=dependencies.get(name, None)
                if depends is None:
                    continue
                field.field._dependencies=depends
Esempio n. 57
0
 def __call__(self):
     """Make sure all content objects use the proper base classes.
     Instances before version 1.0b1 had no base-class.
     To update them call @@fix_base_classes on your site-root.
     """
     out = ''
     portal_types = [
         ('Document', Document),
         ('File', File),
         ('Folder', Folder),
         ('Image', Image),
         ('Link', Link),
         ('News Item', NewsItem),
     ]
     catalog = getToolByName(self.context, 'portal_catalog')
     query = {}
     if HAS_MULTILINGUAL and 'Language' in catalog.indexes():
         query['Language'] = 'all'
     for portal_type, portal_type_class in portal_types:
         query['portal_type'] = portal_type
         results = catalog(query)
         for brain in results:
             obj = brain.getObject()
             if IDexterityContent.providedBy(obj):
                 object_class_name = obj.__class__.__name__
                 target_class_name = portal_type_class.__name__
                 if not object_class_name == target_class_name:
                     obj.__class__ = portal_type_class
                     out += 'Make {0} use {1}\n as base class.'.format(
                         obj.Title(),
                         portal_type_class.__name__,
                     )
     return out