Exemple #1
0
def render_cachekey(fun, self):
    """
    Generates a key based on:

    * Portal URL
    * Negotiated language
    * Anonymous user flag
    * Portlet manager
    * Assignment
    * URL of collection used (instead of using _data)
    
    """
    context = Acquisition.aq_inner(self.context)

    fingerprint = self.collection_url()
    anonymous = getToolByName(context, 'portal_membership').isAnonymousUser()

    key= "".join((
        getToolByName(Acquisition.aq_inner(self.context), 'portal_url')(),
        get_language(Acquisition.aq_inner(self.context), self.request),
        str(anonymous),
        self.manager.__name__,
        self.data.__name__,
        fingerprint))
    return key
Exemple #2
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()
Exemple #3
0
 def can_upload(self):
     context = Acquisition.aq_inner(self.context)
     if not context.displayContentsTab():
         return False
     obj = context
     if context.restrictedTraverse('@@plone').isDefaultPageInFolder():
         obj = Acquisition.aq_parent(Acquisition.aq_inner(obj))
     return ISeqRecordContainer.providedBy(obj)
Exemple #4
0
 def can_upload(self):
     context = Acquisition.aq_inner(self.context)
     if not context.displayContentsTab():
         return False
     obj = context
     if context.restrictedTraverse('@@plone').isDefaultPageInFolder():
         obj = Acquisition.aq_parent(Acquisition.aq_inner(obj))
     return ISeqRecordContainer.providedBy(obj)
def set_property(ob, *args, **kw):
    err = list()
    id = kw['property_id']
    value = kw['property_value']
    type_ = kw['property_type']
    if not id:
        err.append('Property id must not be empty')
    if not value:
        err.append('Property value must not be emtpy')
    if not type_:
        err.append('Property type must not be emtpy')
    if not err:
        ob = Acquisition.aq_inner(ob)
        if Acquisition.aq_base(ob).hasProperty(id):
            try:
                ob._delProperty(id)
            except:
                err.append(
                    'Could not delete existing property %s on %s'
                    % (id, kw['lang']))
        try:
            ob._setProperty(id=id, value=value, type=type_)
        except:
            err.append(
                'Could not set property %s on %s'
                % (id, "/".join(ob.getPhysicalPath())))
    return err
    def folderButtons(self):
        """ valid folder_button actions """

        return [button
                    for button in self.actionTool.listActionInfos(object=Acquisition.aq_inner(self.context))
                        if (button['category'] == 'folder_buttons') and (button['id'] != 'change_state')
                ]
    def sections(self):
        """ subtype sections in current folder """

        context = Acquisition.aq_inner(self.context)
        
        contentFilter = {'review_state':('published', 'visible',), 'portal_type' : self.subtypes()}
        return context.getFolderContents(contentFilter=contentFilter)
Exemple #8
0
 def results(self):
     """ build the query and do the search """
     context = Acquisition.aq_inner(self.context)
     portal_catalog = getToolByName(context, 'portal_catalog')
     query = self.buildQuery()
     results = portal_catalog(query)
     return results
Exemple #9
0
    def buildQuery(self):
        """ Build the query based on the request """
        context = Acquisition.aq_inner(self.context)
        query = { 'sort_on': 'effective',
                  'sort_order':'reverse',
                  'Language': ''}

                  

        ero_topic = self.request.get('ero_topic', None)
        if ero_topic:
            query.update({'ero_topic':ero_topic})

        ero_target_group = self.request.get('ero_target_group', None)
        if ero_target_group:
            query.update({'ero_target_group':ero_target_group})

        country = self.request.get('country', '')
        if country:
            query.update({'country':country})

        SearchableText = self.request.get('SearchableText', '')
        if SearchableText != '':
            query.update({'SearchableText':SearchableText})

        search_portal_types = self.search_portal_types()
        query.update(search_portal_types)

        return query
