def can_manage_portlets(self):
     context = self._context()
     if not ILocalPortletAssignable.providedBy(context):
         return False
     mtool = getToolByName(context, 'portal_membership')
     return mtool.checkPermission("Portlets: Manage portlets",
                                  context) and self.isinmanagerrole()
Esempio n. 2
0
    def get_portlets(self):
        """If there is portlets then extract its.
        """

        self.doc = minidom.Document()
        self.portlet_schemata = dict([(
            iface,
            name,
        ) for name, iface in getUtilitiesFor(IPortletTypeInterface)])  # noqa
        self.portlet_managers = list(getUtilitiesFor(IPortletManager))
        if ILocalPortletAssignable.providedBy(self.context):
            data = None

            root = self.doc.createElement('portlets')

            for elem in self.exportAssignments(self.context):
                root.appendChild(elem)
            for elem in self.exportBlacklists(self.context):
                root.appendChild(elem)
            if root.hasChildNodes():
                self.doc.appendChild(root)
                data = self.doc.toprettyxml(indent='  ', encoding='utf-8')
                self.doc.unlink()

            if data:
                self['portlets'] = data
Esempio n. 3
0
 def can_manage_portlets(self):
     context = self._context()
     ftool = getToolByName(context, 'portal_factory')
     if ftool.isTemporary(context) or \
         not ILocalPortletAssignable.providedBy(context):
         return False
     mtool = getToolByName(context, 'portal_membership')
     return mtool.checkPermission("Portlets: Manage portlets", context)
Esempio n. 4
0
 def can_manage_portlets(self):
     context = self._context()
     ftool = getToolByName(context, 'portal_factory')
     if ftool.isTemporary(context) or \
         not ILocalPortletAssignable.providedBy(context):
         return False
     mtool = getToolByName(context, 'portal_membership')
     return mtool.checkPermission("Portlets: Manage portlets", context)
Esempio n. 5
0
 def available(self):
     secman = getSecurityManager()
     has_manage_portlets_permission = secman.checkPermission(
         'Portlets: Manage portlets', self.context)
     if not has_manage_portlets_permission:
         return False
     else:
         return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 6
0
 def available(self):
     secman = getSecurityManager()
     has_manage_panels_permission = secman.checkPermission(
         self.MANAGE_SETTINGS_PERMISSION, self.context)
     if not has_manage_panels_permission:
         return False
     else:
         # If context can have portlets, it can also have panels.
         return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 7
0
 def available(self):
     secman = getSecurityManager()
     has_manage_portlets_permission = secman.checkPermission(
         'Portlets: Manage portlets',
         self.context
     )
     if not has_manage_portlets_permission:
         return False
     else:
         return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 8
0
def migrate_portlets(src_obj, dst_obj):
    """Copy portlets for all available portletmanagers from one object
    to another.
    Also takes blocked portlet settings into account, keeps hidden portlets
    hidden and skips broken assignments.
    """
    if not ILocalPortletAssignable.providedBy(src_obj) or \
       not ILocalPortletAssignable.providedBy(dst_obj):
        return

    # also take custom portlet managers into account
    managers = [
        reg.name for reg in getSiteManager().registeredUtilities()
        if reg.provided == IPortletManager
    ]
    # faster, but no custom managers
    # managers = [u'plone.leftcolumn', u'plone.rightcolumn']

    # copy information which categories are hidden for which manager
    blacklist_status = IAnnotations(src_obj).get(CONTEXT_BLACKLIST_STATUS_KEY,
                                                 None)
    if blacklist_status is not None:
        IAnnotations(dst_obj)[CONTEXT_BLACKLIST_STATUS_KEY] = \
            deepcopy(blacklist_status)

    # copy all portlet assignments (visibilty is stored as annotation
    # on the assignments and gets copied here too)
    for manager in managers:
        column = getUtility(IPortletManager, manager)
        mappings = getMultiAdapter((src_obj, column),
                                   IPortletAssignmentMapping)
        for key, assignment in mappings.items():
            # skip possibly broken portlets here
            if not hasattr(assignment, '__Broken_state__'):
                add_portlet(dst_obj, assignment, key, manager)
            else:
                logger.warn(u'skipping broken portlet assignment {0} '
                            'for manager {1}'.format(key, manager))
Esempio n. 9
0
 def available(self):
     # As we don't have the view we need to parse the url to see
     # if its folder_contents
     if 'folder_contents' in self.request.getURL().split('/'):
         return False
     secman = getSecurityManager()
     has_manage_portlets_permission = secman.checkPermission(
         'Portlets: Manage portlets',
         self.context
     )
     if not has_manage_portlets_permission:
         return False
     else:
         return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 10
