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 #2
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
    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)
    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
Exemple #6
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
Exemple #7
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
 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 #9
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
 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
 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
    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
 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 ()
Exemple #14
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 #15
0
def _wrap(comp, registry):
    """Return an aq wrapped component with the site as the parent but
    only if the comp has an aq wrapper to begin with.
    """

    # BBB: The primary reason for doing this sort of wrapping of
    # returned utilities is to support CMF tool-like functionality where
    # a tool expects its aq_parent to be the portal object. New code
    # (ie new utilities) should not rely on this predictability to
    # get the portal object and should search out an alternate means
    # (possibly retrieve the ISiteRoot utility). Although in most
    # cases getting at the portal object shouldn't be the required pattern
    # but instead looking up required functionality via other (possibly
    # local) components.

    if registry.__bases__ and IAcquirer.providedBy(comp):
        current_site = getSite()
        registry_site = Acquisition.aq_base(registry.__parent__)
        if not ISite.providedBy(registry_site):
            registry_site = registry_site.__parent__

        if current_site is None:
            # If no current site can be found, return utilities wrapped in
            # the site they where registered in. We loose the whole aq chain
            # here though
            current_site = Acquisition.aq_base(registry_site)

        parent = None

        if current_site == registry_site:
            parent = current_site
        else:
            parent = _recurse_to_site(current_site, registry_site)

        if parent is None:
            raise ValueError('Not enough context to acquire parent')

        base = Acquisition.aq_base(comp)
        # clean up aq_chain, removing REQUEST objects
        parent = _rewrap(parent)

        if base is not Acquisition.aq_base(parent):
            # If the component is not the component registry container,
            # wrap it in the parent
            comp = base.__of__(parent)
        else:
            # If the component happens to be the component registry
            # container we are looking up a ISiteRoot.
            # We are not wrapping it in itself but in its own parent
            comp = base.__of__(Acquisition.aq_parent(parent))

    return comp
Exemple #16
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):
     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
Exemple #18
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
Exemple #19
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')
Exemple #20
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 __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
 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 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 fixTranslationReference(self, recursive=False, langindexoffset=0):
        """ fixes translation references to the canonical.
            Assumes that self is always en and canonical
            tries to handle language extensions for files like hwp_xx.swf
        """
        try:
            langindexoffset = int(langindexoffset)
        except:
            langindexoffset = 0
        context = Acquisition.aq_inner(self.context)
        pl = context.portal_languages
        langs = pl.getSupportedLanguages()

        results = []
        if recursive == True:
            targetobs = context.ZopeFind(context, search_sub=1)
        else:
            targetobs = [(context.getId(), context)]
        for id, ob in targetobs:

            print "handling %s" % ob.absolute_url(1)
            if hasattr(Acquisition.aq_base(ob), "_md") and "language" in ob._md and ob._md["language"] == u"":
                ob._md["language"] = u"en"

            if not hasattr(Acquisition.aq_base(ob), "addTranslationReference"):
                continue

            if not ob.isCanonical():
                results.append("Not Canonical: %s " % ob.absolute_url())
                print "Not Canonical: %s " % ob.absolute_url()

            for lang in langs:
                if ob.hasTranslation(lang):
                    continue
                langob = self._getLangOb(ob, lang, langindexoffset)

                if langob is None:
                    continue

                try:
                    langob.setLanguage("")
                    langob.setLanguage(lang)
                    langob.addTranslationReference(ob)
                    langpath = "/".join(langob.getPhysicalPath())
                    results.append("Adding TransRef for %s" % langpath)
                    print "Adding TransRef for %s" % langpath
                except Exception, at:
                    results.append("Except %s" % str(at))
