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 #2
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
 def _createZODBClone(self):
     """Create a ZODB (editable) equivalent of this object."""
     obj = ControllerPythonScript(self.getId(), filepath=self.filepath)
     obj.write(self.read())
     obj.validators = copy.copy(Acquisition.aq_base(self.validators))  # XXX - don't forget to enable this
     obj.actions = copy.copy(Acquisition.aq_base(self.actions))
     return obj
Exemple #4
0
    def rewriteNaceCodes(self, ob, reindex=0):
        if hasattr(Acquisition.aq_base(ob), '__nace_migrated__'):
            return None, None
        if not hasattr(Acquisition.aq_base(ob), 'getField'):
            return None, None
        field = ob.getField('nace')
        if field is None:
            return None, None
        oldnace = field.getAccessor(ob)()
        if len(oldnace) == 0:
            return None, None
        # should be a tuple or list
        ob.__oldnace__ = oldnace
        if type(oldnace) in [ListType, TupleType]:
            oldnace = list(oldnace)
        elif type(oldnace) in [StringType, UnicodeType]:
            oldnace = [oldnace]
        else:
            raise TypeError, "oldnace is not list nor string!! %s is %s" % (
                oldnace, type(oldnace))

        newnace = set()
        for code in oldnace:
            subst = NACE_MAP.get(code, code)
            if type(subst) in [TupleType, ListType]:
                newnace = newnace.union(subst)
            else:
                newnace.add(subst)
        newnace = tuple(newnace)
        field.getMutator(ob)(newnace)
        ob.__newnace__ = newnace
        ob.__nace_migrated__ = True
        if reindex == 1:
            ob.reindexObject('nace')
        return oldnace, newnace
