def __call__(self):
     criteria_holder = self._criteriaHolder
     criterion = None
     try:
         criterion = getCollectionLinkCriterion(criteria_holder)
     except NoCollectionWidgetDefinedException:
         pass
     if criterion:
         # if we have the collection UID in the REQUEST, return self.index()
         # so we avoid the portal_catalog search for collection
         collectionUID = self.context.REQUEST.form.get('{0}[]'.format(criterion.__name__))
         if collectionUID or not criterion.default:
             return self.index()
         if not self.request['HTTP_REFERER'].endswith('configure_faceted.html') and \
            not self.request['URL'].endswith('folder_contents') and \
            not self.request.get('no_redirect', '0') == '1':
             catalog = api.portal.get_tool('portal_catalog')
             brains = catalog(UID=criterion.default)
             if brains:
                 collection = brains[0].getObject()
                 container = collection.aq_inner.aq_parent
                 if not container == criteria_holder and \
                    IFacetedNavigable.providedBy(container):
                     self.request.RESPONSE.redirect(container.absolute_url())
                     return ''
     return self.index()
    def __init__(self, context, request):
        self.context = context
        self.request = request

        #self.metadata_display = dict(getToolByName(context, 'portal_atct').getMetadataDisplay().items())
        vocab = getUtility(IVocabularyFactory, 'collective.listingviews.MetadataVocabulary')(context)
        self.metadata_display = {item.value: item.title for item in vocab}
        #TODO item.title here is the title for the filter on it. We want the one before the filter was added

        plone_util = getMultiAdapter((self.context, self.request), name="plone")
        self.filters = dict(
            localshort = lambda item, value: plone_util.toLocalizedTime(value, long_format=0),
            locallong = lambda item, value: plone_util.toLocalizedTime(value, long_format=1),
            tolink = lambda item, value: '<a href="%s">%s</a>'%(item.getURL(), value)
        )

        #Tricky part to work out the listing view thats been picked
        if IFacetedLayout is not None and \
            (IFacetedSearchMode.providedBy(self.context) or IFacetedNavigable.providedBy(self.context)):
            # Case: It's being used from facetednavigation
            self.set_listing_view(getListingNameFromView(IFacetedLayout(self.context).layout))
        else:
            # Case: It's being used from a normal display menu view
            view_name = request.getURL().split('/')[-1]
            self.set_listing_view(getListingNameFromView(view_name))
 def _criteriaHolder(self):
     '''Get the element the criteria are defined on.  This will look up parents until
        a folder providing IFacetedNavigable is found.'''
     parent = self.context
     # look up parents until we found the criteria holder or we reach the 'Plone Site'
     while parent and not parent.portal_type == 'Plone Site':
         if IFacetedNavigable.providedBy(parent):
             return parent
         parent = aq_parent(aq_inner(parent))
def _get_criterion(faceted_context, criterion_type):
    """Return the given criterion_type instance of a
       context with a faceted navigation/search view on it."""
    if not IFacetedNavigable.providedBy(faceted_context):
        raise NoFacetedViewDefinedException(NO_FACETED_EXCEPTION_MSG)

    criteria = ICriteria(faceted_context).criteria
    for criterion in criteria:
        if criterion.widget == criterion_type:
            return criterion
Beispiel #5
0
 def get_context(self, faceted_context):
     ignored_types = ("ClassificationSubfolder", "ClassificationFolder")
     # look up parents until we found the criteria holder or we reach the 'Plone Site'
     while faceted_context and not faceted_context.portal_type == 'Plone Site':
         if IFacetedNavigable.providedBy(
                 faceted_context
         ) and faceted_context.portal_type not in ignored_types:
             return faceted_context
         faceted_context = aq_parent(aq_inner(faceted_context))
     return faceted_context
def _updateDefaultCollectionFor(folderObj, default_uid):
    """Use p_default_uid as the default collection selected
       for the CollectionWidget used on p_folderObj."""
    # folder should be a facetednav
    if not IFacetedNavigable.providedBy(folderObj):
        raise NoFacetedViewDefinedException(NO_FACETED_EXCEPTION_MSG)

    criterion = getCollectionLinkCriterion(folderObj)
    # use ICriteria.edit so change is persisted
    ICriteria(folderObj).edit(criterion.__name__, **{'default': default_uid})
    # notify that settings changed
    notify(FacetedGlobalSettingsChangedEvent(folderObj))
