Ejemplo n.º 1
0
    def test_remove_remove_broken_portlet_manager(self):
        from plone.portlets.interfaces import IPortletManager
        from plone.portlets.interfaces import IPortletManagerRenderer
        from plone.portlets.manager import PortletManager
        from zope.browser.interfaces import IBrowserView
        from zope.publisher.interfaces.browser import IBrowserRequest

        sm = self.portal.getSiteManager()
        sm.registerUtility(component=PortletManager(),
                           provided=IPortletManager,
                           name='my.manager')

        self.assertIsNotNone(
            sm.adapters.lookup([Interface, IBrowserRequest, IBrowserView],
                               IPortletManagerRenderer, 'my.manager'))
        self.assertIsNotNone(
            sm.queryUtility(IPortletManager, name='my.manager'))

        class Step(UpgradeStep):
            def __call__(self):
                self.remove_broken_portlet_manager('my.manager')

        Step(self.portal_setup)

        self.assertIsNone(
            sm.adapters.lookup([Interface, IBrowserRequest, IBrowserView],
                               IPortletManagerRenderer, 'my.manager'))
        self.assertIsNone(sm.queryUtility(IPortletManager, name='my.manager'))
def setupVarious_install(context):
    name = 'plone.rightcolumn'
    site = context.getSite()
    site.getSiteManager()
    sm = site.getSiteManager()

    u = queryUtility(IPortletManager, name=name)
    our_interface = False
    if u is not None:
        # Remove the utility only if it is not ours already.
        # This assures that Reinstall does not purge the portlet data.
        our_interface = IPersonalPortletManager in providedBy(u)
        if not our_interface:
            sm.unregisterUtility(provided=IPortletManager, name=name)
    
    assert our_interface or queryUtility(IPortletManager, name=name) is None

    # Create the utility only if needed
    if not our_interface:

        # Create our portlet manager
        manager = PortletManager()
        
        alsoProvides(manager, IPersonalPortletManager)
       
        manager[USER_CATEGORY] = PortletCategoryMapping()
        manager[GROUP_CATEGORY] = PortletCategoryMapping()
        manager[CONTENT_TYPE_CATEGORY] = PortletCategoryMapping()

        sm.registerUtility(component=manager, provided=IPortletManager, name=name)
Ejemplo n.º 3
0
    def testRendererRegistered(self):
        context = self.portal
        request = self.portal.REQUEST
        view = DummyView(context, request)
        manager = PortletManager()
        assignment = TestAssignment()

        renderer = getMultiAdapter((context, request, view, manager, assignment), IPortletRenderer)
        self.assertTrue(isinstance(renderer, TestRenderer))
Ejemplo n.º 4
0
def changeHomePortletsTitles(portal, logger):

    from plone.portlets.interfaces import IPortletManager
    from plone.portlets.interfaces import ILocalPortletAssignmentManager
    from plone.portlets.constants import CONTEXT_CATEGORY
    from zope.app.container.interfaces import INameChooser
    from plone.portlets.interfaces import IPortletAssignmentMapping
    from zope.component.interfaces import ComponentLookupError

    from plone.portlets.interfaces import IPortletManager
    from plone.portlets.manager import PortletManager
    from zope.interface import alsoProvides

    from ubify.viewlets.browser.interfaces import IHomeContent

    try:
        objviews = getattr(portal, 'views')
        assignments = get_assignments_for_sitehome_collectionportlets(
            portal, objviews, logger)
        sm = getSiteManager(portal)
        name = 'ubify.homecontentportletsmanager'
        try:
            portletManager = getUtility(IPortletManager, name=name)
        except ComponentLookupError:
            objportletManager = PortletManager()
            alsoProvides(objportletManager, IHomeContent)

            sm.registerUtility(component=objportletManager,
                               provided=IPortletManager,
                               name=name)
            portletManager = getUtility(IPortletManager, name=name)

        assignable = getMultiAdapter((
            portal,
            portletManager,
        ), ILocalPortletAssignmentManager)
        manager = getMultiAdapter((portal, portletManager),
                                  IPortletAssignmentMapping)

        mgkeys = manager.keys()
        for k in mgkeys:
            del manager[k]

        if assignments:
            if portletManager is not None:
                chooser = INameChooser(manager)
                for assignment in assignments:
                    if manager.has_key(assignment.id) == 0:
                        manager[chooser.chooseName(None,
                                                   assignment)] = assignment
                        logger.info(
                            "Assigning collection portlet manager for %s" %
                            (assignment.id, ))
    except AttributeError:
        logger.info("Unable to set up site home collection portlets.")
