def getContext(context=None):
    if context is NO_VALUE or context is None or not IFolderish.providedBy(context):
        #return SimpleVocabulary(terms)
        req = getRequest()
        for parent in req.PARENTS:
            if IFolderish.providedBy(parent):
                context = parent
                break
    return context
def getContext(context=None):
    if context is NO_VALUE or context is None or not IFolderish.providedBy(context):
        #return SimpleVocabulary(terms)
        req = getRequest()
        for parent in req.PARENTS:
            if IFolderish.providedBy(parent):
                context = parent
                break
    return context
Beispiel #3
0
    def getLanguage(self, langs, env):

        if not IFtwSubsiteLayer.providedBy(env):
            return base_negotiator.getLanguage(langs, env)

        # Get current published object
        obj = find_context(env)
        # Filter out CSS/JS and other non contentish objects
        # IFolderish check includes site root
        if not (IContentish.providedBy(obj) or IFolderish.providedBy(obj)):
            return base_negotiator.getLanguage(langs, env)

        nav_root = get_nav_root(obj)

        if ISubsite.providedBy(nav_root):
            # Get language stored on Subsite
            language = nav_root.force_language
            if language:
                return language
            else:
                return base_negotiator.getLanguage(langs, env)

        else:
            # Use normal Negotiator
            return base_negotiator.getLanguage(langs, env)
Beispiel #4
0
 def can_configure(self):
     """Check if folderview can be configured on context"""
     context = self.context
     if not IFolderish.providedBy(context):
         return False
     already_activated = self.isFolderViewActivated()
     return (not already_activated)
    def update(self):
        super(LogoViewlet, self).update()
        context = aq_inner(self.context)
        p_properties = getToolByName(context, 'portal_properties')
        if hasattr(p_properties, 'folder_logo_properties'):
            portal = self.portal_state.portal()
            bprops = portal.restrictedTraverse('base_properties', None)
            title = None
            folder_logo_properties = getattr(p_properties, 'folder_logo_properties')
            logo_id = IFolderLogoProperties(folder_logo_properties).logo_id
            context = aq_inner(self.context)
            catalog = getToolByName(context, 'portal_catalog')
            folders = [folder for folder in aq_chain(context) if IFolderish.providedBy(folder)]
            logos = []
            for folder in folders:
                path = '/'.join(folder.getPhysicalPath())
                brains = catalog(
                    path=dict(query=path, depth=1),
                    id = logo_id,
                    object_provides = IATImage.__identifier__,
                )
                if len(brains) != 0:
                    logos.append(brains[0])
            if len(logos) != 0:
                logoName = logo_id
                title = logos[0].Title
                portal = aq_parent(logos[0].getObject())
            elif bprops is not None:
                logoName = bprops.logoName
            else:
                logoName = 'logo.jpg'
            self.logo_tag = portal.restrictedTraverse(logoName).tag()

            self.portal_title = title or self.portal_state.portal_title()
    def background(self):
        context = aq_inner(self.context)
        p_properties = getToolByName(context, 'portal_properties')
        if hasattr(p_properties, 'folder_logo_properties'):
            catalog = getToolByName(context, 'portal_catalog')
            folder_logo_properties = getattr(p_properties, 'folder_logo_properties')
            flp = IFolderLogoProperties(folder_logo_properties)
            color = flp.background_color
            image_id = flp.background_image_id

            folders = [folder for folder in aq_chain(context) if IFolderish.providedBy(folder)]
            images = []
            for folder in folders:
                path = '/'.join(folder.getPhysicalPath())
                brains = catalog(
                    path=dict(query=path, depth=1),
                    id = image_id,
                    object_provides = IATImage.__identifier__,
                )
                if len(brains) != 0:
                    images.append(brains[0])
            if len(images) != 0:
                image_path = images[0].getPath()
                style = "background: %s url(%s) no-repeat;" % (color, image_path)
            else:
                style = "background: %s no-repeat;" % (color)
            return style
