Пример #1
0
        def _setter(ob, *args, **kw):
            results = []
            cleft = kw['cleft']
            cright = kw['cright']
            cbelowcontext = kw['cbelowcontext']

            if ob.getCanonical() == ob:
                return
            if ob.portal_type == 'LinguaLink':
                return
            path = "/".join(ob.getPhysicalPath())
            left = assignment_mapping_from_key(ob, 'plone.leftcolumn',
                                               CONTEXT_CATEGORY, path)
            right = assignment_mapping_from_key(ob, 'plone.rightcolumn',
                                                CONTEXT_CATEGORY, path)
            belowcontext = assignment_mapping_from_key(
                ob, 'osha.belowcontent.portlets', CONTEXT_CATEGORY, path)

            for x in list(left.keys()):
                del left[x]
            for x in list(cleft.keys()):
                left[x] = cleft[x]

            for x in list(right.keys()):
                del right[x]
            for x in list(cright.keys()):
                right[x] = cright[x]

            for x in list(belowcontext.keys()):
                del belowcontext[x]
            for x in list(cbelowcontext.keys()):
                belowcontext[x] = cbelowcontext[x]
def addSecondaryNavPortlets(context):
    ''' Add and configure the Classic portlet for secondary navigation
    '''

    portal = getSite()
    objs = (portal.get('ueberuns'), portal.get('ueberuns-en'),
            portal.get('ueberuns-fr'))
    for obj in objs:
        if obj:
            path = '/'.join(obj.getPhysicalPath())
            left_portlet_assignment_mapping = \
                assignment_mapping_from_key(obj, 'plone.leftcolumn',
                    CONTEXT_CATEGORY, path)
            if not left_portlet_assignment_mapping.has_key('secondarynavportlet'
                    ):
                left_portlet_assignment_mapping['secondarynavportlet'
                        ] = \
                    classic.Assignment(template='secondarynavportlets',
                        macro='ueberuns')

    objs = (portal.get('rezensionen'), )
    for obj in objs:
        if obj:
            path = '/'.join(obj.getPhysicalPath())
            left_portlet_assignment_mapping = \
                assignment_mapping_from_key(obj, 'plone.leftcolumn',
                    CONTEXT_CATEGORY, path)
            if not left_portlet_assignment_mapping.has_key('secondarynavportlet'
                    ):
                left_portlet_assignment_mapping['secondarynavportlet'
                        ] = \
                    classic.Assignment(template='secondarynavportlets',
                        macro='rezensionen')
Пример #3
0
     def _setter(ob, *args, **kw):
         results = []
         cleft = kw['cleft']
         cright = kw['cright']
         cbelowcontext = kw['cbelowcontext']
         
         if ob.getCanonical() == ob:
             return 
         if ob.portal_type == 'LinguaLink':
             return
         path = "/".join(ob.getPhysicalPath()) 
         left = assignment_mapping_from_key(ob, 'plone.leftcolumn', CONTEXT_CATEGORY, path)
         right = assignment_mapping_from_key(ob, 'plone.rightcolumn', CONTEXT_CATEGORY, path)
         belowcontext = assignment_mapping_from_key(ob, 'osha.belowcontent.portlets', CONTEXT_CATEGORY, path)
 
         for x in list(left.keys()):
             del left[x]
         for x in list(cleft.keys()):
             left[x] = cleft[x]                   
     
         for x in list(right.keys()):
             del right[x]    
         for x in list(cright.keys()):
             right[x] = cright[x]
     
         for x in list(belowcontext.keys()):
             del belowcontext[x]    
         for x in list(cbelowcontext.keys()):
             belowcontext[x] = cbelowcontext[x]
Пример #4
0
    def testAssignmentRoot(self):
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")
        self.assertEqual(3, len(mapping))

        # No assignment in /news subfolder
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/news")
        self.assertEqual(0, len(mapping))

        context = DummyImportContext(self.portal, purge=False)
        context._files['portlets.xml'] = """<?xml version="1.0"?>
            <portlets>
                <assignment
                    manager="test.testcolumn"
                    category="context"
                    key="/news"
                    type="portlets.test.Test"
                    name="test.portlet4"
                    />
            </portlets>
        """
        importPortlets(context)

        # Still 3 portlets in the root
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")
        self.assertEqual(3, len(mapping))

        # but 1 extra in the /news subfolder
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/news")
        self.assertEqual(1, len(mapping))
Пример #5
0
def copyPortletsFromParent(self, doleft=False, doright=False):
        out = StringIO()
        parent= Acquisition.aq_parent(Acquisition.aq_inner(self))
        ppath = "/".join(parent.getPhysicalPath())
        pleft = assignment_mapping_from_key(parent, 'plone.leftcolumn', CONTEXT_CATEGORY, ppath)
        pright = assignment_mapping_from_key(parent, 'plone.rightcolumn', CONTEXT_CATEGORY, ppath)

        ob = Acquisition.aq_inner(self)
        out.write("Copying portlets from parent %s to here %s\n" %(parent.absolute_url(), ob.absolute_url()))
        path = "/".join(ob.getPhysicalPath())
        left = assignment_mapping_from_key(ob, 'plone.leftcolumn', CONTEXT_CATEGORY, path)
        right = assignment_mapping_from_key(ob, 'plone.rightcolumn', CONTEXT_CATEGORY, path)

        if doleft:
            out.write('Copied left portlets\n')
            for x in list(left.keys()):
                del left[x]
            for x in list(pleft.keys()):
                left[x] = pleft[x]
        else:
            out.write('Left portlets NOT copied\n')

        if doright:
            out.write('Copied right portlets\n')
            for x in list(right.keys()):
                del right[x]
            for x in list(pright.keys()):
                right[x] = pright[x]
        else:
            out.write('Right portlets NOT copied\n')

        return out.getvalue()
Пример #6
0
def portletAssignmentDB(context):
    """ assign portlets as they should be set on the database folder """
    path = '/'.join(context.getPhysicalPath())
    left = assignment_mapping_from_key(context, 'plone.leftcolumn', CONTEXT_CATEGORY, path)
    right = assignment_mapping_from_key(context, 'plone.rightcolumn', CONTEXT_CATEGORY, path)
    for x in list(right.keys()):
        del right[x]
    _blockPortlets(context, 'plone.leftcolumn', CONTEXT_CATEGORY, True)
    _blockPortlets(context, 'plone.rightcolumn', CONTEXT_CATEGORY, True)
Пример #7
0
def portletAssignmentPortal(context):
    """ assign portlets as they should be set on the portal root """
    path = "/"
    left = assignment_mapping_from_key(context, 'plone.leftcolumn', CONTEXT_CATEGORY, path)
    right = assignment_mapping_from_key(context, 'plone.rightcolumn', CONTEXT_CATEGORY, path)
    for x in list(left.keys()):
        del left[x]
    for x in list(right.keys()):
        del right[x]
    left['navtree'] = navigation.Assignment()
    left['events'] = events.Assignment()
    right['news'] = news.Assignment()