Exemple #25
0
def iterFields(ob):
    # noinspection PyUnresolvedReferences
    ob = Acquisition.aq_base(ob)
    primary = ob.getPrimaryField()
    if primary:
        clone = cloneField(primary, primary=True)
        yield clone.__name__, clone

    for name in ob.schema.getSchemataNames():
        for field in ob.schema.getSchemataFields(name):
            if primary and primary.__name__ == field.__name__:
                continue

            # Mark 'primary fields', which get marshaled into payload
            if (bool(getattr(field, 'primary', None)) is True
                    or IBlobField.providedBy(field)
                    or (IFileField.providedBy(field)
                        and not ITextField.providedBy(field))
                    or getattr(field, 'widget', None) == RichWidget
                    or isinstance(field, ZPTField)):
                clone = cloneField(field, primary=True)
            else:
                clone = cloneField(field, primary=False)

            yield clone.__name__, clone
 def tearDownPloneSite(self, portal):
     portal.MailHost = portal._original_MailHost
     sm = zope.component.getSiteManager(context=portal)
     sm.unregisterUtility(provided=IMailHost)
     sm.registerUtility(
         Acquisition.aq_base(portal._original_MailHost),
         provided=IMailHost)
def unwrap(item):
    """Unwrap objects from known wrappings"""
    if HAS_ACQUISITION:
        # noinspection PyUnresolvedReferences
        return Acquisition.aq_base(item)
    else:
        return item
Exemple #28
0
def replaceCatalog(portal):
    import Acquisition
    from ubify.policy import tool

    catalog = getToolByName(portal, 'portal_catalog')
    if not isinstance(Acquisition.aq_base(catalog), tool.CatalogTool):
        catalog.__class__ = tool.CatalogTool
def iterFields(ob):
    # noinspection PyUnresolvedReferences
    ob = Acquisition.aq_base(ob)
    primary = ob.getPrimaryField()
    if primary:
        clone = cloneField(primary, primary=True)
        yield clone.__name__, clone

    for name in ob.schema.getSchemataNames():
        for field in ob.schema.getSchemataFields(name):
            if primary and primary.__name__ == field.__name__:
                continue

            # Mark 'primary fields', which get marshaled into payload
            if (bool(getattr(field, 'primary', None)) is True
                    or IBlobField.providedBy(field)
                    or (IFileField.providedBy(field)
                        and not ITextField.providedBy(field))
                    or getattr(field, 'widget', None) == RichWidget
                    or isinstance(field, ZPTField)):
                clone = cloneField(field, primary=True)
            else:
                clone = cloneField(field, primary=False)

            yield clone.__name__, clone
Exemple #30
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
     )
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
Exemple #32
0
    def wl_lockmapping(self, killinvalids=0, create=0):
        """ if 'killinvalids' is 1, locks who are no longer valid
        will be deleted """

        try:
            locks = getattr(self, '_dav_writelocks', None)
        except:
            locks = None

        if locks is None:
            if create:
                locks = self._dav_writelocks = PersistentMapping()
            else:
                # Don't generate a side effect transaction.
                locks = {}
            return locks
        elif killinvalids:
            # Delete invalid locks
            for token, lock in locks.items():
                if not lock.isValid():
                    del locks[token]
            if (not locks) and hasattr(Acquisition.aq_base(self),
                                       '__no_valid_write_locks__'):
                self.__no_valid_write_locks__()
            return locks
        else:
            return locks
Exemple #33
0
    def wl_lockmapping(self, killinvalids=0, create=0):
        """ if 'killinvalids' is 1, locks who are no longer valid
        will be deleted """

        try:
            locks = getattr(self, "_dav_writelocks", None)
        except:
            locks = None

        if locks is None:
            if create:
                locks = self._dav_writelocks = PersistentMapping()
            else:
                # Don't generate a side effect transaction.
                locks = {}
            return locks
        elif killinvalids:
            # Delete invalid locks
            for token, lock in locks.items():
                if not lock.isValid():
                    del locks[token]
            if (not locks) and hasattr(Acquisition.aq_base(self), "__no_valid_write_locks__"):
                self.__no_valid_write_locks__()
            return locks
        else:
            return locks