Beispiel #7
0
 def displayMailTab(self):
     # Cannot mail into the portal root
     if self.context.restrictedTraverse(
             '@@plone_context_state').is_portal_root():
         return False
     return IFolderish.providedBy(self.context) and \
         _checkPermission(AddPortalContent, self.context)
    def recurse_transition(self,
                           objs,
                           comment,
                           publication_dates,
                           include_children=False):

        data = json_body(self.request)

        for obj in objs:
            if publication_dates:
                deserializer = queryMultiAdapter((obj, self.request),
                                                 IDeserializeFromJson)
                deserializer(data=publication_dates)

            adapter = queryMultiAdapter((obj, getRequest()),
                                        ITransitionExtender,
                                        name=self.transition)
            if adapter:
                errors = adapter.validate_schema(data)
                if errors:
                    raise BadRequest(errors)

            self.wftool.doActionFor(obj,
                                    self.transition,
                                    comment=comment,
                                    transition_params=data)
            if include_children and IFolderish.providedBy(obj):
                self.recurse_transition(obj.objectValues(), comment,
                                        publication_dates, include_children)
 def fields(self):
     if 'collective.behavior.sql.behavior.behaviors.ISQLContent' not in self.context.fti.behaviors:
         return super(SQLTypeOverviewForm, self).fields
     # if this type's class is not a container,
     # remove the field for filtering contained content types
     klass = resolveDottedName(self.context.fti.klass)
     fields = field.Fields(ISQLTypeSettings)
     fti_adapted = ISQLTypeSettings(self.context.fti)
     to_omit = []
     if not fti_adapted.sql_connection:
         to_omit = ['sql_table', 'sql_id_column', 'sql_WHERE', 'sql_modification_timestamp_column', 'sql_modification_last_timestamp', 'sql_folder_id']
         fields = fields.omit('sql_table', 'sql_id_column', 'sql_WHERE', 'sql_modification_timestamp_column', 'sql_modification_last_timestamp', 'sql_folder_id')
     elif not fti_adapted.sql_table:
         to_omit = ['sql_id_column', 'sql_WHERE', 'sql_modification_timestamp_column', 'sql_modification_last_timestamp', 'sql_folder_id']
         fields = fields.omit('sql_id_column', 'sql_WHERE', 'sql_modification_timestamp_column', 'sql_modification_last_timestamp', 'sql_folder_id')
     else:
         engine = create_engine(fti_adapted.sql_connection)
         insp = reflection.Inspector.from_engine(engine)
         tables = insp.get_table_names()
         views = insp.get_view_names()
         if fti_adapted.sql_table in views and fti_adapted.sql_table not in tables:
             fields['sql_id_column'].field.vocabulary = None
             fields['sql_id_column'].field.vocabularyName = "collective.behavior.sql.AvailableSQLAlchemyColumns"
     names = [a for a in ISQLTypeSettings.names() if a not in to_omit]
     filtered = fields.select('title', 'description',
                              'allowed_content_types',
                              'filter_content_types',
                              *names)
     if not IFolderish.implementedBy(klass):
         del filtered['filter_content_types']
     urls = ISQLAlchemyConnectionStrings(component.getUtility(ISiteRoot)).values()
     if len(urls) == 1:
         filtered['sql_connection'].field.default = urls[0]
     return filtered
Beispiel #10
0
def set_folder_context_path(path, context):
    """
    Retorna o contexto da pas

    Args:
        path (list): Do caminho onde a pasta será criada
        context (plone context): Contexto de onde irá criar a pasta

    Returns:
        Retorna o contexto da ultima pasta criada 
    """

    if path:
        #Remove espacos em branco da lista
        path = [i for i in path if i]
        if path:
            p = path[0]
            normalizer = component.getUtility(IIDNormalizer)
            id = normalizer.normalize(p)
            if context.get(id, False):
                folder = context[id]
                if IFolderish.providedBy(folder):
                    if len(path) <= 1:
                        return folder
                else:
                    return False
            else:
                return False

            return set_folder_context_path(path[1:], folder)
    else:
        return context