Ejemplo n.º 5
0
    def _initPortletManagerNode(self, node):
        """Create a portlet manager from a node
        """
        name = str(node.getAttribute('name'))

        if node.hasAttribute('remove'):
            if self._convertToBoolean(node.getAttribute('remove')):
                self.context.unregisterUtility(provided=IPortletManager,
                                               name=name)
                return

        if node.hasAttribute('purge'):
            if self._convertToBoolean(node.getAttribute('purge')):
                manager = getUtility(IPortletManager, name=name)
                # remove global assignments
                for category in manager.keys():
                    for portlet in manager[category].keys():
                        del manager[category][portlet]
                # remove assignments from root
                site = self.environ.getSite()
                mapping = queryMultiAdapter((site, manager),
                                            IPortletAssignmentMapping)
                for portlet in mapping.keys():
                    del mapping[portlet]
                return

        registeredPortletManagers = [
            r.name for r in self.context.registeredUtilities()
            if r.provided.isOrExtends(IPortletManager)
        ]
        if name not in registeredPortletManagers:
            managerClass = node.getAttribute('class')
            if managerClass:
                manager = _resolveDottedName(managerClass)()
            else:
                manager = PortletManager()

            managerType = node.getAttribute('type')
            if managerType:
                alsoProvides(manager, _resolveDottedName(managerType))

            manager[USER_CATEGORY] = PortletCategoryMapping()
            manager[GROUP_CATEGORY] = PortletCategoryMapping()
            manager[CONTENT_TYPE_CATEGORY] = PortletCategoryMapping()

            self.context.registerUtility(component=manager,
                                         provided=IPortletManager,
                                         name=name)
Ejemplo n.º 6
0
def assignStackerRelatedPortlet(portal):
    from ubify.policy.config import list_of_portletmanagers_for_stackerportlet_assignment, cynin_desktop_left_column_text
    static_portlet_text = cynin_desktop_left_column_text

    #static_portlet_nav_url = portal.absolute_url() + "/stacker-badge"
    #static_portlet_text = static_portlet_text % (static_portlet_nav_url)

    from plone.portlet.static import static
    assignments = (static.Assignment(header='cyn.in Desktop',
                                     text=static_portlet_text,
                                     omit_border=True), )

    for name in list_of_portletmanagers_for_stackerportlet_assignment:
        if assignments:
            try:
                portletManager = getUtility(IPortletManager, name=name)
            except ComponentLookupError:
                sm = getSiteManager(portal)
                objportletManager = PortletManager()

                sm.registerUtility(component=objportletManager,
                                   provided=IPortletManager,
                                   name=name)
                portletManager = getUtility(IPortletManager, name=name)

            assignable = getMultiAdapter((
                portal,
                portletManager,
            ), ILocalPortletAssignmentManager)
            manager = getMultiAdapter((portal, portletManager),
                                      IPortletAssignmentMapping)

            if portletManager is not None:
                chooser = INameChooser(manager)
                for assignment in assignments:
                    strtitle = assignment.title.lower()
                    strtitle = strtitle.replace(' ', '-')
                    if manager.has_key(strtitle) == 0:
                        manager[chooser.chooseName(None,
                                                   assignment)] = assignment