Exemple #34
0
def feature_activated(evt):
    if evt.enhancedinterface is interfaces.IAudioContainerEnhanced:
        # we want to remove any dynamic view fti layout that was set so our
        # audio view is displayed properly
        obj = Acquisition.aq_base(evt.object)
        if hasattr(obj, 'layout'):
            del obj.layout
Exemple #35
0
def feature_activated(evt):
    if evt.enhancedinterface is interfaces.IAudioContainerEnhanced:
        # we want to remove any dynamic view fti layout that was set so our
        # audio view is displayed properly
        obj = Acquisition.aq_base(evt.object)
        if hasattr(obj, 'layout'):
            del obj.layout
Exemple #36
0
def unwrap(item):
    """Unwrap objects from known wrappings"""
    if HAS_ACQUISITION:
        # noinspection PyUnresolvedReferences
        return Acquisition.aq_base(item)
    else:
        return item
Exemple #37
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 #38
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 #39
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 ''
def replaceCatalog(portal):
    import Acquisition
    from ubify.policy import tool
    
    catalog = getToolByName(portal, 'portal_catalog')
    if not isinstance(Acquisition.aq_base(catalog), tool.CatalogTool):
        catalog.__class__ = tool.CatalogTool
Exemple #41
0
def EditLink(self, object, borrow_lock=0):
    """Insert the external editor link to 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
        url = "%s/externalEdit_/%s%s%s" % (object.aq_parent.absolute_url(), 
                                           urllib.quote(object.getId()), 
                                           ext, querystr(query))
        return ('<a href="%s" '
                'title="Edit using external editor">'
                '<img src="%s/misc_/ExternalEditor/edit_icon" '
                'align="middle" hspace="2" border="0" alt="External Editor" />'
                '</a>' % (url, object.REQUEST.BASEPATH1)
               )
    else:
        return ''
Exemple #42
0
def EditLink(self, object, borrow_lock=0, skip_data=0):
    """Insert the external editor link to 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
        if skip_data:
            query['skip_data'] = 1
        url = "%s/externalEdit_/%s%s%s" % (object.aq_parent.absolute_url(),
                                           urllib.quote(object.getId()),
                                           ext, querystr(query))
        return ('<a href="%s" '
                'title="Edit using external editor">'
                '<img src="%s/misc_/ExternalEditor/edit_icon" '
                'align="middle" hspace="2" border="0" alt="External Editor" />'
                '</a>' % (url, object.REQUEST.BASEPATH1)
               )
    else:
        return ''
 def getTemplate(self, container):
     site = getToolByName(container, 'portal_url').getPortalObject()
     parent = container
     container_base = Acquisition.aq_base(container)
     while parent is not None:
         template = component.queryMultiAdapter(
             (parent, self), interfaces.ITemplate)
         parent_base = Acquisition.aq_base(parent)
         if template is not None and (
             parent_base is container_base or not
             interfaces.IContainerOnlyTemplate.providedBy(template)
             ):
             return template
         if Acquisition.aq_base(parent) is site:
             return
         parent = Acquisition.aq_parent(parent)
     return interfaces.ITemplate(self, None)