Пример #8
0
def portletAssignmentMembers(context):
    path = '/'.join(context.getPhysicalPath())

    left = assignment_mapping_from_key(context, 'plone.leftcolumn', CONTEXT_CATEGORY, path)
    right = assignment_mapping_from_key(context, 'plone.rightcolumn', CONTEXT_CATEGORY, path)

    for x in list(left.keys()):
        del left[x]

    for x in list(right.keys()):
        del right[x]

    _blockPortlets(context, 'plone.leftcolumn', CONTEXT_CATEGORY, True)

    left['navtree'] = worknav.Assignment()
Пример #9
0
    def propagatePortlets(self):
        """ propagates the portlet config from context to the language versions """
        context = Acquisition.aq_inner(self.context)
        path = "/".join(context.getPhysicalPath())
        left = assignment_mapping_from_key(context, 'plone.leftcolumn',
                                           CONTEXT_CATEGORY, path)
        right = assignment_mapping_from_key(context, 'plone.rightcolumn',
                                            CONTEXT_CATEGORY, path)
        belowcontext = assignment_mapping_from_key(
            context, 'osha.belowcontent.portlets', CONTEXT_CATEGORY, path)

        def _setter(ob, *args, **kw):
            results = []
            cleft = kw['cleft']
            cright = kw['cright']
            cbelowcontext = kw['cbelowcontext']

            if ob.getCanonical() == ob:
                return
            if ob.portal_type == 'LinguaLink':
                return
            path = "/".join(ob.getPhysicalPath())
            left = assignment_mapping_from_key(ob, 'plone.leftcolumn',
                                               CONTEXT_CATEGORY, path)
            right = assignment_mapping_from_key(ob, 'plone.rightcolumn',
                                                CONTEXT_CATEGORY, path)
            belowcontext = assignment_mapping_from_key(
                ob, 'osha.belowcontent.portlets', CONTEXT_CATEGORY, path)

            for x in list(left.keys()):
                del left[x]
            for x in list(cleft.keys()):
                left[x] = cleft[x]

            for x in list(right.keys()):
                del right[x]
            for x in list(cright.keys()):
                right[x] = cright[x]

            for x in list(belowcontext.keys()):
                del belowcontext[x]
            for x in list(cbelowcontext.keys()):
                belowcontext[x] = cbelowcontext[x]

        return self._forAllLangs(_setter,
                                 cleft=left,
                                 cright=right,
                                 cbelowcontext=belowcontext)
Пример #10
0
    def get_assignments(self):
        """ Return dashboard settings for a given group or a user """

        userids = self._get_memberids_from_request()
        site = getUtility(ISiteRoot)

        user2dash = list()
        for userid in userids:
            # iterate over the four portlet managers in each user dashboard
            dash2portlets = list()
            found = False
            for i in range(1, 5):
                # get hold of the user dashboard manager
                manager_name = 'plone.dashboard%d' % i
                manager = getUtility(IPortletManager, name=manager_name)
                mapping = assignment_mapping_from_key(site, 
                                                      manager_name,
                                                      category='user', 
                                                      key=userid, 
                                                      create=True)
                portlets = list()
                for portlet_id in mapping:
                    assignment = mapping[portlet_id]
                    parameters = dict([(k,v) for k,v in assignment.__dict__.items() if not k.startswith('_')])
                    portlets.append(dict(portlet_id=portlet_id, 
                                         assignment=assignment,
                                         parameters=parameters))
                    found = True

                dash2portlets.append(dict(manager=manager_name, portlets=portlets))
            user2dash.append(dict(userid=userid, dashboards=dash2portlets, hasDashboard=found))

        return user2dash
Пример #11
0
    def remove_assignments(self):
        """ Remove a list of portlets from user dashboards """

        site = getUtility(ISiteRoot)
        for id in self.request.form.get('ids', []):
            # id = 'user=XXXX::manager=YYYY:portlet=ZZZZ'
            items = id.split('::')
            userid = items[0].split('=')[-1]
            portlet_manager_name = items[1].split('=')[-1]
            portlet_id = items[2].split('=')[-1]

            # get hold of the user dashboard manager
            portlet_manager = getUtility(IPortletManager, name=portlet_manager_name)
            mapping = assignment_mapping_from_key(site, 
                                                  portlet_manager_name,
                                                  category='user', 
                                                  key=userid, 
                                                  create=False)
            del mapping[portlet_id]
            mapping._p_changed = True

        self.context.plone_utils.addPortalMessage((u'label_portlets_removed_from_dashboard',
                                                    u'Portlets removed from user dashboard(s)'))

        url = '%s/@@view-assignments?userid=%s&group=%s' % (self.context.absolute_url(),
                self.request.get('userid', ''), self.request.get('group', ''))
        return self.request.response.redirect(url)
    def __call__(self):
        """ We look for the weight score and the portlet hash,
            if we have neither than we return an error message """
        request = self.request
        weight = request.get('weight', None)
        portlethash = request.get('portlethash', None)
        try:
            weight = int(weight)
        except ValueError:
            err = 'Error: You must enter an integer for the portlet weight'
            return self.weighted_message(err)
        if not portlethash:
            return self.weighted_message('Error saving data.')

        info = unhashPortletInfo(portlethash)
        # key needs to be converted to str as unicode paths are not accepted
        # in restrictedTraverse called in assignment_mapping_from_key
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'].encode('utf-8'))
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        name = info['name']
        if not hasattr(assignments[name], ATTR):
            setattr(assignments[name], ATTR, PersistentDict())
        getattr(assignments[name], ATTR)['weight'] = weight
        return ''
Пример #13
0
    def url(self):
        """
        Return the url to the main FOP site for this member state

        This is set on the canonical member state only
        """
        context = self.context
        request = self.request
        osha_view = getMultiAdapter((context, request), name=u'oshaview')
        subsite_root = context.restrictedTraverse(osha_view.subsiteRootPath())

        # if the context isn't a subsite then subsite_root will be the
        # portal root
        if not ISubsiteEnhanced.providedBy(subsite_root):
            return

        canonical_member_state = subsite_root.getCanonical()
        try:
            right_portlets = assignment_mapping_from_key(
                canonical_member_state, 'plone.rightcolumn', CONTEXT_CATEGORY,
                "/".join(canonical_member_state.getPhysicalPath())
                )
        except ComponentLookupError:
            return
        if "fop-main-site" in right_portlets.keys():
            return right_portlets["fop-main-site"].url