Ejemplo n.º 7
0
def assign_space_dashboard(space,event):
    #import pdb;pdb.set_trace()
    site = space.portal_url.getPortalObject()
    objDashboard = ISpaceDefaultDashboard(space,None)
    if objDashboard is None:
        return
    
    spaceid = space.id
    portlets = objDashboard()
    
    for name in (spacemembersportletmanager_name,spacedashboardportletmanager_name,spacemindmapmanager_name,spacehomeleftblockmanager_name):
        assignments = portlets.get(name)        
        if assignments:
            try:
                portletManager = getUtility(IPortletManager, name=name)
            except ComponentLookupError:
                sm = getSiteManager(site)
                objportletManager = PortletManager()
                if name == spacedashboardportletmanager_name:
                    alsoProvides(objportletManager,IHomeContent)
                elif name == spacemembersportletmanager_name:
                    alsoProvides(objportletManager,ISpaceMembersContent)
                elif name == spacemindmapmanager_name:
                    alsoProvides(objportletManager,IMindMapContent)
                elif name == spacehomeleftblockmanager_name:
                    alsoProvides(objportletManager,IHomeLeftblockContent)
                    
                sm.registerUtility(component=objportletManager,
                                   provided=IPortletManager,
                                   name = name)        
                portletManager = getUtility(IPortletManager, name=name) 
                
            assignable = getMultiAdapter((space, portletManager,), ILocalPortletAssignmentManager)
            manager = getMultiAdapter((space, portletManager), IPortletAssignmentMapping)
            
            if portletManager is not None:            
                chooser = INameChooser(manager)
                for assignment in assignments:
                    if name == spacemindmapmanager_name:
                        bfound = False
                        for eobj in manager.values():
                            if isinstance(eobj,spacemindmapportlet.Assignment):
                                bfound = True
                            if bfound:
                                break;
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment
                    elif name == spacehomeleftblockmanager_name:
                        bfound = False
                        for eobj in manager.values():
                            if isinstance(eobj,assignment.__class__):
                                bfound = True
                            elif isinstance(eobj,assignment.__class__):
                                bfound = True
                            
                            if bfound:
                                break;
                        
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment
                    elif name == spacemembersportletmanager_name:
                        bfound = False
                        for eobj in manager.values():
                            if isinstance(eobj,assignment.__class__):
                                bfound = True
                            elif isinstance(eobj,assignment.__class__):
                                bfound = True
                            
                            if bfound:
                                break;
                        
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment
                    else:
                        strtitle = assignment.title.lower()
                        strtitle = strtitle.replace(' ','-')
                        if manager.has_key(strtitle) == 0:
                            manager[chooser.chooseName(None, assignment)] = assignment
                        
            assignable.setBlacklistStatus(CONTEXT_CATEGORY, True)

    