Exemple #44
0
    def fixTranslationReference(self, recursive=False):
        """ fixes translation references to the canonical.
            Assumes that self is always en and canonical
            tries to handle language extensions for files like hwp_xx.swf
        """
        context = Acquisition.aq_inner(self.context)
        pl = context.portal_languages
        langs = pl.getSupportedLanguages()

        results = []
        if recursive == True:
            targetobs = context.ZopeFind(context, search_sub=1)
        else:
            targetobs = [(context.getId(), context)]
        for id, ob in targetobs:

            print "handling %s" % ob.absolute_url(1)
            if hasattr(Acquisition.aq_base(ob), '_md') and ob._md.has_key(
                    'language') and ob._md['language'] == u'':
                ob._md['language'] = u'en'

            if not hasattr(Acquisition.aq_base(ob), 'addTranslationReference'):
                continue

            if not ob.isCanonical():
                results.append("Not Canonical: %s " % ob.absolute_url())
                print "Not Canonical: %s " % ob.absolute_url()

            for lang in langs:
                if ob.hasTranslation(lang):
                    continue
                langob = self._getLangOb(ob, lang)

                if langob is None:
                    continue

                try:
                    langob.setLanguage('')
                    langob.setLanguage(lang)
                    langob.addTranslationReference(ob)
                    langpath = "/".join(langob.getPhysicalPath())
                    results.append("Adding TransRef for %s" % langpath)
                    print "Adding TransRef for %s" % langpath
                except Exception, at:
                    results.append("Except %s" % str(at))
 def _setter(ob, *args, **kw):
     flag = kw["flag"]
     subobs = ob.objectValues()
     for subob in subobs:
         if hasattr(Acquisition.aq_base(subob), "setExcludeFromNav"):
             state = subob.getExcludeFromNav()
             subob.setExcludeFromNav(flag)
             if state != flag or subob.isTranslation():
                 subob.reindexObject()
        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)
Exemple #47
0
    def registerUtility(self, component=None, provided=None, name=u'', info=u'',
                        event=True, factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                if isinstance(reg[0], ComponentPathWrapper):
                    # update path
                    self.utilities.unsubscribe((), provided, reg[0])
                    reg[0].path = component.getPhysicalPath()
                    self.utilities.subscribe((), provided, reg[0])
                return
            self.unregisterUtility(reg[0], provided, name)

        subscribed = False
        for ((p, _), data) in self._utility_registrations.iteritems():
            if p == provided and data[0] == component:
                subscribed = True
                break

        wrapped_component = component
        if getattr(component, 'aq_parent', None) is not None:
            # component is acquisition wrapped, so try to store path
            if getattr(component, 'getPhysicalPath', None) is None:
                raise AttributeError(
                    'Component %r does not implement getPhysicalPath, '
                    'so register it unwrapped or implement this method.' %
                    component)
            path = component.getPhysicalPath()
            # If the path is relative we can't store it because we
            # have nearly no chance to use the path for traversal in
            # getUtility.
            if path[0] == '':
                # We have an absolute path, so we can store it.
                wrapped_component = ComponentPathWrapper(
                    Acquisition.aq_base(component), path)

        self._utility_registrations[(provided, name)] = (
            wrapped_component, info, factory)
        self.utilities.register((), provided, name, wrapped_component)

        if not subscribed:
            self.utilities.subscribe((), provided, wrapped_component)

        if event:
            zope.event.notify(zope.component.interfaces.Registered(
                UtilityRegistration(
                    self, provided, name, component, info, factory)
                ))
Exemple #48
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 _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))
Exemple #50
0
 def _setter(ob, *args, **kw):
     flag = kw['flag']
     res = []
     try:
         ob.setDisplayAttachments(flag)
         res.append("OK: set display attachment on %s to %s" %
                    (ob.getId(), flag))
     except Exception, e:
         res.append(
             "ERR setting display attachment on %s (%s)" % ("/".join(
                 ob.getPhysicalPath()), type(Acquisition.aq_base(ob))))