Exemple #10
0
    def search_types(self):
        """ Returns a list of translated search types to select from.
            This method is overwritten from dbfilter to provide a default
            list of types, so that all are selected initially.
        """
        context = Acquisition.aq_inner(self.context)

        default = [
                'OSH_Link', 'RALink', 'CaseStudy',
                'Provider', 'Publication', 'HelpCenterFAQ',
                'Directive', 'Modification', 'Amendment',
                'Note', 'Proposal'
                ]

        local_portal_types = context.getProperty('search_portal_types', default)
        search_portal_types = self.request.get('search_portal_types', local_portal_types)
        if not search_portal_types:
            search_portal_types = default

        TYPES = [
            ('Useful Link', 'OSH_Link', 'OSH_Link' in search_portal_types) ,
            ('Risk Assessment Tool', 'RALink', 'RALink' in search_portal_types) ,
            ('Case Study', 'CaseStudy', 'CaseStudy' in search_portal_types) ,
            ('Provider', 'Provider', 'Provider' in search_portal_types) ,
            ('Publication', 'Publication', 'Publication' in search_portal_types) ,
            ('Frequently Asked Question (FAQ)', 'HelpCenterFAQ', 'HelpCenterFAQ' in search_portal_types) ,
            ('Legislation Directive', 'Directive', 'Directive' in search_portal_types),
            ('Legislation Modification', 'Modification', 'Modification' in search_portal_types),
            ('Legislation Amendment', 'Amendment', 'Amendment' in search_portal_types),
            ('Legislation Note', 'Note', 'Note' in search_portal_types),
            ('Legislation Proposal', 'Proposal', 'Proposal' in search_portal_types)
            ]
        return TYPES
Exemple #11
0
 def getLocalObject(self, name):
     """ see interface """
     return (
         hasattr(Acquisition.aq_base(Acquisition.aq_inner(self.context)), name)
         and getattr(self.context, name)
         or None
     )
Exemple #12
0
 def upload_url(self):
     context = Acquisition.aq_inner(self.context)
     if context.restrictedTraverse('@@plone').isStructuralFolder():
         url = context.absolute_url()
     else:
         url = Acquisition.aq_parent(context).absolute_url()
     return url + '/@@load'
    def getStartHeres(self, startHereLimit=10):
        """
          returns a list of topic dicts
          [{title:topicTitle, startheres:listOfStartHeres, url:urlOfTopic, count:itemsInTopic}, ...]
          startheres are dicts {title:titleOfStartHere,url:urlOfStartHere}
          This is used in helpcenter_ploneorg3.pt.
        """

        context = Acquisition.aq_inner(self.context)

        here_url = context.absolute_url()
        phc = context.getPHCObject()

        topics = phc.getSectionsVocab()
        sections = []
        for topic in topics:
            if ':' not in topic:
                items = self.catalog(portal_type=['HelpCenterReferenceManual', 'HelpCenterTutorial', 'HelpCenterHowTo'],
                                     review_state='published',
                                     getSections=[topic])

                startHeres = []
                for item in items:
                    if item.getStartHere:
                        startHeres.append({'title': item.Title, 'url': item.getURL()})

                sections.append({
                    'title': topic,
                    'startheres': startHeres[:startHereLimit],
                    'url': here_url + '/topic/' + url_quote_plus(topic),
                    'count': len(items),
                    })

        return sections
Exemple #14
0
def _rewrap(obj):
    obj = Acquisition.aq_inner(obj)
    base = Acquisition.aq_base(obj)
    parent = Acquisition.aq_parent(obj)
    if not parent or isinstance(parent, RequestContainer):
        return base
    return base.__of__(_rewrap(parent))
Exemple #15
0
 def num_subscribers(self):
     context = Acquisition.aq_inner(self.context)
     portal_properties = getToolByName(context, "portal_properties")
     num = portal_properties.site_properties.getProperty("num_subscribers_oshmail")
     if hasattr(portal_properties.site_properties, "osha_properties"):
         num = portal_properties.site_properties.osha_properties.getProperty("num_subscribers")
     return num
Exemple #16
0
 def upload_url(self):
     context = Acquisition.aq_inner(self.context)
     if context.restrictedTraverse('@@plone').isStructuralFolder():
         url = context.absolute_url()
     else:
         url = Acquisition.aq_parent(context).absolute_url()
     return url + '/@@load'