#def enable_addable_types(space, event):
#    """Give the given role the add permission on all the selected types.
#    """
#    portal_types = getToolByName(space, 'portal_types')
#    role = 'TeamMember'
#    #import pdb;pdb.set_trace()
#    for fti in portal_types.listTypeInfo():
#        type_id = fti.getId()
#
#        permission = get_factory_permission(space, fti)
#        if permission is not None:
#            roles = [r['name'] for r in space.rolesOfPermission(permission) if r['selected']]
#            acquire = bool(space.permission_settings(permission)[0]['acquire'])
#            if type_id in space.addable_types and role not in roles:
#                roles.append(role)
#            elif type_id not in space.addable_types and role in roles:
#                roles.remove(role)
#            space.manage_permission(permission, roles, acquire)
Ejemplo n.º 8
0
def assign_portal_dashboard(portal, event, isReinstall=False):
    site = portal
    objDashboard = ISiteDefaultDashboard(portal, None)
    if objDashboard is None:
        return

    portlets = objDashboard()

    for name in portlets.keys():
        assignments = portlets.get(name)
        try:
            portletManager = getUtility(IPortletManager, name=name)
        except ComponentLookupError:
            sm = getSiteManager(site)
            objportletManager = PortletManager()
            if name == spacedashboardportletmanager_name:
                alsoProvides(objportletManager, IHomeContent)
            elif name == spacemindmapmanager_name:
                alsoProvides(objportletManager, IMindMapContent)
            elif name == spacehomeleftblockmanager_name:
                alsoProvides(objportletManager, IHomeLeftblockContent)

            sm.registerUtility(component=objportletManager,
                               provided=IPortletManager,
                               name=name)
            portletManager = getUtility(IPortletManager, name=name)

        assignable = getMultiAdapter((
            portal,
            portletManager,
        ), ILocalPortletAssignmentManager)
        manager = getMultiAdapter((portal, portletManager),
                                  IPortletAssignmentMapping)

        if portletManager is not None:
            reorderrecentportlet = False
            recentportletname = ''
            chooser = INameChooser(manager)
            for assignment in assignments:
                if name == spacemindmapmanager_name:
                    bfound = False
                    if isReinstall:
                        removeAssignedPortlets(portal, manager, name)
                    for eobj in manager.values():
                        if isinstance(
                                eobj, static.Assignment
                        ) and eobj.id == site_home_top_banner_static_header.lower(
                        ).replace(' ', '-'):
                            bfound = True
                        if bfound:
                            break
                    if not bfound:
                        manager[chooser.chooseName(None,
                                                   assignment)] = assignment
                elif name == spacehomeleftblockmanager_name:
                    bfound = False
                    if isReinstall:
                        removeAssignedPortlets(portal, manager, name)
                    for eobj in manager.values():
                        if isinstance(eobj, assignment.__class__):
                            bfound = True
                        if bfound:
                            #check for recentsiteupdate portlet fix
                            try:
                                if isinstance(
                                        eobj,
                                        recentsiteupdatesportlet.Assignment
                                ) and hasattr(eobj, 'data') and hasattr(
                                        eobj.data,
                                        'resultcount') and isinstance(
                                            eobj.data.resultcount, int):
                                    bfound = False
                                    del manager[eobj.id]
                                    reorderrecentportlet = True
                                    recentportletname = eobj.id.encode(
                                        'ascii', 'replace')
                            except AttributeError:
                                pass
                        if bfound:
                            break
                    if not bfound:
                        manager[chooser.chooseName(None,
                                                   assignment)] = assignment
                elif name == spacedashboardportletmanager_name:
                    bfound = False
                    if isReinstall:
                        removeAssignedPortlets(portal, manager, name)
                    for eobj in manager.values():
                        if isinstance(eobj, assignment.__class__):
                            bfound = True
                        if bfound:
                            break
                    if not bfound:
                        manager[chooser.chooseName(None,
                                                   assignment)] = assignment
            if reorderrecentportlet and isReinstall:
                keys = list(manager.keys())
                idx = keys.index(recentportletname)
                keys.remove(recentportletname)
                keys.insert(0, recentportletname)
                manager.updateOrder(keys)
        if assignable is not None:
            assignable.setBlacklistStatus(CONTEXT_CATEGORY, True)