Exemple #51
0
def canSerialize(obj):
    result = False

    container_type_tuple = (list, tuple, dict, set, frozenset)

    # if object is a container, we need to check its elements for presence of
    # objects that cannot be put inside the zodb
    if isinstance(obj, container_type_tuple):
        if isinstance(obj, dict):
            result_list = []
            for key, value in obj.iteritems():
                result_list.append(canSerialize(key))
                result_list.append(canSerialize(value))
        else:
            result_list = [canSerialize(element) for element in obj]
        return all(result_list)
    # if obj is an object and implements __getstate__, ZODB.serialize can check
    # if we can store it
    elif isinstance(obj, object) and hasattr(obj, '__getstate__') and hasattr(
            obj, '_p_jar'):
        # Need to unwrap the variable, otherwise we get a TypeError, because
        # objects cannot be pickled while inside an acquisition wrapper.
        unwrapped_obj = Acquisition.aq_base(obj)
        writer = ObjectWriter(unwrapped_obj)
        for obj in writer:
            try:
                writer.serialize(obj)
            # Because writer.serialize(obj) relies on the implementation of __getstate__
            # of obj, all errors can happen, so the "except all" is necessary here.
            except:
                return False
        return True
    else:
        # If cannot serialize object with ZODB.serialize, try with cPickle
        # Only a dump of the object is not enough. Dumping and trying to
        # load it will properly raise errors in all possible situations,
        # for example: if the user defines a dict with an object of a class
        # that he created the dump will stil work, but the load will fail.
        try:
            cPickle.loads(cPickle.dumps(obj))
        # By unknowing reasons, trying to catch cPickle.PicklingError in the "normal"
        # way isn't working. This issue might be related to some weirdness in
        # pickle/cPickle that is reported in this issue: http://bugs.python.org/issue1457119.
        #
        # So, as a temporary fix, we're investigating the exception's class name as
        # string to be able to identify them.
        #
        # Even though the issue seems complicated, this quickfix should be
        # properly rewritten in a better way as soon as possible.
        except (cPickle.PicklingError, TypeError, NameError,
                AttributeError) as e:
            return False
        else:
            return True
Exemple #52
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 __repr__(self):
     url = 'five'
     site = Acquisition.aq_base(self.__parent__)
     try:
         site = _wrap(site, self)
     except (ValueError, TypeError):
         pass
     path = getattr(site, 'getPhysicalPath', None)
     if path is not None and callable(path):
         url = '/'.join(path())
     return "<%s %s>" % (self.__class__.__name__, url)
Exemple #54
0
    def __iter__(self):
        context = self.transmogrifier.context
        for item in self.previous:
            if self.condition(item):
                obj = resolve_object(context, item)
                properties = [
                    (key, obj.getProperty(key), obj.getPropertyType(key))
                    for key in obj.propertyIds()
                    if hasattr(Acquisition.aq_base(obj), key)  # noqa
                ]
                item['_properties'] = properties

                if 'default_page' not in obj.propertyIds():
                    try:
                        default_page = Acquisition.aq_base(obj).default_page
                        obj['_properties'].append(
                            ('default_page', default_page, 'string'))
                    except AttributeError:
                        pass
            yield item
Exemple #55
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]
 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
 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
def constructInstance(item, type_key_matcher, path_key_matcher,
                      required, empty=True):
    portal = api.portal.get()
    types_tool = api.portal.get_tool('portal_types')

    keys = item.keys()
    type_key = type_key_matcher(*keys)[0]
    path_key = path_key_matcher(*keys)[0]

    if not (type_key and path_key):  # not enough info
        return

    type_, path = item[type_key], item[path_key]

    fti = types_tool.getTypeInfo(type_)
    if fti is None:  # not an existing type
        return

    path = path.encode('ASCII')
    container, id_ = posixpath.split(path.strip('/'))

    if not id_:  # site root should exist
        return

    context = traverse(portal, container, None)
    if context is None:
        error = 'Container %s does not exist for item %s' % (
            container, path)
        if required:
            raise KeyError(error)
        logger.warn(error)
        return

    # noinspection PyUnresolvedeferences
    exists = getattr(Acquisition.aq_base(context), id_, None)
    if getattr(exists, 'id', None) == id_:
        return

    obj = _constructInstance(fti, context, id_)

    # For CMF <= 2.1 (aka Plone 3)
    if hasattr(fti, '_finishConstruction'):
        # noinspection PyProtectedMember
        obj = fti._finishConstruction(obj)

    if obj.getId() != id_:
        item[path_key] = posixpath.join(container, obj.getId())

    if empty and obj.objectIds():
        cleanup(obj)