Пример #14
0
    def spm_move_portlet_down(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        portal_state = getMultiAdapter((self.context, self.request),
                                       name=u'plone_portal_state')
        portal = portal_state.portal()
        #        manager = getUtility(IPortletManager, name=info['manager'], context=portal)
        manager = getUtility(IPortletManager, name=info['manager'])
        listhashes = manager.listAllManagedPortlets
        retriever = getMultiAdapter((self.context, manager),
                                    ISolgemaPortletManagerRetriever)
        managedPortletsHashes = [
            a['hash'] for a in retriever.getManagedPortlets()
        ]

        if portlethash in listhashes:
            hashAfter = managedPortletsHashes[
                managedPortletsHashes.index(portlethash) + 1]
            listhashes.remove(portlethash)
            listhashes.insert(listhashes.index(hashAfter) + 1, portlethash)
            manager.listAllManagedPortlets = listhashes
        else:
            manager.listAllManagedPortlets = listhashes.append(portlethash)

        return self._render_column(info, viewname)
Пример #15
0
    def spm_stop_portlet(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        portlethash = self.request.get('hereurl')
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        assigned = ISolgemaPortletAssignment(assignments[info['name']])
        if getattr(assigned, 'stopUrls',
                   None) and len(getattr(assigned, 'stopUrls', [])) > 0:
            urls = assigned.stopUrls
            li = []
            added = False
            for url in urls:
                if hereurl in url and not added:
                    li.append(hereurl)
                    added = True
                else:
                    li.append(url)
            if not added:
                li.append(hereurl)
            assigned.stopUrls = li
        else:
            assigned.stopUrls = [hereurl]
        return self._render_column(info, viewname)
Пример #16
0
    def remove_assignments(self):
        """ Remove a list of portlets from user dashboards """

        site = getUtility(ISiteRoot)
        for id in self.request.form.get('ids', []):
            # id = 'user=XXXX::manager=YYYY:portlet=ZZZZ'
            items = id.split('::')
            userid = items[0].split('=')[-1]
            portlet_manager_name = items[1].split('=')[-1]
            portlet_id = items[2].split('=')[-1]

            # get hold of the user dashboard manager
            portlet_manager = getUtility(IPortletManager,
                                         name=portlet_manager_name)
            mapping = assignment_mapping_from_key(site,
                                                  portlet_manager_name,
                                                  category='user',
                                                  key=userid,
                                                  create=False)
            del mapping[portlet_id]
            mapping._p_changed = True

        self.context.plone_utils.addPortalMessage(
            (u'label_portlets_removed_from_dashboard',
             u'Portlets removed from user dashboard(s)'))

        url = '%s/@@view-assignments?userid=%s&group=%s' % (
            self.context.absolute_url(), self.request.get(
                'userid', ''), self.request.get('group', ''))
        return self.request.response.redirect(url)
Пример #17
0
    def propagatePortlets(self):
        """ propagates the portlet config from context to the language versions
        """

        context = Acquisition.aq_inner(self.context)
        path = "/".join(context.getPhysicalPath())

        managers = dict()
        for managername in self.getPortletManagerNames():
            managers[managername] = assignment_mapping_from_key(context, managername, CONTEXT_CATEGORY, path)

        def _setter(ob, *args, **kw):
            results = []
            canmanagers = kw["managers"]

            if ob.getCanonical() == ob:
                return
            if ob.portal_type == "LinguaLink":
                return
            path = "/".join(ob.getPhysicalPath())

            for canmanagername, canmanager in canmanagers.items():
                manager = assignment_mapping_from_key(ob, canmanagername, CONTEXT_CATEGORY, path)
                for x in list(manager.keys()):
                    del manager[x]
                for x in list(canmanager.keys()):
                    manager[x] = canmanager[x]

        return self._forAllLangs(_setter, managers=managers)
 def all_herited_portlets(self):
     """get herited portlets"""
     portal = self.portal_state.portal()
     manager = self.manager
     retriever = self.getRetriever()
     rportlets = retriever.getManagedPortlets()
     for rportlet in rportlets:
         name = rportlet['assignment'].__name__
         portlet_context = portal.restrictedTraverse(rportlet['key'][1:len(rportlet['key'])], default=None)
         editview = queryMultiAdapter((rportlet['assignment'], self.request), name='edit', default=None)
         if editview is None or rportlet['category'] != CONTEXT_CATEGORY:
             editviewName = ''
         else:
             editviewName = '%s/%s/edit' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         visibility = rportlet['hash'] in self.visible_portlets_hash() and 'portlet_visible' or 'portlet_hidden'
         visibility += rportlet['hash'] in self.context_portlets_hash() and ' portlet_here' or ''
         assignments = assignment_mapping_from_key(self.context, self.manager.__name__, rportlet['category'], rportlet['key'])
         rportlet['title'] = rportlet['assignment'].title
         rportlet['visibility'] = visibility
         rportlet['editview'] = editviewName
         rportlet['up_url'] = '%s/@@spm-move-portlet-up?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['down_url'] = '%s/@@spm-move-portlet-down?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['delete_url'] = '%s/@@spm-delete-portlet?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['stop_url'] = '%s/@@spm-stop-portlet?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['allow_url'] = '%s/@@spm-allow-portlet?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['left_url'] = '%s/@@spm-left-portlet?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['right_url'] = '%s/@@spm-right-portlet?name=%s' % (self.context_baseUrl(rportlet['key'], rportlet['category']), name)
         rportlet['canDelete'] = rportlet['category'] == CONTEXT_CATEGORY and True or False
         rportlet['manager_name'] = self.manager.__name__
     return rportlets
Пример #19
0
    def testManagerPurge(self):
        context = DummyImportContext(self.portal, purge=False)
        context._files['portlets.xml'] = """<?xml version="1.0"?>
            <portlets>
                <portletmanager
                    name="test.testcolumn"
                    purge="True"
                    />
            </portlets>
        """
        importPortlets(context)

        self.assertRaises(KeyError,
                          assignment_mapping_from_key,
                          self.portal, manager_name=u"test.testcolumn",
                          category=GROUP_CATEGORY, key="Reviewers")

        self.assertRaises(KeyError,
                          assignment_mapping_from_key,
                          self.portal, manager_name=u"test.testcolumn",
                          category=CONTENT_TYPE_CATEGORY, key="Folder")

        # context assignment at the root are purged as well
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")
        self.assertEqual(0, len(mapping))
Пример #20
0
    def testAssignmentRemoval(self):
        portal_setup = self.portal.portal_setup

        # wait a bit or we get duplicate ids on import
        time.sleep(1)
        portal_setup.runAllImportStepsFromProfile('profile-plone.app.portlets:testing')

        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")

        # initally there should be no portlet7
        self.assertEqual(mapping.get('test.portlet7', None), None)

        # now we add one
        portlet_factory = getUtility(IFactory, name='portlets.test.Test')
        assignment = portlet_factory()
        mapping['test.portlet7'] = assignment

        # make sure it's there
        self.assertNotEqual(mapping.get('test.portlet7', None), None)

        # wait a bit or we get duplicate ids on import
        time.sleep(1)
        # run the profile
        portal_setup.runAllImportStepsFromProfile('profile-plone.app.portlets:testing')

        # and should have got rid of it again
        self.assertEqual(mapping.get('test.portlet7', None), None)
Пример #21
0
    def spm_left_portlet(self, portlethash, viewname):
        portal_state = getMultiAdapter((self.context, self.context.REQUEST), name=u'plone_portal_state')
        portal = portal_state.portal()
        info = unhashPortletInfo(portlethash)

        assignments = assignment_mapping_from_key(self.context, 
                        info['manager'], info['category'], info['key'])
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        if info['category'] == 'context':
            context = portal.restrictedTraverse(info['key'])
            leftColumn = getUtility(IPortletManager, name=u'plone.leftcolumn', context=context)
            left = getMultiAdapter((context, leftColumn,), IPortletAssignmentMapping, context=context)
            left[info['name']] = assignments[info['name']]
        else:
            rightcolumn = getUtility(IPortletManager, name=u'plone.rightcolumn')
            leftcolumn = getUtility(IPortletManager, name=u'plone.leftcolumn')
            oldcategory = rightcolumn[ info['category'] ]
            oldstorage = oldcategory[ info['key'] ]
            portlet = oldstorage[ info['name'] ]
            newcategory = leftcolumn[ info['category'] ]
            newstorage = newcategory[ info['key'] ]
            newstorage[ info['name'] ] = portlet

        del assignments[info['name']]
        return self._render_both_column(info, viewname)
Пример #22
0
    def test_portlet_displays_attachments(self):
        portal = self.layer['portal']

        mapping = assignment_mapping_from_key(portal,
            manager_name=u"plone.rightcolumn", category=CONTENT_TYPE_CATEGORY, key="Document")

        setRoles(portal, TEST_USER_ID, ('Manager',))
        portal.invokeFactory('Folder', 'dinosaurs', title=u"All about dinosaurs")
        folder = portal['dinosaurs']
        folder.invokeFactory('Document', 'dinosaurs', title=u"All about dinosaurs")
        folder.invokeFactory('File', 'tyrannosaurus.pdf', title=u"Tyrannosaurus Full Report")
        folder.invokeFactory('File', 'stegosaurus.pdf', title=u"Stegosaurus Information Pack")
        document = folder['dinosaurs']
        folder.setDefaultPage('dinosaurs')
        file1 = folder['tyrannosaurus.pdf']
        file2 = folder['stegosaurus.pdf']
        file1.setExcludeFromNav(True)
        file1.reindexObject()
        file2.setExcludeFromNav(True)
        file2.reindexObject()
        setRoles(portal, TEST_USER_ID, ('Member',))

        context = document
        request = document.REQUEST
        view = document.restrictedTraverse('@@plone')
        manager = getUtility(IPortletManager, name='plone.rightcolumn', context=portal)
        assignment = mapping[u'attachments']
        renderer = getMultiAdapter((context, request, view, manager, assignment), IPortletRenderer)

        html = renderer.render()
        self.failIf('All about dinosaurs' in html)
        self.failUnless('Tyrannosaurus Full Report' in html)
        self.failUnless('Stegosaurus Information Pack' in html)
    def __call__(self):
        """ We look for the weight score and the portlet hash,
            if we have neither than we return an error message """
        request = self.request
        weight = request.get('weight', None)
        portlethash = request.get('portlethash', None)
        try:
            weight = int(weight)
        except ValueError:
            err = 'Error: You must enter an integer for the portlet weight'
            return self.weighted_message(err)
        if not portlethash:
            return self.weighted_message('Error saving data.')

        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        name = info['name']
        if not hasattr(assignments[name], ATTR):
            setattr(assignments[name], ATTR, PersistentDict())
        getattr(assignments[name], ATTR)['weight'] = weight
        return self.weighted_message('Weighting saved')
Пример #24
0
    def block_portlets(self, action):
        status = IStatusMessage(self.request)
        context = Acquisition.aq_inner(self.context)
        data, error = self.extractData()
        portlet_manager = data.get('portlet_manager', None)
        blockstatus = data.get('blockstatus', False)

        manager = data.get('portlet_manager', None)
        path = "/".join(context.getPhysicalPath())

        if manager is not None:
            managernames = [manager]
        else:
            managernames = utils.get_portlet_manager_names()

        status.addStatusMessage(u'Set portlet block status on %s' % ', '.join(
            managernames), type='info')
        managers = dict()
        for managername in managernames:
            managers[managername] = assignment_mapping_from_key(
                                            context,
                                            managername,
                                            CONTEXT_CATEGORY,
                                            path,
                                            )

        info, warnings, errors = utils.exec_for_all_langs(
                                                    context,
                                                    utils.block_portlets,
                                                    managers=managers,
                                                    blockstatus=blockstatus,
                                                    )

        self.handle_status(status, info, warnings, errors)
Пример #25
0
    def test_portlet_installed(self):
        portal = self.layer['portal']

        mapping = assignment_mapping_from_key(portal,
            manager_name=u"plone.rightcolumn", category=CONTENT_TYPE_CATEGORY, key="Document")

        self.assertEquals(1, len(mapping))
Пример #26
0
def remove_dashboards(self):
    ptool = getToolByName(self, 'portal_url')
    portal = ptool.getPortalObject()
    dashboards = [
        getUtility(IPortletManager, name=name) for name in [
            'plone.dashboard1', 'plone.dashboard2', 'plone.dashboard3',
            'plone.dashboard4'
        ]
    ]

    for userid in portal.Members.objectIds('ATFolder'):
        print userid
        for dashboard in dashboards:
            try:
                dashmapping = assignment_mapping_from_key(portal,
                                                          dashboard.__name__,
                                                          USER_CATEGORY,
                                                          key=userid)
            except KeyError, e:
                msg = "Cannot find the portlet mapping for %s: %s" % (userid,
                                                                      e)
                print msg
                log.info(msg)
                continue
            dashportlets = [x for x in dashmapping.keys()]
            dashmapping._data.clear()
            dashmapping._p_changed = True
            dashmapping._data._p_changed = True
        transaction.commit()
Пример #27
0
def fixDEPortlets(self):
    path = '/osha/portal/fop/germany'
    cat = self.portal_catalog
    portletManager = getUtility(IPortletManager, name='plone.rightcolumn')
    res = cat(path=path, Language='all', portal_type="RichDocument")

    for r in res:
        try:
            ob = r.getObject()
        except:
            print "Err in getObject, skipping"
            pass
        path = "/".join(ob.getPhysicalPath())
        right = assignment_mapping_from_key(ob, 'plone.rightcolumn',
                                            CONTEXT_CATEGORY, path)
        assignable = getMultiAdapter((
            ob,
            portletManager,
        ), ILocalPortletAssignmentManager)
        portlets = [x for x in list(right.keys())]
        if portlets != ['portlet_themenbezogen', 'portlet_oshsearch'
                        ] and portlets != []:
            print "abweichende portlets auf %s: %s" % (r.getURL(), portlets)
            pass
        for k in portlets:
            del right[k]
        assignable.setBlacklistStatus(CONTEXT_CATEGORY, False)

    return len(res)
Пример #28
0
def exchangeSEPPortlets(self, key):
    portlet_name = u'sep_publications'

    path = '/'.join(self.getPhysicalPath())

    portal = self.portal_url.getPortalObject()
    portal_path = self.portal_url.getPortalPath()
    langs = portal.portal_languages.getSupportedLanguages()

    right = assignment_mapping_from_key(self, 'plone.rightcolumn',
                                        CONTEXT_CATEGORY, path)
    print right.keys()
    from osha.theme.portlets import oshcollection as collection_portlet

    if right.has_key(portlet_name):
        topic_path = right.get(portlet_name).target_collection
        del right[portlet_name]
    else:
        topic_path = "%s/directory/%s/Publication" % (portal_path, key)
    right[portlet_name] = collection_portlet.Assignment(
        header=_(u"legend_publications"),
        target_collection=topic_path,
        limit=5)

    return "ok"
Пример #29
0
def remove_dashboards(self):
    ptool = getToolByName(self, 'portal_url')
    portal = ptool.getPortalObject()
    dashboards = [
        getUtility(IPortletManager, name=name) for name in
        ['plone.dashboard1', 'plone.dashboard2', 'plone.dashboard3',
         'plone.dashboard4']]

    for userid in portal.Members.objectIds('ATFolder'):
        print userid
        for dashboard in dashboards:
            try:
                dashmapping = assignment_mapping_from_key(
                    portal, dashboard.__name__, USER_CATEGORY, key=userid)
            except KeyError, e:
                msg = "Cannot find the portlet mapping for %s: %s" %(
                    userid, e)
                print msg
                log.info(msg)
                continue
            dashportlets = [x for x in dashmapping.keys()]
	    dashmapping._data.clear()
	    dashmapping._p_changed = True
	    dashmapping._data._p_changed = True
	transaction.commit()
Пример #30
0
    def spm_move_portlet_down(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context, 
                        info['manager'], info['category'], info['key'])
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state')
        portal = portal_state.portal()
#        manager = getUtility(IPortletManager, name=info['manager'], context=portal)
        manager = getUtility(IPortletManager, name=info['manager'])
        listhashes = manager.listAllManagedPortlets
        retriever = getMultiAdapter((self.context, manager), ISolgemaPortletManagerRetriever)
        managedPortletsHashes = [a['hash'] for a in retriever.getManagedPortlets()]

        if portlethash in listhashes:
            hashAfter = managedPortletsHashes[managedPortletsHashes.index(portlethash)+1]
            listhashes.remove(portlethash)
            listhashes.insert(listhashes.index(hashAfter)+1, portlethash)
            manager.listAllManagedPortlets = listhashes
        else:
            manager.listAllManagedPortlets = listhashes.append(portlethash)

        return self._render_column(info, viewname)
Пример #31
0
 def spm_stop_portlet(self):
     portlethash = self.request.get('portlethash')
     portlethash = self.request.get('viewname')
     portlethash = self.request.get('hereurl')
     info = unhashPortletInfo(portlethash)
     assignments = assignment_mapping_from_key(self.context, 
                     info['manager'], info['category'], info['key'])
                     
     IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
     assigned = ISolgemaPortletAssignment(assignments[info['name']])
     if getattr(assigned, 'stopUrls', None) and len(getattr(assigned, 'stopUrls', [])) > 0:
         urls = assigned.stopUrls
         li = []
         added = False
         for url in urls:
             if hereurl in url and not added:
                 li.append(hereurl)
                 added = True
             else:
                 li.append(url)
         if not added:
             li.append(hereurl)
         assigned.stopUrls = li
     else:
         assigned.stopUrls = [hereurl]
     return self._render_column(info, viewname)
Пример #32
0
 def testAssignmentCreatedAndOrdered(self):
     mapping = assignment_mapping_from_key(self.portal,
                                           manager_name=u"test.testcolumn",
                                           category=CONTEXT_CATEGORY,
                                           key="/")
     self.assertEquals(3, len(mapping))
     self.assertEquals(['test.portlet3', 'test.portlet2', 'test.portlet1'],
                       list(mapping.keys()))
Пример #33
0
 def getPortletEditUrl(self):
     utool = getToolByName(self.context, "portal_url")
     site = utool.getPortalObject()
     mapping = assignment_mapping_from_key(site, "plone.rightcolumn", "context", "/", create=True)
     name = "megaphone_%s" % self.context.UID()
     assignment = mapping.get(name, None)
     if assignment is not None:
         return "%s/++contextportlets++plone.rightcolumn/%s/edit" % (site.absolute_url(), name)
Пример #34
0
    def delete_portlet(self, portlethash, viewname):
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                        info['manager'], info['category'], info['key'])

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        del assignments[info['name']]
        return self._render_column(info, viewname)
 def all_herited_portlets(self):
     """get herited portlets"""
     portal_state = getMultiAdapter((self.context, self.request),
                                    name=u'plone_portal_state')
     portal = portal_state.portal()
     manager = self.manager
     retriever = self.getRetriever()
     rportlets = retriever.getManagedPortlets()
     for rportlet in rportlets:
         name = rportlet['assignment'].__name__
         portlet_context = portal.restrictedTraverse(
             rportlet['key'][1:len(rportlet['key'])], default=None)
         editview = queryMultiAdapter(
             (rportlet['assignment'], self.request),
             name='edit',
             default=None)
         if editview is None or rportlet['category'] != CONTEXT_CATEGORY:
             editviewName = ''
         else:
             editviewName = '%s/%s/edit' % (self.context_baseUrl(
                 rportlet['key'], rportlet['category']), name)
         visibility = rportlet['hash'] in self.visible_portlets_hash(
         ) and 'portlet_visible' or 'portlet_hidden'
         visibility += rportlet['hash'] in self.context_portlets_hash(
         ) and ' portlet_here' or ''
         assignments = assignment_mapping_from_key(self.context,
                                                   self.manager.__name__,
                                                   rportlet['category'],
                                                   rportlet['key'])
         rportlet['title'] = rportlet['assignment'].title
         rportlet['visibility'] = visibility
         rportlet['editview'] = editviewName
         rportlet['up_url'] = '%s/@@spm-move-portlet-up?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['down_url'] = '%s/@@spm-move-portlet-down?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['delete_url'] = '%s/@@spm-delete-portlet?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['stop_url'] = '%s/@@spm-stop-portlet?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['allow_url'] = '%s/@@spm-allow-portlet?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['left_url'] = '%s/@@spm-left-portlet?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['right_url'] = '%s/@@spm-right-portlet?name=%s' % (
             self.context_baseUrl(rportlet['key'],
                                  rportlet['category']), name)
         rportlet['canDelete'] = rportlet[
             'category'] == CONTEXT_CATEGORY and True or False
         rportlet['manager_name'] = self.manager.__name__
     return rportlets
Пример #36
0
    def test_portlet_installed(self):
        portal = self.layer['portal']

        mapping = assignment_mapping_from_key(
            portal,
            manager_name=u"plone.rightcolumn",
            category=CONTENT_TYPE_CATEGORY,
            key="Document")

        self.assertEquals(1, len(mapping))
Пример #37
0
    def testAssignmentSettings(self):
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")
        assignment = mapping['test.portlet1']
        settings = IPortletAssignmentSettings(assignment)
        self.assertTrue(settings.get('visible', True))

        assignment = mapping['test.portlet2']
        settings = IPortletAssignmentSettings(assignment)
        self.assertFalse(settings.get('visible', True))
Пример #38
0
def _add_portlets(obj, events_topic, news_topic, lang):
    log.info('_add_portlets for language %s' % lang)
    path = "/".join(obj.getPhysicalPath())
    oshabelow = assignment_mapping_from_key(obj, 'osha.belowcontent.portlets', CONTEXT_CATEGORY, path)

    events_topic_path = "/".join(events_topic.getPhysicalPath())
    news_topic_path = "/".join(news_topic.getPhysicalPath())

    translate = getTranslationService().translate
    news_trans = translate(
                        target_language=lang, 
                        msgid=u'News', 
                        default=u'News', 
                        context=obj, 
                        domain='plone'
                        )
    oshabelow[u'news-collection'] = collection.Assignment(
                                        header=news_trans,
                                        target_collection=news_topic_path,
                                        limit=5,
                                        )

    events_trans = translate(
                        target_language=lang, 
                        msgid=u'Events', 
                        default=u'Events', 
                        context=obj, 
                        domain='plone'
                        )
    oshabelow[u'events-collection'] = collection.Assignment(
                                        header=events_trans,
                                        target_collection=events_topic_path,
                                        limit=5,
                                        )

    rightcolumn_manager = component.getUtility(
                    IPortletManager,
                    name=u'plone.rightcolumn',
                    context=obj
                    )

    rightcolumn = component.getMultiAdapter(
                            (obj, rightcolumn_manager),
                            IPortletAssignmentMapping, context=obj
                            )

    rightcolumn[u'activities'] = osha_portlets.image.Assignment(
                                        header=u"Agency's Activities",
                                        image="/en/press/photos/banners/hw_08_banner/hwp_%s.swf" % lang,
                                        url="/%s/campaigns/hw2008/" % lang,
                                        width="167",
                                        height="74",
                                        )

    rightcolumn[u'links'] = osha_portlets.network_member_links.Assignment()
Пример #39
0
    def push_assignment(self):
        """ Push all assignment portlet page assignment into the
            dashboard of a user or a group of users.
        """

        userids = self._get_memberids_from_request()
        if not userids:
            self.context.plone_utils.addPortalMessage(u'No members found',
                                                      'error')
            url = '%s/@@assignments?userid=%s&group=%s' % (
                self.context.absolute_url(), self.request.get(
                    'userid', ''), self.request.get('group', ''))
            return self.request.response.redirect(url)

        dashboards_updated = dict()
        site = getUtility(ISiteRoot)
        for userid in userids:

            # iterate over all configured portlet managers (1-4) for PortletPage
            for i in range(1, 5):

                manager_name = 'vs.dashboardmanager.column%d' % i
                manager = getUtility(IPortletManager,
                                     name=manager_name,
                                     context=self.context)
                mapping = getMultiAdapter((self.context, manager),
                                          IPortletAssignmentMapping)

                # get hold of the user dashboard manager
                manager2 = getUtility(IPortletManager,
                                      name='plone.dashboard%d' % i)
                mapping2 = assignment_mapping_from_key(site,
                                                       'plone.dashboard%d' % i,
                                                       category='user',
                                                       key=userid,
                                                       create=True)

                ids2 = [tp[0] for tp in mapping2.items()]

                # and copy over the assignments
                for id, assignment in mapping.items():
                    assignment_copy = assignment._getCopy(assignment)
                    if not id in ids2:
                        mapping2[id] = assignment_copy
                        LOG.info('assigned portlet %s to %s' % (id, userid))
                        dashboards_updated[userid] = True

        if dashboards_updated:
            self.context.plone_utils.addPortalMessage(
                u'Dashboard(s) updated for members: %s' %
                ', '.join(dashboards_updated.keys()))
        else:
            self.context.plone_utils.addPortalMessage(u'No dashboards updated')
        return self.request.response.redirect(self.context.absolute_url())
Пример #40
0
 def all_herited_portlets(self):
     """get herited portlets"""
     portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
     portal = portal_state.portal()
     manager = self.manager
     retriever = self.getRetriever()
     rportlets = retriever.getManagedPortlets()
     for rportlet in rportlets:
         name = rportlet["assignment"].__name__
         portlet_context = portal.restrictedTraverse(rportlet["key"][1 : len(rportlet["key"])], default=None)
         editview = queryMultiAdapter((rportlet["assignment"], self.request), name="edit", default=None)
         if editview is None or rportlet["category"] != CONTEXT_CATEGORY:
             editviewName = ""
         else:
             editviewName = "%s/%s/edit" % (self.context_baseUrl(rportlet["key"], rportlet["category"]), name)
         visibility = rportlet["hash"] in self.visible_portlets_hash() and "portlet_visible" or "portlet_hidden"
         visibility += rportlet["hash"] in self.context_portlets_hash() and " portlet_here" or ""
         assignments = assignment_mapping_from_key(
             self.context, self.manager.__name__, rportlet["category"], rportlet["key"]
         )
         rportlet["title"] = rportlet["assignment"].title
         rportlet["visibility"] = visibility
         rportlet["editview"] = editviewName
         rportlet["up_url"] = "%s/@@spm-move-portlet-up?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["down_url"] = "%s/@@spm-move-portlet-down?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["delete_url"] = "%s/@@spm-delete-portlet?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["stop_url"] = "%s/@@spm-stop-portlet?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["allow_url"] = "%s/@@spm-allow-portlet?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["left_url"] = "%s/@@spm-left-portlet?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["right_url"] = "%s/@@spm-right-portlet?name=%s" % (
             self.context_baseUrl(rportlet["key"], rportlet["category"]),
             name,
         )
         rportlet["canDelete"] = rportlet["category"] == CONTEXT_CATEGORY and True or False
         rportlet["manager_name"] = self.manager.__name__
     return rportlets
Пример #41
0
    def _create_portlet(self, site, manager, name, type_):
        category = 'context'
        key = '/'
        mapping = assignment_mapping_from_key(
            site, manager, category, key, create=True)

        if name in mapping:
            del mapping[name]

        assignment = getUtility(IFactory, name=type_)()
        mapping[name] = assignment
        return assignment.__of__(site)
Пример #42
0
    def _get_assignment_mapping(self):
        membership_tool = getToolByName(self.context, "portal_membership")
        member = membership_tool.getAuthenticatedMember()

        if not member.getId():
            raise Exception("Could not find userid.")

        userid = member.getId()

        return assignment_mapping_from_key(
            context=self.context, manager_name="plone.dashboard1", category=USER_CATEGORY, key=userid, create=True
        )
Пример #43
0
    def toggle_visibility(self, portlethash, viewname):
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                        info['manager'], info['category'], info['key'])

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        assignment = assignments[info['name']]
        settings = IPortletAssignmentSettings(assignment)
        visible = settings.get('visible', True)
        settings['visible'] = not visible
        return self._render_column(info, viewname)