Beispiel #11
0
def upgrade(context):
    old_stuff = [
        'challenges',
        'workspaces',
        'universities',
        'welcome-to-the-cnrd-virtual-center',
        'people',
        'library',
    ]

    attributes_to_copy = ['title', 'description', 'text', ]

    site = getSite()

    # rename old stuff
    for oid in old_stuff:
        if oid in site.keys():
            site.manage_renameObjects([oid], ['old_stuff_' + oid])
            print 'renamed %s to %s' % (oid, 'old_stuff_' + oid)
        else:
            old_stuff.remove(oid)
            print 'skipping %s' % (oid)

    # cleanup products
    quickinstaller = site.portal_quickinstaller
    installed = quickinstaller.listInstalledProducts()
    quickinstaller.uninstallProducts([p['id'] for p in installed])
    quickinstaller.installProduct('cnrd.vcpolicy')

    # move content to new folders
    for oid in old_stuff:
        old_obj = site['old_stuff_' + oid]
        new_obj = site.get(oid, None)

        if new_obj is None:
            continue

        # set attributes
        for attr in attributes_to_copy:
            value = getattr(old_obj, attr, None)
            if value is not None:
                setattr(new_obj, attr, value)

        if not IFolderish.providedBy(old_obj):
            continue

        clip = old_obj.manage_cutObjects(old_obj.keys())
        new_obj.manage_pasteObjects(clip)
        print 'content moved from %s to %s' % ('old_stuff_' + oid, oid)

    # remove old stuff
    for oid in old_stuff:
        site.manage_delObjects('old_stuff_' + oid)
        print 'removed %s' % ('old_stuff_' + oid)

    # rebuild the catalog
    catalog = getToolByName(context, 'portal_catalog')
    catalog.clearFindAndRebuild()
    for challenge in site['challenges'].values():
        challenge.reindexObject()
 def get_media_container(self):
     container = None
     config_media_path = api.portal.get_registry_record(
         'collective.behavior.relatedmedia.media_container_path')
     nav_root = api.portal.get_navigation_root(self.context)
     media_path = "{}{}".format(
         '/'.join(nav_root.getPhysicalPath()), config_media_path)
     try:
         container = self.context.restrictedTraverse(safe_utf8(media_path))
     except:
         # try to create media folder
         container = nav_root
         for f_id in config_media_path.split('/'):
             if not f_id:
                 continue
             if not hasattr(container, f_id):
                 container = createContentInContainer(
                     container, 'Folder', id=f_id, title=f_id,
                     exclude_from_nav=True, checkConstraints=False)
             else:
                 container = container[f_id]
     if container is None:
         container = aq_inner(self.context)
         while not IFolderish.providedBy(container):
             container = aq_parent(container)
     return container
Beispiel #13
0
 def displayMailTab(self):
     # Cannot mail into the portal root
     if self.context.restrictedTraverse(
             '@@plone_context_state').is_portal_root():
         return False
     return IFolderish.providedBy(self.context) and \
         _checkPermission(AddPortalContent, self.context)
Beispiel #14
0
    def export(self, folder, recursive=False):
        """
        Export content items.

        Possible to do recursively nesting into the children.

        :return: list of dictionaries
        """

        from plone.dexterity.content import Container
        from plone.dexterity.content import Item
        array = []
        for obj in folder.listFolderContents():
            # import pdb; pdb.set_trace()
            if isinstance(obj,Container) or isinstance(obj, Item):
                data = self.grabDexterityData(obj)
            else:
                data = self.grabArchetypesData(obj)
            data.update(self.grabAttributes(obj))

            if recursive:
                if IFolderish.providedBy(obj):
                    data["children"] = self.export(obj, True)

            array.append(data)

        return array
Beispiel #15
0
 def can_configure(self):
     """Check if folderview can be configured on context"""
     context = self.context
     if not IFolderish.providedBy(context):
         return False
     already_activated = self.isFolderViewActivated()
     return not already_activated
def recurse(tree, report_file):
    """ Walk through all the content on a Plone site """
    print 'Checking %s' % tree.getId()
    for id, child in tree.contentItems():
	report_objects_with_broken_blobs(child, report_file)
        if IFolderish.providedBy(child):
            recurse(child, report_file)