Ejemplo n.º 9
0
def assign_cynin_navigation(portal):
    cyninnav = ICyninNavigation(portal)
    if cyninnav is None:
        return
    
    portlets = cyninnav()    
    for name in portlets.keys():        
        assignments = portlets.get(name)
        if assignments:
            try:
                portletManager = getUtility(IPortletManager, name=name)
            except ComponentLookupError:
                sm = getSiteManager(portal)
                objportletManager = PortletManager()
                if name == 'ubify.navigationspacesportletmanager':
                    alsoProvides(objportletManager,INavigationSpacesContent)
                elif name == 'ubify.navigationcollectionportletmanager':
                    alsoProvides(objportletManager,INavigationCollectionContent)
                elif name == 'ubify.navigationmembersportletmanager':
                    alsoProvides(objportletManager,INavigationMembersContent)
                    
                sm.registerUtility(component=objportletManager,
                                   provided=IPortletManager,
                                   name = name)        
                portletManager = getUtility(IPortletManager, name=name) 
            
            assignable = getMultiAdapter((portal, portletManager,), ILocalPortletAssignmentManager)
            manager = getMultiAdapter((portal, portletManager), IPortletAssignmentMapping)

            if portletManager is not None:            
                chooser = INameChooser(manager)
                for assignment in assignments:
                    if name == 'ubify.navigationspacesportletmanager':
                        bfound = False
                        for eobj in manager.values():                            
                            if isinstance(eobj,assignment.__class__):
                                bfound = True
                            if bfound and eobj.root == '/' + contentroot_details['oldid']:
                                bfound = False
                                del manager[eobj.id]
                            if bfound:
                                break;
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment
                    elif name == 'ubify.navigationcollectionportletmanager':
                        bfound = False
                        for eobj in manager.values():
                            if isinstance(eobj,assignment.__class__):
                                bfound = True                            
                            if bfound:
                                break;
                        
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment
                    elif name == 'ubify.navigationmembersportletmanager':                        
                        bfound = False
                        for eobj in manager.values():
                            if isinstance(eobj,assignment.__class__):
                                bfound = True                            
                            if bfound:
                                break;
                        
                        if not bfound:
                            manager[chooser.chooseName(None, assignment)] = assignment    
                        
            assignable.setBlacklistStatus(CONTEXT_CATEGORY, True)