Exemple #5
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 #6
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 #7
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()
    def unregisterUtility(self, component=None, provided=None, name=u'',
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        # If the existing registration is a ComponentPathWrapper, we
        # convert the component that is to be unregistered to a wrapper.
        # This ensures that our custom comparision methods are called.
        if component is not None:
            old = self._utility_registrations.get((provided, name))
            if old is not None:
                if isinstance(old[0], ComponentPathWrapper):
                    unwrapped_component = Acquisition.aq_base(component)
                    component = ComponentPathWrapper(unwrapped_component, '')
        # Unwrap the utility before continuing to super to allow zope.interface
        # to cache the component root
        component_root = Acquisition.aq_base(self)
        return super(PersistentComponents, component_root).unregisterUtility(
            component=component, provided=provided, name=name)
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 createPDF(self, settings, dest, context, path_has_changed, status):
        asPDF = context.restrictedTraverse('asEfact', None)
        if not asPDF:
            # sth bad has happened
            status.addStatusMessage(u"Could not find BrowserView for creating a PDF", type="error")
            return None
        try:
            rawPDF = asPDF(number=settings.issue)
            rawPDF = file(rawPDF, 'rb').read()
        except:
            status.addStatusMessage(u"Creating a PDF file failed. Please check connection to SmartPrintNG server", type="error")
            return None


        filename = "%s.pdf" %settings.issue
        # If no UID of a publication exists yet, or if the destination folder has changed, create a new file
        if not settings.existing_publication or path_has_changed:
            # If an object with the given filename already exists at the destination folder, return an error
            if getattr(Acquisition.aq_base(dest), filename, None):
                obj = getattr(dest, filename)
                status.addStatusMessage(u"An object of type %(type)s already exists at %(path)s, but is not connected " \
                 "to this document. Please remove it first or change the document's short name (id)" %dict(
                    type=type(Acquisition.aq_base(obj)), path=obj.absolute_url()), type="warning")
                return None
            dest.invokeFactory(type_name="File", id=filename)
            transaction.commit()
            newFile = getattr(dest, filename)
            newFile.unmarkCreationFlag()
            settings.existing_publication = newFile.UID()
            isNew=True

        # Retrieve the publication from the catalog by its UID
        else:
            catalog = getToolByName(context, 'portal_catalog')
            brains = catalog(UID=settings.existing_publication)
            if not len(brains):
                status.addStatusMessage(u"Existing Publication could not be retrieved", type="error")
                return None
            newFile = brains[0].getObject()
            if not newFile:
                status.addStatusMessage(u"Reference to exiting Publication is broken", type="error")
                return None
            isNew=False
        newFile.processForm(values=dict(id=filename, title=context.Title(),
            description=context.Description()))
        newFile.setFile(rawPDF)
        # setting Subject AND Subcategory shouldn't be necessary
        # But we don't know yet what the client prefers
        newFile.setSubject(settings.subject)
        # newFile.setSubcategory(settings.subcategory)
        newFile.setNace(settings.nace)
        newFile.setMultilingual_thesaurus(settings.multilingual_thesaurus)
        # set a link to the original document on the publication
        ann = IAnnotations(newFile)
        ann[PUBLICATION_DOCUMENT_REFERENCE] = context.UID()
        if isinstance(settings.publication_date, date):
            newFile.setEffectiveDate(DateTime(settings.publication_date.isoformat()))
        status.addStatusMessage(u"%(verb)s publication at %(url)s" %dict(
            verb=isNew and 'Added' or 'Updated', url=newFile.absolute_url()), type="info")
        return newFile
    def unregisterUtility(self,
                          component=None,
                          provided=None,
                          name=u'',
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        # If the existing registration is a ComponentPathWrapper, we
        # convert the component that is to be unregistered to a wrapper.
        # This ensures that our custom comparision methods are called.
        if component is not None:
            old = self._utility_registrations.get((provided, name))
            if old is not None:
                if isinstance(old[0], ComponentPathWrapper):
                    unwrapped_component = Acquisition.aq_base(component)
                    component = ComponentPathWrapper(unwrapped_component, '')
        # Unwrap the utility before continuing to super to allow zope.interface
        # to cache the component root
        component_root = Acquisition.aq_base(self)
        return super(PersistentComponents,
                     component_root).unregisterUtility(component=component,
                                                       provided=provided,
                                                       name=name)
Exemple #12
0
    def rewriteNaceCodes(self, ob, reindex=0):
        if hasattr(Acquisition.aq_base(ob), "__nace_migrated__"):
            return None, None
        if not hasattr(Acquisition.aq_base(ob), "getField"):
            return None, None
        field = ob.getField("nace")
        if field is None:
            return None, None
        oldnace = field.getAccessor(ob)()
        if len(oldnace) == 0:
            return None, None
        # should be a tuple or list
        ob.__oldnace__ = oldnace
        if type(oldnace) in [ListType, TupleType]:
            oldnace = list(oldnace)
        elif type(oldnace) in [StringType, UnicodeType]:
            oldnace = [oldnace]
        else:
            raise TypeError, "oldnace is not list nor string!! %s is %s" % (oldnace, type(oldnace))

        newnace = set()
        for code in oldnace:
            subst = NACE_MAP.get(code, code)
            if type(subst) in [TupleType, ListType]:
                newnace = newnace.union(subst)
            else:
                newnace.add(subst)
        newnace = tuple(newnace)
        field.getMutator(ob)(newnace)
        ob.__newnace__ = newnace
        ob.__nace_migrated__ = True
        if reindex == 1:
            ob.reindexObject("nace")
        return oldnace, newnace
Exemple #13
0
 def _createZODBClone(self):
     """Create a ZODB (editable) equivalent of this object."""
     obj = ControllerPythonScript(self.getId(), filepath=self.filepath)
     obj.write(self.read())
     obj.validators = copy.copy(Acquisition.aq_base(self.validators))  # XXX - don't forget to enable this
     obj.actions = copy.copy(Acquisition.aq_base(self.actions))
     return obj
    def _findapply(self, obj, result=None, path=''):
        # recursive function to actually dig through and find the locked
        # objects.

        if result is None:
            result = []
        base = Acquisition.aq_base(obj)
        if not hasattr(base, 'objectItems'):
            return result
        try: items = obj.objectItems()
        except: return result

        addresult = result.append
        for id, ob in items:
            if path: p = '%s/%s' % (path, id)
            else: p = id

            dflag = hasattr(ob, '_p_changed') and (ob._p_changed == None)
            bs = Acquisition.aq_base(ob)
            if wl_isLocked(ob):
                li = []
                addlockinfo = li.append
                for token, lock in ob.wl_lockItems():
                    addlockinfo({'owner':lock.getCreatorPath(),
                                 'token':token})
                addresult((p, li))
                dflag = 0
            if hasattr(bs, 'objectItems'):
                self._findapply(ob, result, p)
            if dflag: ob._p_deactivate()

        return result
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
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 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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
0
    def cutAndPaste(self, sourcepath, id, targetpath):
        """ uses OFS to cur and paste an object
            sourecpath must refer to the folder which contains the object to move
            id must be a string containing the id of the object to move
            targetpath must be the folder to move to
            both paths must contain one single %s to place the language
        """
        context = Acquisition.aq_inner(self.context)
        if '%s' not in sourcepath:
            return ["Wrong sourcepath"]
        if '%s' not in targetpath:
            return ["Wrong targetpath"]

        results = []

        for lang in self.langs:
            results.append("Trying language: %s" % lang)

            spath = sourcepath % lang
            source = context.restrictedTraverse(spath, None)
            if source is None:
                results.append("  # Break, source is none")
                continue
            spathtest = "/".join(source.getPhysicalPath())
            if spath != spathtest:
                results.append(
                    "  # Break, requested path not sourcepath (%s != %s)" %
                    (spath, spathtest))
                continue

            tpath = targetpath % lang
            target = context.restrictedTraverse(tpath, None)
            if target is None:
                results.append("  # Break, target is none")
                continue
            tpathtest = "/".join(target.getPhysicalPath())
            if tpath != tpathtest:
                results.append(
                    "  # Break, requested path not targetpath (%s != %s)" %
                    (tpath, tpathtest))
                continue

            ob = getattr(source, id)
            ob = Acquisition.aq_base(ob)
            if ob is None:
                results.append("  # Break, ob is None!!")
            source._delObject(id, suppress_events=True)
            target._setObject(id, ob, set_owner=0, suppress_events=True)
            ob = target._getOb(id)

            notify(ObjectMovedEvent(ob, source, id, target, id))
            notifyContainerModified(source)
            if Acquisition.aq_base(source) is not Acquisition.aq_base(target):
                notifyContainerModified(target)
            ob._postCopy(target, op=1)

            results.append("Copy&Paste successful for language %s" % lang)

        return results
Exemple #24
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 _createZODBClone(self):
     """Create a ZODB (editable) equivalent of this object."""
     obj = ControllerPageTemplate(self.getId(), self._text, self.content_type)
     obj.expand = 0
     obj.write(self.read())
     obj.validators = copy.copy(Acquisition.aq_base(self.validators))
     obj.actions = copy.copy(Acquisition.aq_base(self.actions))
     return obj
Exemple #26
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 #27
0
    def iteration(self):
        context = Acquisition.aq_inner(self.context)
        if interfaces.IXMIteration.providedBy(context):
            return context

        story = self.story
        if story is None:
            return None
        return Acquisition.aq_parent(story)
Exemple #28
0
    def project(self):
        context = Acquisition.aq_inner(self.context)
        if interfaces.IXMProject.providedBy(context):
            return context

        iteration = self.iteration
        if iteration is None:
            return None
        return Acquisition.aq_parent(iteration)
Exemple #29
0
        def _setter(ob, *args, **kw):
            id = kw['id']
            typ = kw['typ']
            value = kw['value']

            ob = Acquisition.aq_inner(ob)
            if Acquisition.aq_base(ob).hasProperty(id):
                ob._delProperty(id)
            ob._setProperty(id=id, value=value, type=typ)
 def _createZODBClone(self):
     """Create a ZODB (editable) equivalent of this object."""
     obj = ControllerPageTemplate(self.getId(), self._text,
                                  self.content_type)
     obj.expand = 0
     obj.write(self.read())
     obj.validators = copy.copy(Acquisition.aq_base(self.validators))
     obj.actions = copy.copy(Acquisition.aq_base(self.actions))
     return obj
Exemple #31
0
 def _setter(ob, *args, **kw):
     id = kw['id']
     typ = kw['typ']
     value = kw['value']
     
     ob = Acquisition.aq_inner(ob)
     if Acquisition.aq_base(ob).hasProperty(id):
         ob._delProperty(id)
     ob._setProperty(id=id, value=value, type=typ)
        def _setter(ob, *args, **kw):
            id = kw["id"]
            typ = kw["typ"]
            value = kw["value"]

            ob = Acquisition.aq_inner(ob)
            if Acquisition.aq_base(ob).hasProperty(id):
                ob._delProperty(id)
            ob._setProperty(id=id, value=value, type=typ)
    def project(self):
        context = Acquisition.aq_inner(self.context)
        if interfaces.IXMProject.providedBy(context):
            return context

        iteration = self.iteration
        if iteration is None:
            return None
        return Acquisition.aq_parent(iteration)
    def iteration(self):
        context = Acquisition.aq_inner(self.context)
        if interfaces.IXMIteration.providedBy(context):
            return context

        story = self.story
        if story is None:
            return None
        return Acquisition.aq_parent(story)
    def cutAndPaste(self, sourcepath, id, targetpath):
        """ Uses OFS to cut and paste an object.
            Sourecpath must refer to the folder which contains the object to
            move. id must be a string containing the id of the object to move.
            targetpath must be the folder to move to.
            Both paths must contain one single %s to place the language
        """
        context = Acquisition.aq_inner(self.context)
        if "%s" not in sourcepath:
            return ["Wrong sourcepath"]
        if "%s" not in targetpath:
            return ["Wrong targetpath"]

        results = []

        for lang in self.langs:
            results.append("Trying language: %s" % lang)

            spath = sourcepath % lang
            source = context.restrictedTraverse(spath, None)
            if source is None:
                results.append("  # Break, source is none")
                continue
            spathtest = "/".join(source.getPhysicalPath())
            if spath != spathtest:
                results.append("  # Break, requested path not sourcepath " "(%s != %s)" % (spath, spathtest))
                continue

            tpath = targetpath % lang
            target = context.restrictedTraverse(tpath, None)
            if target is None:
                results.append("  # Break, target is none")
                continue
            tpathtest = "/".join(target.getPhysicalPath())
            if tpath != tpathtest:
                results.append("  # Break, requested path not targetpath " "(%s != %s)" % (tpath, tpathtest))
                continue

            ob = getattr(source, id, None)
            ob = Acquisition.aq_base(ob)
            if ob is None:
                results.append("  # Break, ob is None!!")
                continue
            source._delObject(id, suppress_events=True)
            target._setObject(id, ob, set_owner=0, suppress_events=True)
            ob = target._getOb(id)

            notify(ObjectMovedEvent(ob, source, id, target, id))
            notifyContainerModified(source)
            if Acquisition.aq_base(source) is not Acquisition.aq_base(target):
                notifyContainerModified(target)
            ob._postCopy(target, op=1)

            results.append("Copy&Paste successful for language %s" % lang)

        return results
Exemple #36
0
 def get_current_seminar(self):
     """ Return the object of a particular type which is
         the parent of the current object.
     """
     obj = Acquisition.aq_inner(self.context)
     while not isinstance(obj, PloneSite):
         if obj.meta_type == 'SPSeminar':
             return obj
         obj = Acquisition.aq_parent(obj)
     return None
def _rewrap(obj):
    """This functions relies on the passed in obj to provide the IAcquirer
    interface.
    """
    obj = Acquisition.aq_inner(obj)
    base = Acquisition.aq_base(obj)
    parent = Acquisition.aq_parent(obj)
    if parent is None or isinstance(parent, RequestContainer):
        return base
    return base.__of__(_rewrap(parent))
 def getCriteriaItems(self):
     """Only use this sort if it is the default or is specified"""
     topic = Acquisition.aq_parent(Acquisition.aq_inner(self))
     if not interfaces.IFormTopic.providedBy(topic) or (
         self.Field() != 'unsorted' and (
             self.getId() in self.REQUEST or
             Acquisition.aq_base(self) is Acquisition.aq_base(
                 topic.listSortCriteria()[0]))):
         return super(FormSortCriterion, self).getCriteriaItems()
     return ()
    def __init__(self, context, request, name, permission, template, owner=None):  # noqa
        # Fix issue where context is a template based view class
        while IBrowserView.providedBy(context):
            context = Acquisition.aq_parent(Acquisition.aq_inner(context))

        super(FragmentView, self).__init__(context, request)
        self.__name__ = name
        self._permission = permission
        self._template = template
        self._owner = owner
Exemple #40
0
def _rewrap(obj):
    """This functions relies on the passed in obj to provide the IAcquirer
    interface.
    """
    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 #41
0
 def unregister_translation_domain_fallback():
   from zope.component.globalregistry import base
   base.unregisterUtility(DummyTranslationDomainFallback)
   sm = zope.component.getSiteManager()
   portal = Acquisition.aq_parent(sm)
   ui_domain = getattr(portal, '_save_ui_domain', [None]).pop()
   if ui_domain is not None:
     # aq_base() to remove acquisition wrapping
     ui_domain = Acquisition.aq_base(ui_domain)
     sm.registerUtility(ui_domain, ITranslationDomain, 'ui')
     del portal._save_ui_domain
 def get_parent_object_of_type(self, meta_type):
     """ Return the object of a particular type which is
     the parent of the current object."""
     if hasattr(self.context, 'meta_type') and self.context.meta_type == meta_type:
         return self.context
     obj = Acquisition.aq_inner(self.context)
     while not isinstance(obj, PloneSite):
         obj = Acquisition.aq_parent(obj)
         if hasattr(obj, 'meta_type') and obj.meta_type == meta_type:
             return obj
     return None
Exemple #43
0
 def unregister_translation_domain_fallback():
     from zope.component.globalregistry import base
     base.unregisterUtility(DummyTranslationDomainFallback)
     sm = zope.component.getSiteManager()
     portal = Acquisition.aq_parent(sm)
     ui_domain = getattr(portal, '_save_ui_domain', [None]).pop()
     if ui_domain is not None:
         # aq_base() to remove acquisition wrapping
         ui_domain = Acquisition.aq_base(ui_domain)
         sm.registerUtility(ui_domain, ITranslationDomain, 'ui')
         del portal._save_ui_domain
Exemple #44
0
def copyLegislation(self):
    portal = getToolByName(self, 'portal_url').getPortalObject()
    folder = getattr(portal.en.legislation.directives,  'provisions-on-workload-ergonomical-and-psychosocial-risks')

    subfolders = self.ZopeFind(obj=folder, search_sub=1,
    obj_metatypes='ATFolder')
    langs = folder.getTranslationLanguages()
    for subf in subfolders:
        id, ob = subf
        if ob.Language() not in ('en',''):
            continue
        print "translating folder", ob.absolute_url()
        linguautils.translate_this(ob, [], 0, langs) 
        linguautils.exec_for_all_langs(ob, linguautils.workflow_action, transition="publish")

    documents = self.ZopeFind(obj=folder, search_sub=1,
        obj_metatypes='ATDocument')
    for doc in documents:
        id, ob = doc
        if ob.Language() not in ('en', ''):
            continue
        print "translating document", ob.absolute_url()
        linguautils.translate_this(ob, ['title', 'description', 'text'], 0, langs)
        linguautils.exec_for_all_langs(ob, linguautils.workflow_action, transition="publish")

    print "folder:", folder
    objs = self.ZopeFind(obj=folder, search_sub=1, obj_metatypes='Collage')

    for item in objs:
        id, ob = item
        id = id.split('/')[-1]
        print "id:", id
        print "url", ob.absolute_url()
        print item
        parent = Acquisition.aq_parent(ob)
        print parent
        parentlang = parent.Language()
        trans = parent.getTranslations()
        for lang in trans.keys():
            if lang == parentlang:
                continue
            target = trans[lang][0]
#            if getattr(Acquisition.aq_base(target), id, None) and type(getattr(Acquisition.aq_base(target), id, None)) == type(ob):
#                target.manage_delObjects(id)
            if not getattr(Acquisition.aq_base(target), id, None) or not \
            type(getattr(Acquisition.aq_base(target), id, None))==type(ob):
                cp = ob._getCopy(ob)
                target._setObject(id, cp)
                print "doing the copying", cp, [id]
            else:
                print "target in lang %s at %s already has obj with id %s" % (lang,
                target.absolute_url(), id)

    return "ok!"
Exemple #45
0
    def my_siblings(self):
        """ find siblings with the same portal_type.
        """

        context = Acquisition.aq_base(self.context)
        parent = Acquisition.aq_parent(self.context)
        portal_type = context.portal_type
        my_id = context.id
        sibs = api.content.find(context=parent,
                                portal_type=portal_type,
                                depth=1)
        return [s for s in sibs if s.id != my_id]
Exemple #46
0
 def getBase_url(self):
     """ Returns a (sub-) sites URL including the language folder
     if present """
     language = getToolByName(self.context, "portal_languages").getPreferredLanguage()
     subsite_url = self.subsiteRootUrl()
     subsite_path = self.subsiteRootPath()
     root = self.context.restrictedTraverse(subsite_path)
     if hasattr(Acquisition.aq_base(Acquisition.aq_inner(root)), language):
         base_url = "%s/%s" % (subsite_url, language)
     else:
         base_url = subsite_url
     return base_url
 def __iter__(self):
     context = self.transmogrifier.context
     for item in self.previous:
         if self.condition(item):
             obj = resolve_object(context, item)
             uuid_ = IUUID(obj, None)
             if uuid_ is not None:
                 item['_uuid'] = uuid_
             elif hasattr(Acquisition.aq_base(obj), 'UID'):
                 item['_uuid'] = Acquisition.aq_base(obj).UID()
             if not item.get('_uuid'):
                 item['_uuid'] = str(uuid.uuid4()).replace('-', '')
         yield item
 def __iter__(self):
     context = self.transmogrifier.context
     key = self.options.get('key', '_gopip')
     for item in self.previous:
         if self.condition(item):
             obj = resolve_object(context, item)
             id_ = obj.getId()
             parent = Acquisition.aq_parent(obj)
             if hasattr(Acquisition.aq_base(parent), 'getObjectPosition'):
                 item[key] = parent.getObjectPosition(id_)
             else:
                 item[key] = None
         yield item
Exemple #49
0
 def __iter__(self):
     portal = api.portal.get()
     for item in self.previous:
         if self.condition(item):
             ob = traverse(portal, item['_path'])
             uuid_ = IUUID(ob, None)
             if uuid is not None:
                 item['_uuid'] = uuid_
             elif hasattr(Acquisition.aq_base(ob), 'UID'):
                 item['_uuid'] = Acquisition.aq_base(ob).UID()
             if not item.get('_uuid'):
                 item['_uuid'] = str(uuid.uuid4()).replace('-', '')
         yield item
 def __iter__(self):
     key = self.options.get('key', '_gopip')
     for item in self.previous:
         if self.condition(item):
             if '_object' in item and key:
                 ob = item['_object']
                 id_ = ob.getId()
                 parent = Acquisition.aq_parent(ob)
                 if hasattr(Acquisition.aq_base(ob), 'getObjectPosition'):
                     item[key] = parent.getObjectPosition(id_)
                 else:
                     item[key] = None
         yield item
Exemple #51
0
    def get_optional_collectors(self):
        optional_collectors = []
        if self.optional:
            optional_collectors.append(self)
        for child in self.objectValues():
            if collective.singing.interfaces.ICollector.providedBy(child):
                if hasattr(
                    Acquisition.aq_base(child), 'get_optional_collectors'):
                    optional_collectors.extend(child.get_optional_collectors())
                elif getattr(Acquisition.aq_base(child), 'optional', False):
                    optional_collectors.append(child)

        return optional_collectors
 def __iter__(self):
     context = self.transmogrifier.context
     for item in self.previous:
         if self.condition(item):
             obj = resolve_object(context, item)
             parent = Acquisition.aq_parent(obj)
             uuid_ = IUUID(parent, None)
             if uuid_ is not None:
                 item['_parent_uuid'] = uuid_
             elif hasattr(Acquisition.aq_base(parent), 'UID'):
                 item['_parent_uuid'] = Acquisition.aq_base(parent).UID()
             if not item.get('_parent_uuid'):
                 item['_parent_uuid'] = None
         yield item
Exemple #53
0
    def test_switching_memberdata_factory(self):
        from Products.CMFCore.MemberDataTool import MemberData
        tool = self._makeOne()
        user = DummyUser('dummy', '', [], [])
        member = Acquisition.aq_base(tool.wrapUser(user))
        self.assertEquals(getattr(member, 'iamnew', None), None)

        class NewMemberData(MemberData):
            iamnew = 'yes'
        provideUtility(NewMemberData, IFactory, 'MemberData')

        user = DummyUser('dummy2', '', [], [])
        member = Acquisition.aq_base(tool.wrapUser(user))
        self.assertEquals(getattr(member, 'iamnew', None), 'yes')
 def render(self):
     if 'nextprev.collection' in self.request:
         topic = self.context.restrictedTraverse(
             self.request['nextprev.collection'])
         if Acquisition.aq_base(
                 self.context) is not Acquisition.aq_base(topic):
             name = self.__parent__.__name__
             if name == 'plone':
                 name = self.__parent__._data['template_id']
             if self.isListing(name):
                 self.request.response.expireCookie(
                     name='nextprev.collection', path='/')
                 self.request.response.expireCookie(name='nextprev.form',
                                                    path='/')
     return ''
 def __iter__(self):
     context = self.transmogrifier.context
     key = self.options.get('key', '_gopip')
     for item in self.previous:
         position = item.get(key)
         if self.condition(item) and position is not None:
             obj = resolve_object(context, item)
             id_ = obj.getId()
             parent = Acquisition.aq_parent(obj)
             if hasattr(Acquisition.aq_base(parent),
                        'moveObjectToPosition'):
                 parent.moveObjectToPosition(id_,
                                             position,
                                             suppress_events=False)
         yield item
Exemple #56
0
def EditURL(self, object, borrow_lock=0):
    """Return the URL to externally edit an object if appropriate"""
    base = Acquisition.aq_base(object)
    user = getSecurityManager().getUser()
    editable = (hasattr(base, 'manage_FTPget')
                or hasattr(base, 'EditableBody')
                or hasattr(base, 'document_src') or hasattr(base, 'read'))
    if editable and user.has_permission(ExternalEditorPermission, object):
        query = {}
        if is_mac_user_agent(object.REQUEST['HTTP_USER_AGENT']):
            # Add extension to URL so that the Mac finder can
            # launch the ZopeEditManager helper app
            # this is a workaround for limited MIME type
            # support on MacOS X browsers
            ext = '.zem'
            query['macosx'] = 1
        else:
            ext = ''
        if borrow_lock:
            query['borrow_lock'] = 1

        path = object.absolute_url().split('/')
        path.insert(-1, 'externalEdit_')
        return "%s%s%s" % ('/'.join(path), ext, querystr(query))
    return ''
Exemple #57
0
 def __of__(self, parent):
     # Accesses the database, returning an acquisition
     # wrapper around the connected object rather than around self.
     try:
         return self._getOrOpenObject(parent)
     except:
         return Acquisition.ImplicitAcquisitionWrapper(self, parent)
Exemple #58
0
    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):
                sections = item.getSections
                if not sections or sections and len(sections) < 2:
                    items.append(item)
            return items
        else:
            if isinstance(section, str):
                # 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 #59
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