Exemple #17
0
    def setUpWidgets(self, ignore_request=False):
        request = self.request
        if 'form.actions.save' in request:
            # Add annotated values to the request so that we see the saved
            # values on a freshly opened form.
            context = Acquisition.aq_inner(self.context).getCanonical()
            annotations = IAnnotations(context)
            for key in [PRESS_CONTACTS_KEY, FEED_KEY, KEYWORDS_KEY]:
                if annotations.get(key):
                    if key == KEYWORDS_KEY:
                        request.form['form.%s' % key] = ' '.join(
                            annotations[key])
                    elif key == PRESS_CONTACTS_KEY:
                        good_paths = list()
                        # safeguard against missing press contacts
                        for path in annotations[key]:
                            if path.startswith('/'):
                                path = path[1:]
                                try:
                                    context.restrictedTraverse(str(path))
                                    good_paths.append(path)
                                    request.form['form.%s' % key] = \
                                        annotations[key]
                                except AttributeError:
                                    pass
                        if len(good_paths) < len(annotations[key]):
                            annotations[key] = good_paths
                    else:
                        request.form['form.%s' % key] = annotations[key]

        self.adapters = {}
        self.widgets = form.setUpWidgets(
            self.form_fields, self.prefix, self.context, self.request,
            form=self, adapters=self.adapters, ignore_request=ignore_request)
    def available_translations(self, context=None):
        """ list all available translations for this publication """
        context = context or Acquisition.aq_inner(self.context)
        portal_languages = cmfutils.getToolByName(context, 'portal_languages')
        ali = portal_languages.getAvailableLanguageInformation()

        if HAVE_LINGUAPLONE:
            translations = context.getTranslations()
        else:
            translations = {context.Language(): (context, context.Language())}

        if len(translations.keys()) < 1:
            return

        lang_codes = translations.keys()
        lang_codes.sort()

        sm = getSecurityManager()
        R = []
        for lang in lang_codes:
            trans = translations[lang][0]
            if not sm.checkPermission('View', trans):
                continue
            url = trans.absolute_url()

            name = ali.get(lang, {'native': lang})['native']
            R.append((name, url))
        return R
def createObjectAsPortalOwner(container, type_name, id_):
    """Create an object as the portal owner"""
    info = interfaces.ITemplateTypeInfo(
        container.portal_types.getTypeInfo(type_name), None)
    if info is None:
        return
    template = info.getTemplate(container)
    if template is None:
        return
    source = Acquisition.aq_parent(Acquisition.aq_inner(template))

    sm = SecurityManagement.getSecurityManager()
    SecurityManagement.newSecurityManager(
        None,
        container.portal_url.getPortalObject().getOwner())
    result, = container.manage_pasteObjects(
        source.manage_copyObjects([template.getId()]))
    container.manage_renameObject(result['new_id'], id_)
    SecurityManagement.setSecurityManager(sm)

    added = container[id_]
    owner.changeOwnershipOf(added)
    event.notify(interfaces.TemplateCopiedEvent(added, template))

    return added
    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)
Exemple #21
0
    def _searchCatalog(self):
        """ search the catalog for all items on a subject 
            this is to be cached 
        """
        start = time.time()

        context = Acquisition.aq_inner(self.context)
        portal_catalog = getToolByName(context, 'portal_catalog')

        query = {'Language': '', 
                 'Subject': self.Subject or '', 
                 'review_state': 'published'
                }
        results = portal_catalog(query)
        stop = time.time()
        print "Catalog time is %s" % (stop-start)
        # The brain objects fetch the values potentially lazy only if needed. 
        # This may be bad for caching and seems to result in the hard to debug 
        # ConnectionStateError: Shouldn't load state for 0x3768d0 when the connection is closed error. 
        # I therefore copy the results over into a static datastructure.
        sres = []
        schema = portal_catalog.schema()
        for result in results:
            staticbrain = {}
            for key in schema:
                staticbrain[key] = result[key]
            staticbrain['getURL'] = result.getURL()
            staticbrain['getPath'] = result.getPath()
            
            sres.append(staticbrain)
            
        return sres
