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
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))
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 UNLOCK(self, REQUEST, RESPONSE): """ Unlocking a Null Resource removes it from its parent """ self.dav__init(REQUEST, RESPONSE) security = getSecurityManager() user = security.getUser() token = REQUEST.get_header('Lock-Token', '') url = REQUEST['URL'] if token: token = tokenFinder(token) else: raise BadRequest, 'No lock token was submitted in the request' cmd = davcmds.Unlock() result = cmd.apply(self, token, url) parent = Acquisition.aq_parent(self) parent._delObject(self.id) if result: RESPONSE.setStatus(207) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setBody(result) else: RESPONSE.setStatus(204) return RESPONSE
def handleException(self, object, request, exc_info, retry_allowed=True): transaction.abort() # TODO handle Retry, ConflictError, etc. # TODO handle logging exception_type, exception, traceback = exc_info loc = object if Acquisition.aq_parent(object) is None: # Try to get an object, since we apparently have a method # Note: We are guaranteed that an object has a location, # so just getting the instance the method belongs to is # sufficient. loc = getattr(loc, 'im_self', loc) loc = getattr(loc, '__self__', loc) # Give the exception instance its location and look up the # view. exception = LocationProxy(exception, loc, '') name = queryDefaultViewName(exception, request) if name is not None: # TODO annotate the transaction view = queryMultiAdapter((exception, request), name=name) if view is not None: # XXX should we use mapply here? body = self.callObject(request, view) request.response.setResult(body) transaction.commit() else: # This is the last resort. We shouldn't get here, but # in case we do, we have to set the result to something. request.response.setStatus(500) request.response.setResult('An error occurred.')
def createObjectAsPortalOwner(container, type_name, id_): """Create an object as the portal owner""" info = interfaces.ITemplateTypeInfo( container.portal_types.getTypeInfo(type_name), None) if info is None: return template = info.getTemplate(container) if template is None: return source = Acquisition.aq_parent(Acquisition.aq_inner(template)) sm = SecurityManagement.getSecurityManager() SecurityManagement.newSecurityManager( None, container.portal_url.getPortalObject().getOwner()) result, = container.manage_pasteObjects( source.manage_copyObjects([template.getId()])) container.manage_renameObject(result['new_id'], id_) SecurityManagement.setSecurityManager(sm) added = container[id_] owner.changeOwnershipOf(added) event.notify(interfaces.TemplateCopiedEvent(added, template)) return added
def 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
def _setter(ob, *args, **kw): if ob.isPrincipiaFolderish: tool = getattr(Acquisition.aq_parent(ob), "portal_languages") if tool.id in ob.objectIds(): ob._delObject(tool.id) newob = tool._getCopy(tool) newob._setId(tool.id) notify(ObjectCopiedEvent(newob, tool)) ob._setOb(tool.id, newob) ob._objects = ob._objects + (dict(meta_type=tool.meta_type, id=tool.id),) newob = ob._getOb(tool.id) newob.wl_clearLocks() newob._postCopy(ob, op=0) newob.manage_afterClone(newob) notify(ObjectClonedEvent(newob)) languages = kw.get("languages", None) if languages: if isinstance(languages, tuple): languages = list(languages) elif isinstance(languages, types.StringType) or isinstance(languages, types.UnicodeType): languages = [languages] newob.supported_langs = languages return ["Added language tool to %s" % ob.getId()]
def __getattr__(self, name): blacklist = ['im_func', 'func_code', 'index_html'] if name.startswith('_') or name in blacklist: raise AttributeError(name) # Check if there is views/<self.__name__>.<name>.py in the theme, if not raise # noqa currentTheme = getCurrentTheme() if currentTheme is None: raise AttributeError(name) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) # noqa if themeDirectory is None: raise AttributeError(name) script = None scriptPath = "%s/%s.py" % (FRAGMENTS_DIRECTORY, self.__name__) if themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if six.PY3 and isinstance(script, six.binary_type): script = script.decode('utf8') if 'def {0:}(self'.format(name) in script: script += '\n\nreturn {0:s}(self)'.format(name) else: script = None scriptPath = "%s/%s.%s.py" % (FRAGMENTS_DIRECTORY, self.__name__, name) if script is None and themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if six.PY3 and isinstance(script, six.binary_type): script = script.decode('utf8') if script is None: raise AttributeError(name) # Set the default PythonScript bindings as globals script_globals = { 'script': self, 'context': self.context, 'container': Acquisition.aq_parent(self.context), 'traverse_subpath': '' } # Build re-usable restricted function components like in PythonScript try: code, g, defaults = prepare_restricted_function( 'self,*args,**kwargs', script or 'pass', name, scriptPath, list(script_globals.keys())) except SyntaxError: raise AttributeError(name) # Update globals g = g.copy() g.update(script_globals) g['__file__'] = scriptPath func = types.FunctionType(code, g, None, defaults) # Return the func as instancemethod return types.MethodType(func, self)
def listobjects(self): context = Acquisition.aq_inner(self.context) container = Acquisition.aq_parent(context) objects = container.objectValues(['ATDocument', 'RichDocument']) ip = container.getDefaultPage() filtered_objects = [x for x in objects if x.getId()!=ip] return filtered_objects
def _setter(ob, *args, **kw): if ob.isPrincipiaFolderish: tool = getattr(Acquisition.aq_parent(ob), 'portal_languages') if tool.id in ob.objectIds(): ob._delObject(tool.id) newob = tool._getCopy(tool) newob._setId(tool.id) notify(ObjectCopiedEvent(newob, tool)) ob._setOb(tool.id, newob) ob._objects = ob._objects + (dict(meta_type=tool.meta_type, id=tool.id), ) newob = ob._getOb(tool.id) newob.wl_clearLocks() newob._postCopy(ob, op=0) newob.manage_afterClone(newob) notify(ObjectClonedEvent(newob)) languages = kw.get('languages', None) if languages: if isinstance(languages, tuple): languages = list(languages) elif isinstance(languages, types.StringType) or isinstance( languages, types.UnicodeType): languages = [languages] newob.supported_langs = languages return ["Added language tool to %s" % ob.getId()]
def upload_url(self): context = Acquisition.aq_inner(self.context) if context.restrictedTraverse('@@plone').isStructuralFolder(): url = context.absolute_url() else: url = Acquisition.aq_parent(context).absolute_url() return url + '/@@load'
def listobjects(self): context = Acquisition.aq_inner(self.context) container = Acquisition.aq_parent(context) objects = container.objectValues(['ATDocument', 'RichDocument']) ip = container.getDefaultPage() filtered_objects = [x for x in objects if x.getId() != ip] return filtered_objects
def __getattr__(self, name): blacklist = ['im_func', 'func_code', 'index_html'] if name.startswith('_') or name in blacklist: raise AttributeError(name) # Check if there is views/<self.__name__>.<name>.py in the theme, if not raise # noqa currentTheme = getCurrentTheme() if currentTheme is None: raise AttributeError(name) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) # noqa if themeDirectory is None: raise AttributeError(name) script = None scriptPath = "%s/%s.py" % (FRAGMENTS_DIRECTORY, self.__name__) if themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if 'def {0:}(self'.format(name) in script: script += '\n\nreturn {0:s}(self)'.format(name) else: script = None scriptPath = "%s/%s.%s.py" % (FRAGMENTS_DIRECTORY, self.__name__, name) if script is None and themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if script is None: raise AttributeError(name) # Set the default PythonScript bindings as globals script_globals = { 'script': self, 'context': self.context, 'container': Acquisition.aq_parent(self.context), 'traverse_subpath': '' } # Build re-usable restricted function components like in PythonScript try: code, g, defaults = prepare_restricted_function( 'self,*args,**kwargs', script or 'pass', name, scriptPath, script_globals.keys() ) except SyntaxError: raise AttributeError(name) # Update globals g = g.copy() g.update(script_globals) g['__file__'] = scriptPath func = new.function(code, g, None, defaults) # Return the func as instancemethod return types.MethodType(func, self)
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 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 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 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: sm.registerUtility(ui_domain, ITranslationDomain, 'ui') del portal._save_ui_domain
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
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))
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 _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 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 render(self): """ render only if we're in a translatable folder """ parent = Acquisition.aq_parent(self.context) if getattr(parent, 'contains_translations', False): # Call parent method which performs the actual rendering return self.index() else: # No output when the viewlet is disabled return ""
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!"
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
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 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 get_container_of_original(self, obj, manual=False): """ If the obj is a working copy, return the container of the original""" if IHomeFolder.providedBy(self.context) or manual: if ICatalogBrain.providedBy(obj): obj = obj.getObject() iterate_control = getMultiAdapter( (obj, self.request), name='iterate_control') original = iterate_control.get_original(obj) if original: return safe_unicode(Acquisition.aq_parent(original).Title()) return ""
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
def _forAllLangs(self, method, *args, **kw): """ helper method. Takes a method and executes it on all language versions of context """ context = Acquisition.aq_inner(self.context) status = IStatusMessage(self.request) changes_made = False for lang in self.langs: lpath = self.dynamic_path % lang base = context.getTranslation(lang) if base is None: base = context.restrictedTraverse(lpath, None) # make sure that the base found by restrictedTraverse has the # same parent as the context! if base is None or Acquisition.aq_parent(base) != Acquisition.aq_parent(context): log.info("Break for lang %s, base is none" % lang) continue else: log.warn( "Object found at %s which is not linked as a " "translation of %s" % (lpath, "/".join(context.getPhysicalPath())) ) status.addStatusMessage( _( "Object found at %s which is not linked as a " "translation of %s" % (lpath, "/".join(context.getPhysicalPath())) ), type="info", ) kw["lang"] = lang method(base, *args, **kw) log.info("Executing for language %s" % lang) status.addStatusMessage(_(u"Changes made for language %s" % lang), type="info") changes_made = True return changes_made
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 __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 setGlobalTranslationService(translation_service): global global_translation_service global_translation_service = translation_service zope.component.provideUtility(DummyTranslationDomainFallback, provides=IFallbackTranslationDomainFactory) # disable translation for the 'ui' domain so it can use the fallback above. # Save it on a portal attribute since we don't have access to the test # class sm = zope.component.getSiteManager() portal = Acquisition.aq_parent(sm) ui_domain = sm.getUtility(ITranslationDomain, name='ui') # store in a list to avoid acquisition wrapping portal._save_ui_domain = [ui_domain] sm.unregisterUtility(provided=ITranslationDomain, name='ui')
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 __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
def availableSources(context): """List available sources in the site starting at context. """ sources = {} while context is not None: for item in context.objectValues(): if (IExternalSource.providedBy(item) and item.id not in sources and item.is_usable()): sources[item.id] = item if IRoot.providedBy(context): break context = Acquisition.aq_parent(context) sources = sources.items() sources.sort(key=lambda i: i[1].get_title().lower()) return sources
def availableSources(context): """List available sources in the site starting at context. """ sources = {} while context is not None: for item in context.objectValues(): if (IExternalSource.providedBy(item) and item.id not in sources and item.is_usable()): sources[item.id] = item if IRoot.providedBy(context): break context = Acquisition.aq_parent(context) sources = list(sources.items()) sources.sort(key=lambda i: i[1].get_title().lower()) return sources
def _sectionCmp(a, b): # XXX: convert into an ordering adapter for Plone 4 # depends on cmp(True, False) == 1 ash = getattr(a, 'getStartHere', False) bsh = getattr(b, 'getStartHere', False) if ash == bsh: if PLONE4: from plone.folder.interfaces import IOrdering ordering = getAdapter(Acquisition.aq_parent(a.getObject()), IOrdering) return cmp(ordering.getObjectPosition(a.id), ordering.getObjectPosition(b.id)) else: # Plone 3 return cmp(a.getObjPositionInParent(), b.getObjPositionInParent()) elif ash: return -1 else: return 1
def collection_url(self): collection = self.collection() if collection is None: return None if self.data.show_more == 'direct': return collection.absolute_url() else: collectionpath = "/".join(collection.getPhysicalPath()) context = Acquisition.aq_inner(self.context) if not context.isPrincipiaFolderish: context = Acquisition.aq_parent(context) contextpath = "/".join(context.getPhysicalPath()) return "%s/@@oshtopic-view?tp=%s" % (context.absolute_url(), collectionpath)
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)
def __iter__(self): portal = api.portal.get() key = self.options.get('key', '_gopip') for item in self.previous: position = item.get(key) if self.condition(item) and position is not None: try: ob = traverse(portal, item['_path']) except KeyError: pass if ob: id_ = ob.getId() parent = Acquisition.aq_parent(ob) if hasattr(Acquisition.aq_base(parent), 'moveObjectToPosition'): parent.moveObjectToPosition( id_, position, suppress_events=False) yield item
def __iter__(self): portal = api.portal.get() key = self.options.get('key', '_gopip') for item in self.previous: position = item.get(key) if self.condition(item) and position is not None: try: ob = traverse(portal, item['_path']) except KeyError: pass if ob: id_ = ob.getId() parent = Acquisition.aq_parent(ob) if hasattr(Acquisition.aq_base(parent), 'moveObjectToPosition'): parent.moveObjectToPosition(id_, position, suppress_events=False) yield item
def collection_url(self): collection = self.collection() if collection is None: return None collectionpath = "/".join(collection.getPhysicalPath()) context = Acquisition.aq_inner(self.context) if not context.isPrincipiaFolderish: context = Acquisition.aq_parent(context) contextpath = "/".join(context.getPhysicalPath()) # If the shown collection is within the current context, reference it directly if collectionpath.startswith(contextpath): return collection.absolute_url() # If the collection is in a different place in the site, use the proxy view else: return "%s/@@oshtopic-view?tp=%s" % (context.absolute_url(), collectionpath)
def _sectionCmp(a, b): # XXX: convert into an ordering adapter for Plone 4 # depends on cmp(True, False) == 1 ash = getattr(a, 'getStartHere', False) bsh = getattr(b, 'getStartHere', False) if ash == bsh: if PLONE4: from plone.folder.interfaces import IOrdering ordering = getAdapter(Acquisition.aq_parent(a.getObject()), IOrdering) try: return cmp(ordering.getObjectPosition(a.id), ordering.getObjectPosition(b.id)) except ValueError: # not comparable; these items are probably not in the same folder return 0 else: # Plone 3 return cmp(a.getObjPositionInParent(), b.getObjPositionInParent()) elif ash: return -1 else: return 1
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 parents(context, iface=None): """Iterate through parents for the context (providing the given interface). Return generator to walk the acquisition chain of object, considering that it could be a function. Source: http://plone.org/documentation/manual/developer-manual/archetypes/ appendix-practicals/b-org-creating-content-types-the-plone-2.5-way/ writing-a-custom-pas-plug-in """ context = Acquisition.aq_inner(context) while context is not None: if iface.providedBy(context): yield context funcObject = getattr(context, "im_self", None) if funcObject is not None: context = Acquisition.aq_inner(funcObject) else: # Don't use Acquisition.aq_inner() since portal_factory (and # probably other) things, depends on being able to wrap itself in a # fake context. context = Acquisition.aq_parent(context)