Пример #44
0
def copyPortletsFromParent(self, doleft=False, doright=False):
    out = StringIO()
    parent = Acquisition.aq_parent(Acquisition.aq_inner(self))
    ppath = "/".join(parent.getPhysicalPath())
    pleft = assignment_mapping_from_key(parent, 'plone.leftcolumn',
                                        CONTEXT_CATEGORY, ppath)
    pright = assignment_mapping_from_key(parent, 'plone.rightcolumn',
                                         CONTEXT_CATEGORY, ppath)

    ob = Acquisition.aq_inner(self)
    out.write("Copying portlets from parent %s to here %s\n" %
              (parent.absolute_url(), ob.absolute_url()))
    path = "/".join(ob.getPhysicalPath())
    left = assignment_mapping_from_key(ob, 'plone.leftcolumn',
                                       CONTEXT_CATEGORY, path)
    right = assignment_mapping_from_key(ob, 'plone.rightcolumn',
                                        CONTEXT_CATEGORY, path)

    if doleft:
        out.write('Copied left portlets\n')
        for x in list(left.keys()):
            del left[x]
        for x in list(pleft.keys()):
            left[x] = pleft[x]
    else:
        out.write('Left portlets NOT copied\n')

    if doright:
        out.write('Copied right portlets\n')
        for x in list(right.keys()):
            del right[x]
        for x in list(pright.keys()):
            right[x] = pright[x]
    else:
        out.write('Right portlets NOT copied\n')

    return out.getvalue()