0
 def _get_text_adapters(self):
     if self.obj.portal_type in self.portal_types or self.portal_types == []:
         adapter = queryAdapter(self.obj, IBulkModifyContentChanger)
         if adapter:
             yield adapter
     if self.portlets and ILocalPortletAssignable.providedBy(self.obj):
         for manager_name in self.managers:
             manager = getUtility(IPortletManager, name=manager_name,
                                  context=self.obj)
             mapping = getMultiAdapter((self.obj, manager),
                                       IPortletAssignmentMapping)
             for ignored, assignment in mapping.items():
                 if isinstance(assignment, StaticAssignment):
                     yield assignment
Esempio n. 11
0
def migrate_portlets(src_obj, dst_obj):
    """Copy portlets for all available portletmanagers from one object
    to another.
    Also takes blocked portlet settings into account, keeps hidden portlets
    hidden and skips broken assignments.
    """
    if not ILocalPortletAssignable.providedBy(src_obj) or \
       not ILocalPortletAssignable.providedBy(dst_obj):
        return

    # also take custom portlet managers into account
    managers = [reg.name for reg in getSiteManager().registeredUtilities()
                if reg.provided == IPortletManager]
    # faster, but no custom managers
    # managers = [u'plone.leftcolumn', u'plone.rightcolumn']

    # copy information which categories are hidden for which manager
    blacklist_status = IAnnotations(src_obj).get(
        CONTEXT_BLACKLIST_STATUS_KEY, None)
    if blacklist_status is not None:
        IAnnotations(dst_obj)[CONTEXT_BLACKLIST_STATUS_KEY] = \
            deepcopy(blacklist_status)

    # copy all portlet assignments (visibilty is stored as annotation
    # on the assignments and gets copied here too)
    for manager in managers:
        column = getUtility(IPortletManager, manager)
        mappings = getMultiAdapter((src_obj, column),
                                   IPortletAssignmentMapping)
        for key, assignment in mappings.items():
            # skip possibly broken portlets here
            if not hasattr(assignment, '__Broken_state__'):
                add_portlet(dst_obj, assignment, key, manager)
            else:
                logger.warn(u'skipping broken portlet assignment {0} '
                            'for manager {1}'.format(key, manager))
Esempio n. 12
0
 def _get_text_adapters(self):
     if self.obj.portal_type in self.portal_types or self.portal_types == []:
         adapter = queryAdapter(self.obj, IBulkModifyContentChanger)
         if adapter:
             yield adapter
     if self.portlets and ILocalPortletAssignable.providedBy(self.obj):
         for manager_name in self.managers:
             manager = getUtility(IPortletManager, name=manager_name,
                                  context=self.obj)
             mapping = getMultiAdapter((self.obj, manager),
                                       IPortletAssignmentMapping)
             for ignored, assignment in mapping.items():
                 adapter = queryAdapter(assignment, IBulkModifyContentChanger)
                 if adapter:
                     yield adapter
Esempio n. 13
0
def remove_portlet_assignments(obj):
    """Remove portlet assignments on object."""
    from plone.portlets.interfaces import ILocalPortletAssignable
    from plone.portlets.interfaces import IPortletAssignmentMapping
    from plone.portlets.interfaces import IPortletManager
    from zope.component import getMultiAdapter
    from zope.component import getUtility
    if not ILocalPortletAssignable.providedBy(obj):
        return
    for name in ('plone.leftcolumn', 'plone.rightcolumn'):
        manager = getUtility(IPortletManager, name=name)
        mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping)
        for i in mapping.keys():
            logger.info('Portlet "{0}" removed'.format(i))
            del mapping[i]
Esempio n. 14
0
def list_portlet_assignments(obj):
    """List all portlet assignments on a given object."""
    if not ILocalPortletAssignable.providedBy(obj):
        return

    print('object: {0}'.format(obj))
    for name in ('plone.leftcolumn', 'plone.rightcolumn'):
        manager = getUtility(IPortletManager, name=name)
        mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping)
        items = list(mapping.items())
        if not items:
            continue

        print('├─ {0}'.format(name))
        for k, v in items:
            print('├─── {0} ({1})'.format(k, v))