Beispiel #17
0
 def _walk(self, obj, level=-1):
     yield self._getInfo(obj)
     if level != 0 and (IFolderish.providedBy(obj) \
                    or IBaseFolder.providedBy(obj)):
         for v in obj.contentValues():
             for i in self._walk(v, level - 1):
                 yield i
    def update(self):
        super(LogoViewlet, self).update()
        context = aq_inner(self.context)
        registry = getUtility(IRegistry)
        portal = self.portal_state.portal()
        bprops = portal.restrictedTraverse('base_properties', None)
        title = None
        logo_id = registry.get('collective.folderlogo.logo_id', u'logo')
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        folders = [folder for folder in aq_chain(context) if IFolderish.providedBy(folder)]
        logos = []
        for folder in folders:
            path = '/'.join(folder.getPhysicalPath())
            brains = catalog(
                path=dict(query=path, depth=1),
                id=logo_id,
                object_provides=IATImage.__identifier__)
            if len(brains) != 0:
                logos.append(brains[0])
        if len(logos) != 0:
            logoName = logo_id
            title = logos[0].Title
            portal = aq_parent(logos[0].getObject())
        elif bprops is not None:
            logoName = bprops.logoName
        else:
            logoName = 'logo.jpg'
        self.logo_tag = portal.restrictedTraverse(str(logoName)).tag()

        self.portal_title = title or self.portal_state.portal_title()
Beispiel #19
0
    def __call__(self):
        """Return the rendered contents of the viewlet manager specified."""
        manager = self.data.get('manager')
        viewName = self.data.get('view', None)
        section = self.data.get('section', 'body')
        viewlet = self.data.get('viewlet', None)

        view = findView(self, viewName)

        if not IFolderish.providedBy(self.context):
            self.context = self.context.aq_parent

        managerObj = queryMultiAdapter(
            (self.context, self.request, view),
            IViewletManager,
            name=manager
        )
        managerObj.update()

        obj_to_render = managerObj

        if viewlet:
            provided_viewlets = [i.__name__ for i in managerObj.viewlets]
            if viewlet not in provided_viewlets:
                mgr_name = managerObj.__name__
                msg = 'Viewlet %s is not provided by %s' % (viewlet,
                                                            mgr_name)
                raise ValueError(msg)
            obj_to_render = [i for i in managerObj.viewlets
                             if i.__name__ == viewlet][0]

        if section == 'head':
            return u"<html><head>%s</head></html>" % obj_to_render.render()
        else:
            return u"<html><body>%s</body></html>" % obj_to_render.render()
def list_content(content, callback):
    """Recursively list CMF content out of the given one. ``callback``
    is called every thousand items after a commit.
    """

    def recurse(content):
        for child in content.contentValues():
            if IFolderish.providedBy(child):
                for grandchild in recurse(child):
                    yield grandchild
            yield child

    count = 0
    total = 0
    if IFolderish.providedBy(content):
        for child in recurse(content):
            yield child
            count += 1
            total += 1
            if count > 200:
                logger.info('{0} items indexed'.format(total))
                transaction.commit()
                content._p_jar.cacheGC()
                callback()
                count = 0
        yield content
    elif IContentish.providedBy(content):
        yield content
Beispiel #21
0
def recurse(tree):
    """ Walk through all the content on a Plone site """
    for id, child in tree.contentItems():
        remove_blobs(child)

        if IFolderish.providedBy(child):
            recurse(child)
 def navStrategy(self):
     context = aq_inner(self.context)
     if IFolderish.providedBy(context):
         root = '/'.join(context.getPhysicalPath())
     else:
         parent = context.__parent__
         root = '/'.join(parent.getPhysicalPath())
     query = {
         'path': root,
         'review_state': 'published',
         'portal_type': 'meetshaus.jmscontent.contentpage',
         'sort_order': 'getObjPositionInParent'
     }
     root_obj = context.unrestrictedTraverse(root)
     strategy = DefaultNavtreeStrategy(root_obj)
     strategy.rootPath = '/'.join(root_obj.getPhysicalPath())
     strategy.showAllParents = False
     strategy.bottomLevel = 999
     tree = buildFolderTree(root_obj, root_obj, query, strategy=strategy)
     items = []
     for c in tree['children']:
         item = {}
         item['item'] = c['item']
         item['children'] = c.get('children', '')
         item['itemid'] = c['normalized_id']
         item_id = c['normalized_id']
         if item_id == context.getId():
             item['class'] = 'active'
         else:
             item['class'] = ''
         items.append(item)
     return items