Пример #45
0
def _add_portlets(obj, events_topic, news_topic, lang):
    log.info('_add_portlets for language %s' % lang)
    path = "/".join(obj.getPhysicalPath())
    oshabelow = assignment_mapping_from_key(obj, 'osha.belowcontent.portlets',
                                            CONTEXT_CATEGORY, path)

    events_topic_path = "/".join(events_topic.getPhysicalPath())
    news_topic_path = "/".join(news_topic.getPhysicalPath())

    translate = getTranslationService().translate
    news_trans = translate(target_language=lang,
                           msgid=u'News',
                           default=u'News',
                           context=obj,
                           domain='plone')
    oshabelow[u'news-collection'] = collection.Assignment(
        header=news_trans,
        target_collection=news_topic_path,
        limit=5,
    )

    events_trans = translate(target_language=lang,
                             msgid=u'Events',
                             default=u'Events',
                             context=obj,
                             domain='plone')
    oshabelow[u'events-collection'] = collection.Assignment(
        header=events_trans,
        target_collection=events_topic_path,
        limit=5,
    )

    rightcolumn_manager = component.getUtility(IPortletManager,
                                               name=u'plone.rightcolumn',
                                               context=obj)

    rightcolumn = component.getMultiAdapter((obj, rightcolumn_manager),
                                            IPortletAssignmentMapping,
                                            context=obj)

    rightcolumn[u'activities'] = osha_portlets.image.Assignment(
        header=u"Agency's Activities",
        image="/en/press/photos/banners/hw_08_banner/hwp_%s.swf" % lang,
        url="/%s/campaigns/hw2008/" % lang,
        width="167",
        height="74",
    )

    rightcolumn[u'links'] = osha_portlets.network_member_links.Assignment()