Esempio n. 15
0
    def getPortlets(self):
        """Work out which portlets to display, returning a list of dicts
        describing assignments to render.
        """
        manager = self.storage.__name__

        pcontext = IPortletContext(self.context, None)
        if pcontext is None:
            return []

        assignable = ILocalPortletAssignable(self.context, None)
        if assignable is None:
            return []

        annotations = IAnnotations(assignable, None)
        if annotations is None:
            return []

        local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
        if local is None:
            return []

        localManager = local.get(manager, None)
        if localManager is None:
            return []

        assignments = []
        for assignment in localManager.values():
            try:
                settings = IPortletAssignmentSettings(assignment)
            except TypeError:
                # Portlet does not exist any longer
                continue
            if not settings.get('visible', True):
                continue
            assignments.append(assignment)

        return [{
            'category': CONTEXT_CATEGORY,
            'key': pcontext.uid,
            'name': a.__name__,
            'assignment': a
        } for a in assignments]
    def __iter__(self):
        self.portlet_schemata = dict([(
            iface,
            name,
        ) for name, iface in getUtilitiesFor(IPortletTypeInterface)])
        self.portlet_managers = list(getUtilitiesFor(IPortletManager))

        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]

            if not pathkey:
                yield item
                continue

            path = item[pathkey]
            obj = self.context.unrestrictedTraverse(path, None)
            if obj is None:  # path doesn't exist
                yield item
                continue

            if ILocalPortletAssignable.providedBy(obj):
                data = None

                root = self.doc.createElement('portlets')

                for elem in self.exportAssignments(obj):
                    root.appendChild(elem)
                for elem in self.exportBlacklists(obj):
                    root.appendChild(elem)
                if root.hasChildNodes():
                    self.doc.appendChild(root)
                    data = self.doc.toprettyxml(indent='  ', encoding='utf-8')
                    self.doc.unlink()

                if data:
                    item.setdefault(self.fileskey, {})
                    item[self.fileskey]['portlets'] = {
                        'name': '.portlets.xml',
                        'data': data,
                    }
            yield item
    def __iter__(self):

        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]
            fileskey = self.fileskey(*item.keys())[0]

            if not (pathkey and fileskey):
                yield item
                continue
            if 'portlets' not in item[fileskey]:
                yield item
                continue

            path = item[pathkey]
            obj = self.context.unrestrictedTraverse(path, None)
            if obj is None:  # path doesn't exist
                yield item
                continue

            # Purge assignments if 'purge' option set to true
            if self.purge:
                for name, portletManager in getUtilitiesFor(IPortletManager):
                    assignable = queryMultiAdapter((obj, portletManager),
                                                   IPortletAssignmentMapping)
                    if assignable is not None:
                        for key in list(assignable.keys()):
                            del assignable[key]

            if ILocalPortletAssignable.providedBy(obj):
                data = None
                data = item[fileskey]['portlets']['data']
                doc = minidom.parseString(data)
                root = doc.documentElement
                for elem in root.childNodes:
                    if elem.nodeName == 'assignment':
                        self.importAssignment(obj, elem)
                    elif elem.nodeName == 'blacklist':
                        self.importBlacklist(obj, elem)

            yield item
    def __iter__(self):
        self.portlet_schemata = dict([(iface, name, ) for name, iface in
            getUtilitiesFor(IPortletTypeInterface)])
        self.portlet_managers = list(getUtilitiesFor(IPortletManager))

        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]

            if not pathkey:
                yield item
                continue

            path = item[pathkey]
            obj = self.context.unrestrictedTraverse(path, None)
            if obj is None:         # path doesn't exist
                yield item
                continue

            if ILocalPortletAssignable.providedBy(obj):
                data = None

                root = self.doc.createElement('portlets')

                for elem in self.exportAssignments(obj):
                    root.appendChild(elem)
                for elem in self.exportBlacklists(obj):
                    root.appendChild(elem)
                if root.hasChildNodes():
                    self.doc.appendChild(root)
                    data = self.doc.toprettyxml(indent='  ', encoding='utf-8')
                    self.doc.unlink()

                if data:
                    item.setdefault(self.fileskey, {})
                    item[self.fileskey]['portlets'] = {
                        'name': '.portlets.xml',
                        'data': data,
                    }
            yield item
    def __iter__(self):

        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]
            fileskey = self.fileskey(*item.keys())[0]

            if not (pathkey and fileskey):
                yield item
                continue
            if 'portlets' not in item[fileskey]:
                yield item
                continue

            path = item[pathkey]
            obj = self.context.unrestrictedTraverse(path, None)
            if obj is None:         # path doesn't exist
                yield item
                continue

            # Purge assignments if 'purge' option set to true
            if self.purge:
                for name, portletManager in getUtilitiesFor(IPortletManager):
                    assignable = queryMultiAdapter((obj, portletManager), IPortletAssignmentMapping)
                    if assignable is not None:
                        for key in list(assignable.keys()):
                            del assignable[key]

            if ILocalPortletAssignable.providedBy(obj):
                data = None
                data = item[fileskey]['portlets']['data']
                doc = minidom.parseString(data)
                root = doc.documentElement
                for elem in root.childNodes:
                    if elem.nodeName == 'assignment':
                        self.importAssignment(obj, elem)
                    elif elem.nodeName == 'blacklist':
                        self.importBlacklist(obj, elem)

            yield item