Beispiel #23
0
    def getBanners(self):
        """
        Returns a list of objects that provide ICarouselBanner.
        """

        banner_brains = []
        if IFolderish.providedBy(self.context):
            catalog = getToolByName(self.context, "portal_catalog")
            banner_brains = catalog.searchResults(
                {
                    "path": "/".join(self.context.getPhysicalPath()),
                    "object_provides": ICarouselBanner.__identifier__,
                    "sort_on": "getObjPositionInParent",
                }
            )
        elif IATTopic.providedBy(self.context):
            banner_brains = self.context.queryCatalog()

        banner_objects = [b.getObject() for b in banner_brains]
        banner_objects = [b for b in banner_objects if ICarouselBanner.providedBy(b)]

        # Shuffle carousel images if needde
        if self.getSettings().random_order:
            shuffle(banner_objects)

        return banner_objects
 def getSections(self):
     portal = self.portal_state.portal()
     items = portal.getFolderContents()
     for brain in items:
         obj = brain.getObject()
         if IFolderish.providedBy(obj):
             yield obj
Beispiel #25
0
    def recurse_transition(
        self, objs, comment, publication_dates, include_children=False
    ):
        for obj in objs:
            if publication_dates:
                deserializer = queryMultiAdapter(
                    (obj, self.request), IDeserializeFromJson
                )
                deserializer(data=publication_dates)

            if obj.EffectiveDate() == "None":
                obj.setEffectiveDate(DateTime())
                obj.reindexObject()
            if not self.wftool.getWorkflowsFor(obj):
                continue
            try:
                self.wftool.doActionFor(obj, self.transition, comment=comment)
            except WorkflowException as e:
                if not self.is_same_state(obj):
                    # this is a real error
                    raise e
            if include_children and IFolderish.providedBy(obj):
                self.recurse_transition(
                    obj.objectValues(), comment, publication_dates, include_children
                )
def getBreadcrumbs(self, path=None):
    """Patch for displaying plone root in tiny mce breadcrumbs for
    browsing language neutral folders located next to language folders.
    """
    result = []

    root = getUtility(ISiteRoot)
    root_url = root.absolute_url()

    if path is not None:
        root_abs_url = root.absolute_url()
        path = path.replace(root_abs_url, '', 1)
        path = path.strip('/')
        root = aq_inner(root.restrictedTraverse(path))

    relative = aq_inner(self.context).getPhysicalPath()[len(
        root.getPhysicalPath()):]
    if path is None:
        # Add siteroot
        result.append({'title': 'Root',
            'url': '/'.join(root.getPhysicalPath())})

    for i in range(len(relative)):
        now = relative[:i + 1]
        obj = aq_inner(root.restrictedTraverse(now))

        if IFolderish.providedBy(obj):
            if not now[-1] == 'talkback':
                result.append({'title': obj.title_or_id(),
                    'url': root_url + '/' + '/'.join(now)})
    return result
def get_editor_language(request):
    """ Get editor language override
    """

    cached = getattr(request, "_cached_admin_language", None)
    if cached:
        return cached

    alwaysTranslate = getattr(request, "alwaysTranslate", None)
    if alwaysTranslate:
        return None

    context = find_context(request)

    # Filter out CSS and other non-sense
    # IFolderish check includes site root
    if not (IContentish.providedBy(context) or IFolderish.providedBy(context)):
        # Early terminate
        return None

    # Check if we are the editor
    portal_state = getMultiAdapter((context, request),
                                                    name="plone_portal_state")
    if portal_state.anonymous():
        # Anon visitor, normal language ->
        request.alwaysTranslate = True
        return None

    language = 'en'

    # english for all authenticated users
    request._cached_admin_language = language
    return language