Пример #46
0
def setupPortletAt(portal, portlet_type, manager, path, name="", **kw):
    """
    setupPortletAt(portal, 'portlets.Events', 'plone.rightcolumn', '/vereinigungen/fachliche-vereinigungen/sektion-kondensierte-materie/halbleiterphysik') # noqa
    """
    portlet_factory = getUtility(IFactory, name=portlet_type)
    assignment = portlet_factory(**kw)
    mapping = assignment_mapping_from_key(
        portal, manager, CONTEXT_CATEGORY, path, create=True
    )

    if not name:
        chooser = INameChooser(mapping)
        name = chooser.chooseName(None, assignment)

    mapping[name] = assignment
Пример #47
0
    def _get_assignment_mapping(self):
        membership_tool = getToolByName(self.context, 'portal_membership')
        member = membership_tool.getAuthenticatedMember()

        if not member.getId():
            raise Exception(
                'Could not find userid.')

        userid = member.getId()

        return assignment_mapping_from_key(
            context=self.context,
            manager_name='plone.dashboard1',
            category=USER_CATEGORY,
            key=userid,
            create=True)
Пример #48
0
    def test_portlet_displays_attachments(self):
        portal = self.layer['portal']

        mapping = assignment_mapping_from_key(
            portal,
            manager_name=u"plone.rightcolumn",
            category=CONTENT_TYPE_CATEGORY,
            key="Document")

        setRoles(portal, TEST_USER_ID, ('Manager', ))
        portal.invokeFactory('Folder',
                             'dinosaurs',
                             title=u"All about dinosaurs")
        folder = portal['dinosaurs']
        folder.invokeFactory('Document',
                             'dinosaurs',
                             title=u"All about dinosaurs")
        folder.invokeFactory('File',
                             'tyrannosaurus.pdf',
                             title=u"Tyrannosaurus Full Report")
        folder.invokeFactory('File',
                             'stegosaurus.pdf',
                             title=u"Stegosaurus Information Pack")
        document = folder['dinosaurs']
        folder.setDefaultPage('dinosaurs')
        file1 = folder['tyrannosaurus.pdf']
        file2 = folder['stegosaurus.pdf']
        file1.setExcludeFromNav(True)
        file1.reindexObject()
        file2.setExcludeFromNav(True)
        file2.reindexObject()
        setRoles(portal, TEST_USER_ID, ('Member', ))

        context = document
        request = document.REQUEST
        view = document.restrictedTraverse('@@plone')
        manager = getUtility(IPortletManager,
                             name='plone.rightcolumn',
                             context=portal)
        assignment = mapping[u'attachments']
        renderer = getMultiAdapter(
            (context, request, view, manager, assignment), IPortletRenderer)

        html = renderer.render()
        self.failIf('All about dinosaurs' in html)
        self.failUnless('Tyrannosaurus Full Report' in html)
        self.failUnless('Stegosaurus Information Pack' in html)
    def change_portlet_weight(self, portlethash, viewname, weight):
        try:
            weight = int(weight)
        except ValueError:
            return self._render_column()

        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(
            self.context, info['manager'], info['category'], info['key']
        )

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        name = info['name']
        if not hasattr(assignments[name], ATTR):
            setattr(assignments[name], ATTR, PersistentDict())
        getattr(assignments[name], ATTR)['weight'] = weight
        return "done"