def portletsSetUp(test):
    sectionsSetUp(test)

    from zope.interface import Interface
    from zope.annotation.interfaces import IAttributeAnnotatable
    from plone.portlets.interfaces import ILocalPortletAssignable

    # this bases class adds __of__ method
    from Acquisition import Implicit

    class MockPortal(Implicit):
        implements(IAttributeAnnotatable, ILocalPortletAssignable)

        _last_path = None
        def unrestrictedTraverse(self, path, default):
            if path[0] == '/':
                return default # path is absolute
            if isinstance(path, unicode):
                return default
            if path == 'not/existing/bar':
                return default
            if path.endswith('/notassignable'):
                return object()
            self._last_path = path
            return self

        def getPhysicalPath(self):
            return [''] + self._last_path.split('/')

    portal = MockPortal()
    test.globs['plone'] = portal
    test.globs['transmogrifier'].context = test.globs['plone']

    class PortletsSource(SampleSource):
        classProvides(ISectionBlueprint)
        implements(ISection)

        def __init__(self, *args, **kw):
            super(PortletsSource, self).__init__(*args, **kw)
            self.sample = (
                dict(),
                dict(_path='not/existing/bar'),
                dict(_path='spam/eggs/notassignable'),
                dict(_path='assignable'),
                dict(_path='other-assignable', 
                    files=dict(portlets=dict(
                        name='.portlets.xml',
                        data="""<?xml version="1.0" encoding="utf-8"?>
<portlets>
  <assignment category="context" key="/other-assignable" manager="plone.leftcolumn" name="habra-rss" type="portlets.rss">
    <property name="count">
      20
    </property>
    <property name="url">
      http://habrahabr.ru/rss/
    </property>
    <property name="portlet_title">
      Habrahabr RSS feed
    </property>
    <property name="timeout">
      120
    </property>
  </assignment>
  <blacklist category="user" manager="plone.leftcolumn" status="block"/>
  <blacklist category="group" manager="plone.leftcolumn" status="acquire"/>
  <blacklist category="content_type" manager="plone.leftcolumn" status="acquire"/>
  <blacklist category="context" manager="plone.leftcolumn" status="acquire"/>
</portlets>
""")
                    )
                )
            )

    provideUtility(PortletsSource,
        name=u'quintagroup.transmogrifier.tests.portletssource')

    class PortletsSource2(SampleSource):
        classProvides(ISectionBlueprint)
        implements(ISection)

        def __init__(self, *args, **kw):
            super(PortletsSource2, self).__init__(*args, **kw)
            self.sample = (
                dict(),
                dict(_path='other-assignable',
                    files=dict(portlets=dict(
                        name='.portlets.xml',
                        data="""<?xml version="1.0" encoding="utf-8"?>
<portlets>
  <assignment category="context" key="/other-assignable" manager="plone.leftcolumn" name="sumno-rss-2" type="portlets.rss">
    <property name="count">
      30
    </property>
    <property name="url">
      http://sumno.com/rss
    </property>
    <property name="portlet_title">
      Sumno RSS feed
    </property>
    <property name="timeout">
      360
    </property>
  </assignment>
  <blacklist category="user" manager="plone.leftcolumn" status="block"/>
  <blacklist category="group" manager="plone.leftcolumn" status="acquire"/>
  <blacklist category="content_type" manager="plone.leftcolumn" status="acquire"/>
  <blacklist category="context" manager="plone.leftcolumn" status="acquire"/>
</portlets>
""")
                    )
                )
            )
    provideUtility(PortletsSource2,
       name=u'quintagroup.transmogrifier.tests.portletssource2')

    # prepare the one portlet for testing
    from zope.interface import alsoProvides
    from zope.component import getUtility, getMultiAdapter
    from zope.component.interfaces import IFactory
    from zope.component.factory import Factory

    from plone.portlets.manager import PortletManager
    from plone.portlets.interfaces import IPortletManager, IPortletType, \
        IPortletAssignmentMapping
    from plone.portlets.registration import PortletType

    from plone.app.portlets.assignable import localPortletAssignmentMappingAdapter
    from plone.portlets.assignable import LocalPortletAssignmentManager
    from plone.app.portlets.interfaces import IPortletTypeInterface
    from plone.portlets.interfaces import  ILocalPortletAssignmentManager
    from plone.portlets.constants import USER_CATEGORY
    # from plone.app.portlets.browser.interfaces import IPortletAdding
    from plone.app.portlets.portlets.rss import IRSSPortlet, Assignment #, Renderer, AddForm, EditForm

    # register portlet manager and assignment mapping adapter
    manager = PortletManager()
    provideUtility(manager, IPortletManager, name='plone.leftcolumn')
    provideAdapter(localPortletAssignmentMappingAdapter)
    provideAdapter(LocalPortletAssignmentManager)
    mapping = getMultiAdapter((portal, manager), IPortletAssignmentMapping)
    assignable = getMultiAdapter((portal, manager), ILocalPortletAssignmentManager)
    test.globs['mapping'] = mapping
    test.globs['assignable'] = assignable

    # register portlet (this is what plone:portlet zcml directive does)
    PORTLET_NAME = 'portlets.rss'
    alsoProvides(IRSSPortlet, IPortletTypeInterface)
    provideUtility(provides=IPortletTypeInterface, name=PORTLET_NAME, component=IRSSPortlet)
    provideUtility(provides=IFactory, name=PORTLET_NAME, component=Factory(Assignment))

    # register a portlet type (this is what <portlet /> element in portlets.xml
    # does)
    portlet = PortletType()
    portlet.title = 'RSS Feed'
    portlet.description = 'A portlet which can receive and render an RSS feed.'
    portlet.addview = PORTLET_NAME
    portlet.for_ = [Interface]
    provideUtility(component=portlet, provides=IPortletType, 
        name=PORTLET_NAME)

    # add a portlet and configure it (this is done on @@manage-portlets view)
    assignment = getUtility(IFactory, name=PORTLET_NAME)()
    mapping['rss'] = assignment
    portlet_interface = getUtility(IPortletTypeInterface, name=PORTLET_NAME)
    data = {
        'portlet_title': u'RSS feed',
        'count': 10,
        'url': u'http://sumno.com/feeds/main-page/',
        'timeout': 60
    }
    for k, v in data.items():
        field = portlet_interface.get(k)
        field = field.bind(assignment)
        field.validate(v)
        field.set(assignment, v)
    # set blacklists for user category to 'block'
    assignable.setBlacklistStatus(USER_CATEGORY, True)