Esempio n. 20
0
    def get_portlets(self):
        """If there is portlets then extract its.
        """

        self.doc = minidom.Document()
        self.portlet_schemata = dict([(iface, name,) for name, iface in getUtilitiesFor(IPortletTypeInterface)])  # noqa
        self.portlet_managers = list(getUtilitiesFor(IPortletManager))
        if ILocalPortletAssignable.providedBy(self.context):
            data = None

            root = self.doc.createElement('portlets')

            for elem in self.exportAssignments(self.context):
                root.appendChild(elem)
            for elem in self.exportBlacklists(self.context):
                root.appendChild(elem)
            if root.hasChildNodes():
                self.doc.appendChild(root)
                data = self.doc.toprettyxml(indent='  ', encoding='utf-8')
                self.doc.unlink()

            if data:
                self['portlets'] = data
Esempio n. 21
0
def copy_portlet_assignments_and_settings(src, target):
    if not ILocalPortletAssignable.providedBy(src):
        alsoProvides(src, ILocalPortletAssignable)
    src_utilities = getUtilitiesFor(IPortletManager, context=src)
    for manager_name, src_manager in src_utilities:
        src_manager_assignments = getMultiAdapter(
            (src, src_manager),
            IPortletAssignmentMapping)
        target_manager = queryUtility(
            IPortletManager,
            name=manager_name,
            context=target)
        if target_manager is None:
            logger.warning('New folder %s does not have portlet manager %s' %
                           (target.getId(), target_manager))
        else:
            target_manager_assignments = getMultiAdapter(
                (target, target_manager),
                IPortletAssignmentMapping)
            for id, assignment in src_manager_assignments.items():
                target_manager_assignments[id] = assignment
            src_assignment_manager = getMultiAdapter(
                (src, src_manager),
                ILocalPortletAssignmentManager)
            target_assignment_manager = getMultiAdapter(
                (target, target_manager),
                ILocalPortletAssignmentManager)
            #
            # In lineage 0.1 child folders did not inherit their parent's
            # portlets no matter what porlet block settings were set.
            #
            target_assignment_manager.setBlacklistStatus(
                CONTEXT_CATEGORY, True)
            for category in (GROUP_CATEGORY, CONTENT_TYPE_CATEGORY):
                target_assignment_manager.setBlacklistStatus(
                    category,
                    src_assignment_manager.getBlacklistStatus(category))
Esempio n. 22
0
    def getPortlets(self):
        """Work out which portlets to display, returning a list of dicts
        describing assignments to render.
        """

        if IPortletContext.providedBy(self.context):
            pcontext = self.context
        else:
            pcontext = queryAdapter(self.context, IPortletContext)

        if pcontext is None:
            return []

        # Holds a list of (category, key, assignment).
        categories = []

        # Keeps track of the blacklisting status for global categores
        # (user, group, content type). The status is either True (blocked)
        # or False (not blocked).
        blacklisted = {}

        # This is the name of the manager (column) we're rendering
        manager = self.storage.__name__

        # 1. Fetch blacklisting status for each global category

        # First, find out which categories we will need to determine
        # blacklist status for

        for category, key in pcontext.globalPortletCategories(False):
            blacklisted[category] = None

        # Then walk the content hierarchy to find out what blacklist status
        # was assigned. Note that the blacklist is tri-state; if it's None it
        # means no assertion has been made (i.e. the category has neither been
        # whitelisted or blacklisted by this object or any parent). The first
        # item to give either a blacklisted (True) or whitelisted (False)
        # value for a given item will set the appropriate value. Parents of
        # this item that also set a black- or white-list value will then be
        # ignored.

        # Whilst walking the hierarchy, we also collect parent portlets,
        # until we hit the first block.

        current = self.context
        currentpc = pcontext
        blacklistFetched = set()
        parentsBlocked = False

        while current is not None and currentpc is not None:
            if ILocalPortletAssignable.providedBy(current):
                assignable = current
            else:
                assignable = queryAdapter(current, ILocalPortletAssignable)

            if assignable is not None:
                if IAnnotations.providedBy(assignable):
                    annotations = assignable
                else:
                    annotations = queryAdapter(assignable, IAnnotations)

                if not parentsBlocked:
                    local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
                    if local is not None:
                        localManager = local.get(manager, None)
                        if localManager is not None:
                            categories.extend([(CONTEXT_CATEGORY, currentpc.uid, a) for a in localManager.values()])

                lpam = getMultiAdapter((assignable, self.storage), ILocalPortletAssignmentManager)
                if lpam.getBlacklistStatus(CONTEXT_CATEGORY):
                    parentsBlocked = True
                for cat, cat_status in blacklisted.items():
                    local_status = lpam.getBlacklistStatus(cat)
                    if local_status is not None:
                        blacklistFetched.add(cat)
                        if cat_status is None:
                            blacklisted[cat] = local_status

            # We can abort if parents are blocked and we've fetched all
            # blacklist statuses

            if parentsBlocked and len(blacklistFetched) == len(blacklisted):
                break

            # Check the parent - if there is no parent, we will stop
            current = currentpc.getParent()
            if current is not None:
                if IPortletContext.providedBy(current):
                    currentpc = current
                else:
                    currentpc = queryAdapter(current, IPortletContext)

        # Get all global mappings for non-blacklisted categories

        for category, key in pcontext.globalPortletCategories(False):
            if not blacklisted[category]:
                mapping = self.storage.get(category, None)
                if mapping is not None:
                    for a in mapping.get(key, {}).values():
                        categories.append((category, key, a, ))

        assignments = []
        for category, key, assignment in categories:
            try:
                settings = IPortletAssignmentSettings(assignment)
                if not settings.get('visible', True):
                    continue
            except TypeError:
                # Portlet does not exist any longer
                continue
            assignments.append({'category': category,
                                'key': key,
                                'name': str(assignment.__name__),
                                'assignment': assignment
                                })
        return assignments