def patched_recurse_transition(self,
                               objs,
                               comment,
                               publication_dates,
                               include_children=False):
    logger.info('called plone.restapi patch')
    transition_id = self.transition
    pprops = getToolByName(self, 'portal_properties')
    sprops = pprops.site_properties
    transitions_or_states = sprops.getProperty(
        'pub_date_set_on_workflow_transition_or_state', ['publish'])
    for obj in objs:
        if publication_dates:
            deserializer = queryMultiAdapter((obj, self.request),
                                             IDeserializeFromJson)
            deserializer(data=publication_dates)

        # set effective date only if transition is publish and we have no date
        if obj.EffectiveDate() == "None" and transition_id in \
                transitions_or_states:
            obj.setEffectiveDate(DateTime())

        self.wftool.doActionFor(obj, transition_id, comment=comment)
        if include_children and IFolderish.providedBy(obj):
            self.recurse_transition(obj.objectValues(), comment,
                                    publication_dates, include_children)
Beispiel #29
0
    def getBanners(self):
        """
        Returns a list of objects that provide ICarouselBanner.
        """

        banner_brains = []
        if IFolderish.providedBy(self.context):
            catalog = getToolByName(self.context, 'portal_catalog')
            banner_brains = catalog.searchResults({
                'path':
                '/'.join(self.context.getPhysicalPath()),
                'object_provides':
                ICarouselBanner.__identifier__,
                'sort_on':
                'getObjPositionInParent',
            })
        elif IATTopic.providedBy(self.context):
            banner_brains = self.context.queryCatalog()

        banner_objects = [b.getObject() for b in banner_brains]
        banner_objects = [
            b for b in banner_objects if ICarouselBanner.providedBy(b)
        ]

        # Shuffle carousel images if needde
        if self.getSettings().random_order:
            shuffle(banner_objects)

        return banner_objects
Beispiel #30
0
    def getBreadcrumbs(self, path=None):
        """ Get breadcrumbs """
        result = []
        root_url = getNavigationRoot(self.obj)
        root = aq_inner(self.obj.restrictedTraverse(root_url))
        root_url = root.absolute_url()

        if path is not None:
            root_abs_url = root.absolute_url()
            path = path.replace(root_abs_url, '', 1)
            path = path.strip('/')
            root = aq_inner(root.restrictedTraverse(path))

        relative = aq_inner(self.obj).getPhysicalPath()[len(root.getPhysicalPath()):]
        if path is None:
            # Add siteroot
            result.append({'title': root.title_or_id(),
                           'url': '/'.join(root.getPhysicalPath())})

        for i in range(len(relative)):
            now = relative[:i + 1]
            obj = aq_inner(root.restrictedTraverse(now))

            if IFolderish.providedBy(obj):
                if not now[-1] == 'talkback':
                    result.append({'title': obj.title_or_id(),
                                   'url': root_url + '/' + '/'.join(now)})
        return result
    def get_modulistica_data(self, context=None):
        if context is None:
            context = self.context
        res = []
        for child in context.listFolderContents():
            if child.portal_type == "Document" and child.getId(
            ) == "multimedia":
                continue

            serializer = queryMultiAdapter((child, self.request),
                                           ISerializeToJsonSummary)
            data = serializer()
            if child.portal_type == "Document":
                for schema in iterSchemata(context):
                    for name, field in getFields(schema).items():
                        if name not in ["blocks", "blocks_layout"]:
                            continue

                        # serialize the field
                        serializer = queryMultiAdapter(
                            (field, child, self.request), IFieldSerializer)
                        value = serializer()
                        data[json_compatible(name)] = value
            if IFolderish.providedBy(child):
                children = [
                    x for x in self.get_modulistica_data(context=child)
                    if x.get("@type", "") not in
                    ["Document", "CartellaModulistica"]
                ]
                if children:
                    data["items"] = children
            res.append(data)
        return res
Beispiel #32
0
 def getContainer(self):
     """ Get the item for which we perform the listing
     """
     context = self.context.aq_inner
     if IFolderish.providedBy(context):
         return context
     else:
         return context.aq_parent
Beispiel #33
0
 def getContainer(self):
     """ Get the item for which we perform the listing
     """
     context = self.context.aq_inner
     if IFolderish.providedBy(context):
         return context
     else:
         return context.aq_parent
def onObjectModified(ob, event):
    """Reindex in container"""
    parent = getattr(ob, 'aq_parent', None)
    if parent is None:
        return

    if IFolderish.providedBy(parent):
        IFolderContents(parent).index(ob)