Exemple #22
0
    def __call__(self):
        reindex = not not self.request.get('reindex', False)
        limit = self.request.get('limit', 0)
        limit = int(limit)
        out = StringIO.StringIO()
        out.write("Converting the Nace codes\n")
        out.write(
            "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n")
        out.write("\n\n")
        if limit > 0:
            out.write("Limiting to %s objects\n" % limit)
        else:
            out.write("No limit. Convert all objects\n")

        context = Acquisition.aq_inner(self.context)
        portal_catalog = getToolByName(context, 'portal_catalog')
        results = portal_catalog.searchResults(Language='all')
        cnt = 0
        for brain in results:
            try:
                ob = brain.getObject()
            except AttributeError:
                continue
            o, n = self.rewriteNaceCodes(ob, reindex)
            if o is not None:
                cnt += 1
                out.write("Path: %s\nOld: %s\nNew: %s\n\n" %
                          (brain.getPath(), o, n))

            if limit >= 0 and cnt >= limit:
                break

        out.write("%s objects done" % cnt)
        return out.getvalue()
Exemple #23
0
    def __call__(self):
        reindex = not not self.request.get("reindex", False)
        limit = self.request.get("limit", 0)
        limit = int(limit)
        out = StringIO.StringIO()
        out.write("Converting the Nace codes\n")
        out.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n")
        out.write("\n\n")
        if limit > 0:
            out.write("Limiting to %s objects\n" % limit)
        else:
            out.write("No limit. Convert all objects\n")

        context = Acquisition.aq_inner(self.context)
        portal_catalog = getToolByName(context, "portal_catalog")
        results = portal_catalog.searchResults(Language="all")
        cnt = 0
        for brain in results:
            try:
                ob = brain.getObject()
            except AttributeError:
                continue
            o, n = self.rewriteNaceCodes(ob, reindex)
            if o is not None:
                cnt += 1
                out.write("Path: %s\nOld: %s\nNew: %s\n\n" % (brain.getPath(), o, n))

            if limit >= 0 and cnt >= limit:
                break

        out.write("%s objects done" % cnt)
        return out.getvalue()
Exemple #24
0
    def queryCatalog(self, b_size=10):
        context = Acquisition.aq_inner(self.context)
        catalog = getToolByName(context, "portal_catalog")

        portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
        navigation_root_path = portal_state.navigation_root_path()

        oshaview = getMultiAdapter((self.context, self.request), name=u"oshaview")
        mySEP = oshaview.getCurrentSingleEntryPoint()
        kw = ""
        if mySEP is not None:
            kw = mySEP.getProperty("keyword", "")

        query = dict(portal_type="Event", review_state="published", path=navigation_root_path, sort_on="start")

        if self.request.get("show", "") == "previous":
            query.update(end={"query": DateTime(), "range": "max"})
        else:
            query.update(end={"query": DateTime(), "range": "min"})

        if kw != "":
            query.update(Subject=kw)
        results = catalog(query)

        b_start = self.request.get("b_start", 0)
        batch = Batch(results, b_size, int(b_start), orphan=0)
        return batch
Exemple #25
0
 def broken_links(self):
     """ return all links sorted by path which need PM attention 
     """
     context = Acquisition.aq_inner(self.context)
     link_catalog = getToolByName(context, 'portal_linkchecker').database.link_catalog
     uid_catalog = getToolByName(context, 'uid_catalog')
     results = link_catalog(state=['red', 'orange'])
     links = []
     uids = []
     for link in results:
         item = {}
         item["url"] = link.url
         item["reason"] = link.reason
         item["lastcheck"] = link.lastcheck
         item["id"] = link.getId
         item["link"] = link.link
         item["state"] = link.state
         item["object"] = link.object
         links.append(item)
         ob = uid_catalog(UID=link.object)[0].getObject()
         item["document"] = ob
         item['path'] = ob.absolute_url()
         
     links.sort(lambda x,y: cmp(x['path'], y['path']))
     return links
Exemple #26
0
 def listobjects(self):
     context = Acquisition.aq_inner(self.context)
     container = Acquisition.aq_parent(context)
     objects = container.objectValues(['ATDocument', 'RichDocument'])
     ip = container.getDefaultPage()
     filtered_objects = [x for x in objects if x.getId() != ip]
     return filtered_objects
 def story(self):
     context = Acquisition.aq_inner(self.context)
     if interfaces.IXMStory.providedBy(context):
         return context
     if interfaces.IXMTask.providedBy(context):
         return Acquisition.aq_parent(context)
     return None