Beispiel #7
0
def _get_criterion_by_attr(faceted_context, attr_name, value_to_match):
    """
    """
    if not IFacetedNavigable.providedBy(faceted_context):
        raise NoFacetedViewDefinedException(NO_FACETED_EXCEPTION_MSG)

    criterions = ICriteria(faceted_context)
    for criterion in criterions.values():
        if not hasattr(criterion, attr_name):
            continue
        else:
            attr = getattr(criterion, attr_name)
            value = hasattr(attr, '__call__') and attr() or attr
            if value == value_to_match:
                return criterion
    def getMenuItems(self, obj, request):
        """ Safely get menu items
        """
        res = super(FacetedDisplayMenu, self).getMenuItems(obj, request)
        if not IFacetedNavigable.providedBy(obj):
            return res

        faceted_adapter = queryAdapter(obj, IFacetedLayout)
        if not faceted_adapter:
            return res

        new = []
        template = {
            'submenu': None,
            'description': '',
            'extra': {
                'separator': None,
                'id': '',
                'class': ''
            },
            'selected': False,
            'action': '',
            'title': '',
            'icon': None
        }

        current = faceted_adapter.layout
        for name, label in faceted_adapter.layouts:
            layout = template.copy()
            layout['extra'] = template['extra'].copy()
            layout['extra']['id'] = name
            layout['title'] = label
            layout['action'] = '%s/@@faceted_layout?layout=%s' % (
                obj.absolute_url(), name)

            if (name == current):
                layout['selected'] = True
                layout['extra']['class'] = 'actionMenuSelected'

            new.append(layout)

        return new
    def getMenuItems(self, obj, request):
        """ Safely get menu items
        """
        res = super(FacetedDisplayMenu, self).getMenuItems(obj, request)
        if not IFacetedNavigable.providedBy(obj):
            return res

        faceted_adapter = queryAdapter(obj, IFacetedLayout)
        if not faceted_adapter:
            return res

        new = []
        template = {
            'submenu': None,
            'description': '',
            'extra': {
                'separator': None,
                'id': '',
                'class': ''},
            'selected': False,
            'action': '',
            'title': '',
            'icon': None
        }

        current = faceted_adapter.layout
        for name, label in faceted_adapter.layouts:
            layout = template.copy()
            layout['extra'] = template['extra'].copy()
            layout['extra']['id'] = name
            layout['title'] = label
            layout['action'] = '%s/@@faceted_layout?layout=%s' % (
                obj.absolute_url(), name)

            if name == current:
                layout['selected'] = True
                layout['extra']['class'] = 'actionMenuSelected'

            new.append(layout)

        return new