Esempio n. 23
0
 def portlet_assignable(self):
     return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 24
0
    def getPortlets(self):
        """Work out which portlets to display, returning a list of dicts
        describing assignments to render.
        """

        pcontext = IPortletContext(self.context, None)
        if pcontext is None:
            return []

        # Holds a list of (category, key, assignment).
        categories = []

        # Keeps track of the blacklisting status for global categores
        # (user, group, content type). The status is either True (blocked)
        # or False (not blocked).
        blacklisted = {}

        # This is the name of the manager (column) we're rendering
        manager = self.storage.__name__

        # 1. Fetch blacklisting status for each global category

        # First, find out which categories we will need to determine
        # blacklist status for

        for category, key in pcontext.globalPortletCategories(False):
            blacklisted[category] = None

        # Then walk the content hierarchy to find out what blacklist status
        # was assigned. Note that the blacklist is tri-state; if it's None it
        # means no assertion has been made (i.e. the category has neither been
        # whitelisted or blacklisted by this object or any parent). The first
        # item to give either a blacklisted (True) or whitelisted (False)
        # value for a given item will set the appropriate value. Parents of
        # this item that also set a black- or white-list value will then be
        # ignored.

        # Whilst walking the hierarchy, we also collect parent portlets,
        # until we hit the first block.

        current = self.context
        currentpc = pcontext
        blacklistFetched = set()
        parentsBlocked = False

        while current is not None and currentpc is not None:
            assignable = ILocalPortletAssignable(current, None)
            if assignable is not None:
                annotations = IAnnotations(assignable)

                if not parentsBlocked:
                    local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
                    if local is not None:
                        localManager = local.get(manager, None)
                        if localManager is not None:
                            #categories.extend([(CONTEXT_CATEGORY, currentpc.uid, a) for a in localManager.values()]) #SV -
                            new_categories = [
                                (CONTEXT_CATEGORY, currentpc.uid, a)
                                for a in localManager.values()
                            ]  #SV +
                            categories = new_categories + categories  #SV +

                blacklistStatus = annotations.get(CONTEXT_BLACKLIST_STATUS_KEY,
                                                  {}).get(manager, None)
                if blacklistStatus is not None:
                    for cat, status in blacklistStatus.items():
                        if cat == CONTEXT_CATEGORY:
                            if not parentsBlocked and status == True:
                                parentsBlocked = True
                        else:  # global portlet categories
                            if blacklisted.get(cat, False) is None:
                                blacklisted[cat] = status
                            if status is not None:
                                blacklistFetched.add(cat)

            # We can abort if parents are blocked and we've fetched all
            # blacklist statuses

            if parentsBlocked and len(blacklistFetched) == len(blacklisted):
                break

            # Check the parent - if there is no parent, we will stop
            current = currentpc.getParent()
            if current is not None:
                currentpc = IPortletContext(current, None)

        # Get all global mappings for non-blacklisted categories

        for category, key in pcontext.globalPortletCategories(False):
            if not blacklisted[category]:
                mapping = self.storage.get(category, None)
                if mapping is not None:
                    for a in mapping.get(key, {}).values():
                        categories.append((
                            category,
                            key,
                            a,
                        ))

        assignments = []
        for category, key, assignment in categories:
            assignments.append({
                'category': category,
                'key': key,
                'name': assignment.__name__,
                'assignment': assignment
            })
        return assignments
    def can_manage_portlets(self):

        if not ILocalPortletAssignable.providedBy(self.context):
            return False
        mtool = getToolByName(self.context, 'portal_membership')
        return mtool.checkPermission("Portlets: Manage portlets", self.context)