Beispiel #35
0
def doRecurse(location):
    for xid, child in location.contentItems():
        # do something !
        logger.info('id:' + str(xid))
        logger.info('child:' + str(child.portal_type))
        child.reindexObject()
        if IFolderish.providedBy(child):
            doRecurse(child)
Beispiel #36
0
 def can_configure(self):
     """
     """
     context = self.context
     if not IFolderish.providedBy(context):
         return False
     alreadyActivated = self.isFolderProfActivated()
     return (not alreadyActivated)
Beispiel #37
0
 def render(self):
     self.request.response.setHeader('Content-Type', 'application/json')
     j = {}
     if self.folder and IFolderish.providedBy(self.folder):
         for id in FOLDER_IDS:
             if hasattr(self.folder, id):
                 j[id] = self.get_folder_contents(id)
     return json.dumps(j, sort_keys=True, indent=4)
 def render(self):
     self.request.response.setHeader('Content-Type', 'application/json')
     j = {}
     if self.folder and IFolderish.providedBy(self.folder):
         for id in FOLDER_IDS:
             if hasattr(self.folder, id):
                 j[id] = self.get_folder_contents(id)
     return json.dumps(j, sort_keys=True, indent=4)
 def enabled(self):
     """Check if context is folderish or the default view of a folderish."""
     context = self.context
     context_state = api.content.get_view(
         'plone_context_state', context, self.request)
     if context_state.is_default_page():
         context = context.aq_parent
     return IFolderish.providedBy(context)
    def traverse(self, name, ignored):
        # Populate translation info
        self.info['target_language'] = ILanguage(self.context).get_language()

        catalog = getToolByName(self.context, 'portal_catalog')
        # Search source object using unrestricted API,
        # because user may be anonymous during traverse.
        brains = catalog.unrestrictedSearchResults(UID=name)
        if len(brains) != 1:
            raise TraversalError(self.context, name)
        source = brains[0]._unrestrictedGetObject()

        self.info['source_language'] = ILanguage(source).get_language()
        self.info['portal_type'] = source.portal_type
        self.info['tg'] = ITG(source)

        # If source has already been translated to this language, just redirect
        for brain in catalog.unrestrictedSearchResults(
                TranslationGroup=self.info['tg'],
                Language=self.info['target_language']):
            self.request.response.redirect(brain.getURL())
            return u''

        # XXX: register this adapter on dx container and a second one for AT
        if not IDexterityContent.providedBy(source):
            # we are not on DX content, assume AT
            baseUrl = self.context.absolute_url()
            url = '%s/@@add_at_translation?type=%s' % (baseUrl, name)
            return self.request.response.redirect(url)

        # set the self.context to the place where it should be stored
        if not IFolderish.providedBy(self.context):
            self.context = self.context.__parent__

        # get the type information
        ttool = getToolByName(self.context, 'portal_types')
        ti = ttool.getTypeInfo(self.info['portal_type'])

        if ti is None:
            logger.error('No type information found for {0}'.format(
                self.info['portal_type']))
            raise TraversalError(self.context, name)

        registry = getUtility(IRegistry)
        settings = registry.forInterface(IMultiLanguageExtraOptionsSchema)

        if not settings.redirect_babel_view:
            add_view = None
        else:
            add_view = queryMultiAdapter((self.context, self.request, ti),
                                         name='babel_view')
        if add_view is None:
            add_view = queryMultiAdapter((self.context, self.request, ti))
            if add_view is not None:
                raise TraversalError(self.context, name)

        add_view.__name__ = ti.factory
        return add_view.__of__(self.context)
 def get_folder_contents(self, id):
     """Return list of content objects inside the object which id as a list
     of dictionaries.
     """
     if IFolderish.providedBy(self.folder[id]):
         results = self.folder[id].listFolderContents()
     else:
         results = []
     return self.serialize(results)
Beispiel #42
0
 def get_folder_contents(self, id):
     """Return list of content objects inside the object which id as a list
     of dictionaries.
     """
     if IFolderish.providedBy(self.folder[id]):
         results = self.folder[id].listFolderContents()
     else:
         results = []
     return self.serialize(results)