Beispiel #10
0
def _enableFacetedDashboardFor(obj,
                               xmlpath=None,
                               show_left_column=True,
                               default_UID=None,
                               enable_faceted=True,
                               update_layout=True):
    """Enable a faceted view on obj and import a
       specific xml if given p_xmlpath."""
    # already a faceted?
    if enable_faceted and IFacetedNavigable.providedBy(obj):
        logger.error("Faceted navigation is already enabled for '%s'" %
                     '/'.join(obj.getPhysicalPath()))
        return

    # do not go further if xmlpath does not exist
    if xmlpath and not path.exists(xmlpath):
        raise Exception("Specified xml file '%s' doesn't exist" % xmlpath)
    # .enable() here under will redirect to enabled faceted
    # we cancel this, safe previous RESPONSE status and location
    response_status = obj.REQUEST.RESPONSE.getStatus()
    response_location = obj.REQUEST.RESPONSE.getHeader('location')
    if enable_faceted:
        obj.unrestrictedTraverse('@@faceted_subtyper').enable()

    if update_layout:
        # use correct layout in the faceted
        IFacetedLayout(obj).update_layout('faceted-table-items')
    # show the left portlets
    if show_left_column and IHidePloneLeftColumn.providedBy(obj):
        noLongerProvides(obj, IHidePloneLeftColumn)
    # import configuration
    if xmlpath:
        obj.unrestrictedTraverse('@@faceted_exportimport').import_xml(
            import_file=open(xmlpath))
    # define default collection UID
    if default_UID:
        _updateDefaultCollectionFor(obj, default_UID)
    obj.reindexObject()
    obj.REQUEST.RESPONSE.status = response_status
    obj.REQUEST.RESPONSE.setHeader('location', response_location or '')
    def __init__(self, context, request):
        self.context = context
        self.request = request

        #TODO: this won't work with p.a.collections
        self.metadata_display = dict(getToolByName(context, 'portal_atct').getMetadataDisplay().items())

        plone_util = getMultiAdapter((self.context, self.request), name="plone")
        self.filters = dict(
            localshort = lambda item, value: plone_util.toLocalizedTime(value, long_format=0),
            locallong = lambda item, value: plone_util.toLocalizedTime(value, long_format=1),
            tolink = lambda item, value: '<a href="%s">%s</a>'%(item.getURL(), value)
        )

        #Tricky part to work out the listing view thats been picked
        if IFacetedLayout is not None and \
            (IFacetedSearchMode.providedBy(self.context) or IFacetedNavigable.providedBy(self.context)):
            # Case: It's being used from facetednavigation
            self.set_listing_view(getListingNameFromView(IFacetedLayout(self.context).layout))
        else:
            # Case: It's being used from a normal display menu view
            view_name = request.getURL().split('/')[-1]
            self.set_listing_view(getListingNameFromView(view_name))
    def getMenuItems(self, obj, request):
        """ Safely get menu items
        """
        res = super(FacetedDisplayMenu, self).getMenuItems(obj, request)
        if not IFacetedNavigable.providedBy(obj):
            return res

        faceted_adapter = queryAdapter(obj, IFacetedLayout)
        if not faceted_adapter:
            return res

        new = []
        template = {
            "submenu": None,
            "description": "",
            "extra": {"separator": None, "id": "", "class": ""},
            "selected": False,
            "action": "",
            "title": "",
            "icon": None,
        }

        current = faceted_adapter.layout
        for name, label in faceted_adapter.layouts:
            layout = template.copy()
            layout["extra"] = template["extra"].copy()
            layout["extra"]["id"] = name
            layout["title"] = label
            layout["action"] = "@@faceted_layout?layout=%s" % name

            if name == current:
                layout["selected"] = True
                layout["extra"]["class"] = "actionMenuSelected"

            new.append(layout)

        return new
Beispiel #13
0
def getDashboardQueryResult(faceted_context):
    """
    Return dashboard selelected items of a faceted query.
    """
    if not IFacetedNavigable.providedBy(faceted_context):
        raise NoFacetedViewDefinedException(NO_FACETED_EXCEPTION_MSG)

    request = faceted_context.REQUEST
    uids = request.form.get('uids', '')
    faceted_query = request.form.get('facetedQuery', None)

    brains = []
    # maybe we have a facetedQuery? aka the meeting view was filtered and we want to print this result
    if not uids:
        if faceted_query:
            # put the facetedQuery criteria into the REQUEST.form
            for k, v in json.JSONDecoder().decode(faceted_query).items():
                # we receive list of elements, if we have only one elements, remove it from the list
                if isinstance(v, list) and len(v) == 1:
                    v = v[0]
                request.form['{0}[]'.format(k)] = v
        faceted = faceted_context.restrictedTraverse('@@faceted_query')
        brains = faceted.query(batch=False)
    # if we have uids, let 'brains' be directly available in the template context too
    # brains could already fetched, if it is the case, use it, get it otherwise
    elif uids:
        uids = uids.split(',')
        catalog = api.portal.get_tool('portal_catalog')
        brains = catalog(UID=uids)

        # we need to sort found brains according to uids
        def getKey(item):
            return uids.index(item.UID)

        brains = sorted(brains, key=getKey)
    return brains