Esempio n. 26
0
 def testAssignable(self):
     self.failUnless(ILocalPortletAssignable.providedBy(self.folder))
     self.failUnless(ILocalPortletAssignable.providedBy(self.portal))
 def can_manage_portlets(self):
     context = self._context()
     if not ILocalPortletAssignable.providedBy(context):
         return False
     mtool = getToolByName(context, 'portal_membership')
     return mtool.checkPermission("Portlets: Manage portlets", context) and self.isinmanagerrole()
    def getPortlets(self):

        portal_state = getMultiAdapter((self.context, self.context.REQUEST),
                                       name=u'plone_portal_state')
        portal = portal_state.portal()
        pcontext = IPortletContext(self.context, None)
        if pcontext is None:
            return []

        categories = []

        blacklisted = {}

        manager = self.storage.__name__

        for category, key in pcontext.globalPortletCategories(False):
            blacklisted[category] = None

        current = self.context
        currentpc = pcontext
        blacklistFetched = set()
        parentsBlocked = False

        while current is not None and currentpc is not None:
            if ILocalPortletAssignable.providedBy(current):
                assignable = current
            else:
                assignable = queryAdapter(current, ILocalPortletAssignable)

            if assignable is not None:
                if IAnnotations.providedBy(assignable):
                    annotations = assignable
                else:
                    annotations = queryAdapter(assignable, IAnnotations)

                if not parentsBlocked:
                    local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
                    if local is not None:
                        localManager = local.get(manager, None)
                        if localManager is not None:
                            categories.extend([(CONTEXT_CATEGORY,
                                                currentpc.uid, a)
                                               for a in localManager.values()])

                blacklistStatus = annotations.get(CONTEXT_BLACKLIST_STATUS_KEY,
                                                  {}).get(manager, None)
                if blacklistStatus is not None:
                    for cat, status in blacklistStatus.items():
                        if cat == CONTEXT_CATEGORY:
                            if not parentsBlocked and status == True:
                                parentsBlocked = True
                        else:  # global portlet categories
                            if blacklisted.get(cat, False) is None:
                                blacklisted[cat] = status
                            if status is not None:
                                blacklistFetched.add(cat)

            if parentsBlocked and len(blacklistFetched) == len(blacklisted):
                break
            current = currentpc.getParent()
            if current is not None:
                if IPortletContext.providedBy(current):
                    currentpc = current
                else:
                    currentpc = queryAdapter(current, IPortletContext)

        for category, key in pcontext.globalPortletCategories(False):
            if not blacklisted[category]:
                mapping = self.storage.get(category, None)
                if mapping is not None:
                    for a in mapping.get(key, {}).values():
                        categories.append((
                            category,
                            key,
                            a,
                        ))

        managerUtility = getUtility(IPortletManager, manager, portal)

        here_url = '/'.join(aq_inner(self.context).getPhysicalPath())

        assignments = []
        for category, key, assignment in categories:
            assigned = ISolgemaPortletAssignment(assignment)
            portletHash = hashPortletInfo(
                dict(
                    manager=manager,
                    category=category,
                    key=key,
                    name=assignment.__name__,
                ))
            if not getattr(assigned, 'stopUrls', False) or len([
                    stopUrl for stopUrl in getattr(assigned, 'stopUrls', [])
                    if stopUrl in here_url
            ]) == 0:
                assignments.append({
                    'category':
                    category,
                    'key':
                    key,
                    'name':
                    assignment.__name__,
                    'assignment':
                    assignment,
                    'hash':
                    hashPortletInfo(
                        dict(
                            manager=manager,
                            category=category,
                            key=key,
                            name=assignment.__name__,
                        )),
                    'stopUrls':
                    ISolgemaPortletAssignment(assignment).stopUrls,
                })

        if hasattr(managerUtility, 'listAllManagedPortlets'):
            hashlist = managerUtility.listAllManagedPortlets
            assignments.sort(lambda a, b: cmp(
                hashlist.count(a['hash']) > 0 and hashlist.index(a['hash']
                                                                 ) or 0,
                hashlist.count(b['hash']) > 0 and hashlist.index(b['hash']) or
                0))

        return assignments
    def getManagedPortlets(self):
        """Work out which portlets to display, returning a list of dicts
        describing assignments to render.
        Bypass blacklist tests
        """
        portal_state = getMultiAdapter((self.context, self.context.REQUEST),
                                       name=u'plone_portal_state')
        portal = portal_state.portal()
        pcontext = IPortletContext(self.context, None)
        if pcontext is None:
            return []

        categories = []

        blacklisted = {}

        manager = self.storage.__name__

        current = self.context
        currentpc = pcontext
        blacklistFetched = set()
        parentsBlocked = False

        while current is not None and currentpc is not None:
            assignable = ILocalPortletAssignable(current, None)
            if assignable is not None:
                annotations = IAnnotations(assignable)
                local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
                if local is not None:
                    localManager = local.get(manager, None)
                    if localManager is not None:
                        categories.extend([(CONTEXT_CATEGORY, currentpc.uid, a)
                                           for a in localManager.values()])

            # Check the parent - if there is no parent, we will stop
            current = currentpc.getParent()
            if current is not None:
                currentpc = IPortletContext(current, None)

        # Get all global mappings for non-blacklisted categories

        for category, key in pcontext.globalPortletCategories(False):
            mapping = self.storage.get(category, None)
            if mapping is not None:
                for a in mapping.get(key, {}).values():
                    categories.append((
                        category,
                        key,
                        a,
                    ))

        managerUtility = getUtility(IPortletManager, manager, portal)

        if not getattr(managerUtility, 'listAllManagedPortlets', []):
            managerUtility.listAllManagedPortlets = []

        hashlist = getattr(managerUtility, 'listAllManagedPortlets', [])
        assignments = []
        for category, key, assignment in categories:
            portletHash = hashPortletInfo(
                dict(
                    manager=manager,
                    category=category,
                    key=key,
                    name=assignment.__name__,
                ))
            if portletHash not in hashlist:
                hashlist.append(portletHash)
            assignments.append({
                'category':
                category,
                'key':
                key,
                'name':
                assignment.__name__,
                'assignment':
                assignment,
                'hash':
                portletHash,
                'stopUrls':
                ISolgemaPortletAssignment(assignment).stopUrls,
                'manager':
                manager,
            })

        managerUtility.listAllManagedPortlets = hashlist

        #order the portlets
        assignments.sort(lambda a, b: cmp(hashlist.index(a['hash']),
                                          hashlist.index(b['hash'])))

        li = []
        here_url = '/'.join(aq_inner(self.context).getPhysicalPath())
        for assigndict in assignments:
            stopped = False
            if assigndict.has_key('stopUrls') and hasattr(
                    assigndict['stopUrls'],
                    'sort') and len(assigndict['stopUrls']) > 0:
                for stopUrl in assigndict['stopUrls']:
                    if stopUrl in here_url:
                        stopped = True
            assigndict['stopped'] = stopped
            assigndict['here_url'] = here_url

        return assignments