Exemple #28
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)
 def getItemsBySection(self, section, **kwargs):
     """Get items in this section"""
     
     context = Acquisition.aq_inner(self.context)
     
     criteria = {}
     if section == 'No section':
         items = []
         for item in context.getFolderContents(contentFilter = kwargs):
             if not item.getSections:
                 items.append(item)
         return items
     else:
         if isinstance(section, basestring):
             # Wrap in list to avoid solr interpreting sections with spaces
             # as multiple keywords
             criteria['getSections'] = [section]
         else:
             criteria['getSections'] = section
         res = []
         #we have to filter the brains to avoid getting one concerning a minor section when the section is a major section
         # -> we don't want 'major:minor' if only 'major' is searched
         for brain in context.getFolderContents(contentFilter = criteria):
             #the searched section is a major one, we have to check if there's a minor one too"
             if section.find(':') == -1 and len([s for s in brain.getSections if s.startswith('%s:'%section)]):
                 continue
             res.append(brain)
         return res
Exemple #30
0
 def getContext(self):
     context = Acquisition.aq_inner(self.context)
     # if dynamic-pressroom was used on a Document, get the parent-folder
     if IATDocument.providedBy(context):
         context = Acquisition.aq_parent(context)
     context = context.getCanonical()
     return context
Exemple #31
0
 def listobjects(self):
     context = Acquisition.aq_inner(self.context)
     container = Acquisition.aq_parent(context)
     objects = container.objectValues(['ATDocument', 'RichDocument'])
     ip = container.getDefaultPage()
     filtered_objects = [x for x in objects if x.getId()!=ip]
     return filtered_objects
Exemple #32
0
 def cropHtmlText(self, text, length, ellipsis='...'):
     """ First strip html, then crop """
     context = Acquisition.aq_inner(self.context)
     portal_transforms = getToolByName(context, 'portal_transforms')
     text = portal_transforms.convert('html_to_text', text).getData()
     return context.restrictedTraverse('@@plone').cropText(
         text, length, ellipsis)
Exemple #33
0
    def getResults(self):
        context = Acquisition.aq_inner(self.context)

        # try to get query parameters from Topic (if present)
        query = hasattr(context, 'buildQuery') and context.buildQuery()
        if query:
            catalog = getToolByName(context, 'portal_catalog')
            results = catalog(query)
            # filter out results that are both outdated and expired
            to_show = [
                x for x in results if not (
                    getattr(x, 'outdated', False) and isExpired(x))
            ]
            return to_show

        # otherwise construct a query
        portal_state = getMultiAdapter(
            (self.context, self.request), name=u'plone_portal_state')
        navigation_root_path = portal_state.navigation_root_path()

        oshaview = getMultiAdapter(
            (self.context, self.request), name=u'oshaview')
        mySEP = oshaview.getCurrentSingleEntryPoint()
        kw = ''

        if mySEP:
            kw = mySEP.getProperty('keyword', '')

        query = '(portal_type:("News Item") OR isNews:true) AND '
        'review_state:published AND path_parents:%s' % navigation_root_path
        if kw != '':
            query = ' AND '.join([query, 'Subject:(%s)' % ' OR '.join(kw)])
        return search_solr(query, sort='Date desc')
Exemple #34
0
 def link(self):
     context = Acquisition.aq_inner(self.context)
     portal_languages = getToolByName(context, 'portal_languages')
     preflang = portal_languages.getPreferredLanguage()
     if preflang not in self.portal.objectIds():
         preflang = 'en'
     return "%s/%s/help" %(self.portal.absolute_url(), preflang)
Exemple #35
0
 def num_subscribers(self):
     context = Acquisition.aq_inner(self.context)
     portal_properties = getToolByName(context, 'portal_properties')
     num = portal_properties.site_properties.getProperty(
         'num_subscribers_oshmail')
     if hasattr(portal_properties.site_properties, 'osha_properties'):
         num = portal_properties.site_properties.osha_properties.getProperty(
             'num_subscribers')
     return num
Exemple #36
0
    def __call__(self):
        self.request.set('disable_border', True)
        context = Acquisition.aq_inner(self.context)

        portal_catalog = getToolByName(context, 'portal_catalog')
        portal_languages = getToolByName(context, 'portal_languages')
        self.lang = portal_languages.getPreferredLanguage()
        self.items = self._searchCatalog()
        return self.index()