Пример #50
0
    def testAssignmentPropertiesSet(self):
        mapping = assignment_mapping_from_key(self.portal,
            manager_name=u"test.testcolumn", category=CONTEXT_CATEGORY, key="/")

        assignment = mapping['test.portlet1']
        self.assertEqual(u'Test pr\xf6p 1', assignment.test_text)
        self.assertEqual(False, assignment.test_bool)
        self.assertEqual((u'published', u'private'), assignment.test_tuple)

        assignment = mapping['test.portlet2']
        self.assertEqual('Test prop 2', assignment.test_text)
        self.assertEqual(True, assignment.test_bool)
        self.assertEqual((), assignment.test_tuple)

        assignment = mapping['test.portlet3']
        self.assertEqual(None, assignment.test_text)
        self.assertEqual(None, assignment.test_bool)
        self.assertEqual(None, assignment.test_tuple)
Пример #51
0
    def spm_allow_portlet(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        portlethash = self.request.get('hereurl')
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        li = []
        assigned = ISolgemaPortletAssignment(assignments[info['name']])
        if hasattr(assigned, 'stopUrls') and len(assigned.stopUrls) > 0:
            urls = assigned.stopUrls
            for url in urls:
                if url not in hereurl:
                    li.append(url)
        assigned.stopUrls = li
        return self._render_column(info, viewname)
Пример #52
0
    def at_post_create_script(self):
        """ create the portlet  """
        # do we have to create the portlet?
        tool = getToolByName(self, 'simpleblog_tool')
        if tool.getCreatePortletOnBlogCreation():
            portlet_mapping = assignment_mapping_from_key(
                context=self,
                manager_name=u"plone.rightcolumn",
                category="context",
                key="/".join(self.getPhysicalPath()))

            showComments = tool.getShowComments()
            showRecent = tool.getShowRecent()
            showCalendar = tool.getShowCalendar()
            showCategories = tool.getShowCategories()

            portlet_mapping[self.UID()] = simpleblogportlet.Assignment(
                showCategories=showCategories,
                showCalendar=showCalendar,
                showRecent=showRecent,
                showComments=showComments)
Пример #53
0
    def spm_delete_portlet(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        info = unhashPortletInfo(portlethash)
        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])

        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()
        portal_state = getMultiAdapter((self.context, self.request),
                                       name=u'plone_portal_state')
        portal = portal_state.portal()
        manager = getUtility(IPortletManager,
                             name=info['manager'],
                             context=portal)
        listhashes = manager.listAllManagedPortlets
        del assignments[info['name']]
        listhashes.remove(portlethash)
        manager.listAllManagedPortlets = listhashes
        return self._render_column(info, viewname)