Esempio n. 30
0
 def portlet_assignable(self):
     return ILocalPortletAssignable.providedBy(self.context)
Esempio n. 31
0
 def testAssignable(self):
     self.failUnless(ILocalPortletAssignable.providedBy(self.folder))
     self.failUnless(ILocalPortletAssignable.providedBy(self.portal))
Esempio n. 32
0
 def testAssignable(self):
     self.assertTrue(ILocalPortletAssignable.providedBy(self.folder))
     self.assertTrue(ILocalPortletAssignable.providedBy(self.portal))
    def getPortlets(self):

        portal_state = getMultiAdapter((self.context, self.context.REQUEST), name=u'plone_portal_state')
        portal = portal_state.portal()
        pcontext = IPortletContext(self.context, None)
        if pcontext is None:
            return []

        categories = [] 

        blacklisted = {}

        manager = self.storage.__name__

        for category, key in pcontext.globalPortletCategories(False):
            blacklisted[category] = None

        current = self.context
        currentpc = pcontext
        blacklistFetched = set()
        parentsBlocked = False
        
        while current is not None and currentpc is not None:
            if ILocalPortletAssignable.providedBy(current):
                assignable = current
            else:
                assignable = queryAdapter(current, ILocalPortletAssignable)

            if assignable is not None:
                if IAnnotations.providedBy(assignable):
                    annotations = assignable
                else:
                    annotations = queryAdapter(assignable, IAnnotations)
                
                if not parentsBlocked:
                    local = annotations.get(CONTEXT_ASSIGNMENT_KEY, None)
                    if local is not None:
                        localManager = local.get(manager, None)
                        if localManager is not None:
                            categories.extend([(CONTEXT_CATEGORY, currentpc.uid, a) for a in localManager.values()])

                blacklistStatus = annotations.get(CONTEXT_BLACKLIST_STATUS_KEY, {}).get(manager, None)
                if blacklistStatus is not None:
                    for cat, status in blacklistStatus.items():
                        if cat == CONTEXT_CATEGORY:
                            if not parentsBlocked and status == True:
                                parentsBlocked = True
                        else: # global portlet categories
                            if blacklisted.get(cat, False) is None:
                                blacklisted[cat] = status
                            if status is not None:
                                blacklistFetched.add(cat)

            if parentsBlocked and len(blacklistFetched) == len(blacklisted):
                break
            current = currentpc.getParent()
            if current is not None:
                if IPortletContext.providedBy(current):
                    currentpc = current
                else:
                    currentpc = queryAdapter(current, IPortletContext)

        for category, key in pcontext.globalPortletCategories(False):
            if not blacklisted[category]:
                mapping = self.storage.get(category, None)
                if mapping is not None:
                    for a in mapping.get(key, {}).values():
                        categories.append((category, key, a,))

        managerUtility = getUtility(IPortletManager, manager, portal)

        here_url = '/'.join(aq_inner(self.context).getPhysicalPath())

        assignments = []
        for category, key, assignment in categories:
            assigned = ISolgemaPortletAssignment(assignment)
            portletHash = hashPortletInfo(dict(manager=manager, category=category, key=key, name =assignment.__name__,))
            if not getattr(assigned, 'stopUrls', False) or len([stopUrl for stopUrl in getattr(assigned, 'stopUrls', []) if stopUrl in here_url])==0:
                assignments.append({'category'    : category,
                                    'key'         : key,
                                    'name'        : assignment.__name__,
                                    'assignment'  : assignment,
                                    'hash'        : hashPortletInfo(dict(manager=manager, category=category, key=key, name =assignment.__name__,)),
                                    'stopUrls'    : ISolgemaPortletAssignment(assignment).stopUrls,
                                    })
        
        if hasattr(managerUtility, 'listAllManagedPortlets'):
            hashlist = managerUtility.listAllManagedPortlets
            assignments.sort(lambda a,b:cmp(hashlist.count(a['hash'])>0 and hashlist.index(a['hash']) or 0, hashlist.count(b['hash'])>0 and hashlist.index(b['hash']) or 0))

        return assignments
    def test_migration_preserves_portlets(self):
        portal = self.layer['portal']
        z2.login(portal['acl_users'], 'manager')
        portal.invokeFactory("Child Folder", "cf1")
        cf1 = portal.cf1
        cf1.setTitle("CF 1")
        make_objectmanager_site(cf1)
        pw = portal.portal_workflow
        pw.doActionFor(cf1, "publish")
        self.failUnless(cf1.Title() == "CF 1")
        self.failUnless(pw.getInfoFor(cf1, "review_state") == "published")
        self.failUnless(ISite.providedBy(cf1))
        # Child folders in 0.1 seemed to provide ILocalPortletAssignable but
        # not in 0.6
        if not ILocalPortletAssignable.providedBy(cf1):
            zope.interface.alsoProvides(cf1, ILocalPortletAssignable)
            added_portlet_assignable_interace = True
        else:
            added_portlet_assignable_interace = False

        mapping = cf1.restrictedTraverse('++contextportlets++plone.leftcolumn')
        for m in mapping.keys():
            del mapping[m]
        portlet = zope.component.getUtility(IPortletType,
                                            name='plone.portlet.static.Static')
        addview = mapping.restrictedTraverse('+/' + portlet.addview)
        addview.createAndAdd(data={
            'header': u"test title",
            'text': u"test text"})
        self.assertEquals(len(mapping), 1)

        left_col_manager = zope.component.getUtility(
            IPortletManager,
            name='plone.leftcolumn',
            context=cf1)
        assignment_manager = zope.component.getMultiAdapter(
            (cf1, left_col_manager),
            ILocalPortletAssignmentManager)
        assignment_manager.setBlacklistStatus(GROUP_CATEGORY, None)
        assignment_manager.setBlacklistStatus(CONTENT_TYPE_CATEGORY, False)

        if added_portlet_assignable_interace:
            zope.interface.noLongerProvides(cf1, ILocalPortletAssignable)

        self.run_migration_step()

        cf1 = portal.cf1
        mapping = cf1.restrictedTraverse('++contextportlets++plone.leftcolumn')
        self.assertEquals(len(mapping), 1)

        left_col_manager = zope.component.getUtility(
            IPortletManager,
            name='plone.leftcolumn',
            context=cf1)
        assignment_manager = zope.component.getMultiAdapter(
            (cf1, left_col_manager),
            ILocalPortletAssignmentManager)
        self.assertTrue(
            assignment_manager.getBlacklistStatus(CONTEXT_CATEGORY))
        self.assertTrue(
            assignment_manager.getBlacklistStatus(GROUP_CATEGORY) is None)
        self.assertFalse(
            assignment_manager.getBlacklistStatus(CONTENT_TYPE_CATEGORY))
Esempio n. 35
0
 def testAssignable(self):
     self.assertTrue(ILocalPortletAssignable.providedBy(self.folder))
     self.assertTrue(ILocalPortletAssignable.providedBy(self.portal))