Beispiel #14
0
    def bodyClass(self, template, view):
        """
        Extend Plone to add a CSS class on <body> based on :
        1. the 1st level folder of the current context :
         - 'section-theme1' or 'section-theme2' or ... for portal tabs folders
           based on their positions
         - section-notheme if not in a portal tab folder
        2. the citizen user
        3. minisite
        4. homepage
        5. the portal_type of the collection (if any)
        6. the expiration of the content
        7. the layout used for faceted navigations
        """
        context = self.context

        # Get default body classes
        body_class = base.LayoutPolicy.bodyClass(self, template, view)

        # Get 1st level folders appearing in navigation
        portal_catalog = api.portal.get_tool(name='portal_catalog')
        navtreeProps = api.portal.get_tool(name='portal_properties').navtree_properties
        navigation_root = api.portal.get_navigation_root(context)
        queryDict = {}
        queryDict['path'] = {'query': '/'.join(navigation_root.getPhysicalPath()), 'depth': 1}
        if navtreeProps.enable_wf_state_filtering:
            queryDict['review_state'] = navtreeProps.wf_states_to_show
        queryDict['sort_on'] = 'getObjPositionInParent'
        queryDict['portal_type'] = 'Folder'
        queryDict['is_default_page'] = False
        brains = portal_catalog(queryDict)
        res = [b for b in brains if b.id not in navtreeProps.idsNotToList]

        # Get the first level of the current
        actual_url_path = '/'.join(context.getPhysicalPath())
        # Check if we are in a theme and check if we are in the right one (position)
        index = 1
        inTheme = False
        for brain in res:
            # checking startswith is not enough
            # see ticket #1227 :
            # if theme1 id is "theme" and theme2 id is "theme2", while being in the
            # theme2, it starts with 'theme' so it returns True to checking if being in theme 1...
            brainPath = brain.getPath()
            if actual_url_path.startswith(brainPath):
                brainPathLen = len(brainPath)
                if len(actual_url_path) == brainPathLen \
                   or actual_url_path[brainPathLen:brainPathLen + 1] == '/':
                    inTheme = True
                    body_class += ' section-theme%s' % index
            index += 1

        if not inTheme:
            body_class += ' section-notheme'

        header_class = api.portal.get_registry_record(
            'cpskin.core.interfaces.ICPSkinSettings.header_class'
        )
        if header_class:
            body_class += ' {0}'.format(header_class)

        navigation_class = api.portal.get_registry_record(
            'cpskin.core.interfaces.ICPSkinSettings.navigation_class'
        )
        if navigation_class:
            body_class += ' {0}'.format(navigation_class)

        content_columns_class = api.portal.get_registry_record(
            'cpskin.core.interfaces.ICPSkinSettings.columns_class'
        )
        if content_columns_class:
            body_class += ' {0}'.format(content_columns_class)

        footer_class = api.portal.get_registry_record(
            'cpskin.core.interfaces.ICPSkinSettings.footer_class'
        )
        if footer_class:
            body_class += ' {0}'.format(footer_class)

        minisite = self.request.get('cpskin_minisite', None)
        if minisite:
            if minisite.is_in_minisite_mode:
                body_class += ' in-minisite in-minisite-out-portal'
            elif minisite.is_in_portal_mode:
                body_class += ' in-minisite in-minisite-in-portal'

        if is_main_homepage(context):
            body_class += ' main-homepage'

        user = api.user.get_current()
        if is_citizen(user):
            body_class += ' user-citizen'

        if context.portal_type == 'Collection':
            normalizer = queryUtility(IIDNormalizer).normalize
            query = context.query
            portal_types = []
            if query is not None:
                for criteria in query:
                    if criteria.get('i') == 'portal_type':
                        portal_types = criteria.get('v')
            for portal_type in portal_types:
                body_class += ' collection-%s' % normalizer(portal_type)

        expiration_date = context.expiration_date
        if expiration_date and expiration_date < DateTime():
            body_class += ' expired-content'

        if IFacetedNavigable.providedBy(context):
            faceted_adapter = queryAdapter(context, IFacetedLayout)
            if faceted_adapter:
                body_class += ' %s' % faceted_adapter.layout

        return body_class
Beispiel #15
0
 def faceted_enabled(self):
     return IFacetedNavigable.providedBy(self.context)
 def get_context(self, faceted_context):
     while not IFacetedNavigable.providedBy(faceted_context) and \
             not faceted_context.meta_type == 'Plone Site':
         return self.get_context(faceted_context.aq_inner.aq_parent)
     return faceted_context
Beispiel #17
0
 def faceted_enabled(self):
     return IFacetedNavigable.providedBy(self.context)