Пример #54
0
    def get_assignments(self):
        """ Return dashboard settings for a given group or a user """

        userids = self._get_memberids_from_request()
        site = getUtility(ISiteRoot)

        user2dash = list()
        for userid in userids:
            # iterate over the four portlet managers in each user dashboard
            dash2portlets = list()
            found = False
            for i in range(1, 5):
                # get hold of the user dashboard manager
                manager_name = 'plone.dashboard%d' % i
                manager = getUtility(IPortletManager, name=manager_name)
                mapping = assignment_mapping_from_key(site,
                                                      manager_name,
                                                      category='user',
                                                      key=userid,
                                                      create=True)
                portlets = list()
                for portlet_id in mapping:
                    assignment = mapping[portlet_id]
                    parameters = dict([(k, v)
                                       for k, v in assignment.__dict__.items()
                                       if not k.startswith('_')])
                    portlets.append(
                        dict(portlet_id=portlet_id,
                             assignment=assignment,
                             parameters=parameters))
                    found = True

                dash2portlets.append(
                    dict(manager=manager_name, portlets=portlets))
            user2dash.append(
                dict(userid=userid,
                     dashboards=dash2portlets,
                     hasDashboard=found))

        return user2dash
Пример #55
0
    def spm_left_portlet(self):
        portlethash = self.request.get('portlethash')
        portlethash = self.request.get('viewname')
        portal_state = getMultiAdapter((self.context, self.request),
                                       name=u'plone_portal_state')
        portal = portal_state.portal()
        info = unhashPortletInfo(portlethash)

        assignments = assignment_mapping_from_key(self.context,
                                                  info['manager'],
                                                  info['category'],
                                                  info['key'])
        IPortletPermissionChecker(assignments.__of__(aq_inner(self.context)))()

        if info['category'] == 'context':
            context = portal.restrictedTraverse(info['key'])
            leftColumn = getUtility(IPortletManager,
                                    name=u'plone.leftcolumn',
                                    context=context)
            left = getMultiAdapter((
                context,
                leftColumn,
            ),
                                   IPortletAssignmentMapping,
                                   context=context)
            left[info['name']] = assignments[info['name']]
        else:
            rightcolumn = getUtility(IPortletManager,
                                     name=u'plone.rightcolumn')
            leftcolumn = getUtility(IPortletManager, name=u'plone.leftcolumn')
            oldcategory = rightcolumn[info['category']]
            oldstorage = oldcategory[info['key']]
            portlet = oldstorage[info['name']]
            newcategory = leftcolumn[info['category']]
            newstorage = newcategory[info['key']]
            newstorage[info['name']] = portlet

        del assignments[info['name']]
        return self._render_both_column(info, viewname)