def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation # root if not utils.isDefaultPage(context, request) \ and not rootPath.startswith(itemPath): base += ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) return base
def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) try: name, item_url = get_view_url(context) except AttributeError: print context raise if container is None: return ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation root if not utils.isDefaultPage(context, request) and not rootPath.startswith(itemPath): base += ({'absolute_url': _checkPermission('View', context) and item_url or None, 'Title': utils.pretty_title_or_id(context, context), },) return base
def breadcrumbs(self): context = self.context request = self.request parent = aq_parent(context) name, item_url = get_view_url(context) if parent is None: return ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) view = getMultiAdapter((parent, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) else: item_url = '%s/%s' % (parent.absolute_url(), name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # Don't show default pages in breadcrumbs or pages above the navigation root if not utils.isDefaultPage(context, request) and not rootPath.startswith(itemPath): base += ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) return base
def render(self): """Render the viewlet only if there is at least one tool example in the folder and this page is set as default view for this folder. """ if (isDefaultPage(self.context, self.request) and len(self.examples) > 0): return super(ToolExamplesViewlet, self).render() return ""
def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation # root installed = packages_installed() if 'genweb.organs' in installed: if (not utils.isDefaultPage(context, request) or context.portal_type == 'genweb.organs.organsfolder') \ and not rootPath.startswith(itemPath): base += ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) else: if not utils.isDefaultPage( context, request) and not rootPath.startswith(itemPath): base += ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) return base
def breadcrumbs(self): real_context = aq_inner(self.context) request_path = self.request.get('PATH_INFO', '') if 'VirtualHostBase' in request_path: path = ('',) + re.search(r'VirtualHostBase/\w+/.*?/(.*?)/VirtualHostRoot/(.*)', request_path).groups() request_path = '/'.join(path) context_path = '/'.join(real_context.getPhysicalPath()) if request_path == context_path: context = real_context else: self.context.plone_log(request_path) parent_path = request_path[:request_path.rfind('/')] self.context.plone_log(parent_path) context = self.context.restrictedTraverse(parent_path) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ( {'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation # root if not utils.isDefaultPage(context, request) \ and not rootPath.startswith(itemPath): base += ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) if request_path != context_path: name, item_url = get_view_url(real_context) base += ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(real_context, real_context), }, ) return base return True
def latest_examples(self): """Return the latest OSH related tool examples contained in this folder (and subfolders). """ if isDefaultPage(self.context, self.request): obj = aq_parent(self.context) else: obj = self.context return get_examples(obj, limit=LIMIT, osh_related_only=True)
def _get_context(self, context, request): """ Walk up parents until a non-default-page is found. """ if not context: return None if utils.isDefaultPage(context, request): return self._get_context(aq_parent(context), request) return context
def root_item_class(self): context = aq_inner(self.context) root = self.getNavRoot() if (aq_base(root) is aq_base(context) or (aq_base(root) is aq_base(aq_parent(aq_inner(context))) and utils.isDefaultPage(context, self.request))): return 'active' else: return 'default'
def isDefaultPage(self, obj, request=None): """Finds out if the given obj is the default page in its parent folder. Only considers explicitly contained objects, either set as index_html, with the default_page property, or using IBrowserDefault. """ if request is None: request = self.REQUEST return utils.isDefaultPage(obj, request)
def root_item_class(self): context = aq_inner(self.context) root = self.getNavRoot() if (aq_base(root) is aq_base(context) or (aq_base(root) is aq_base(aq_parent(aq_inner(context))) and utils.isDefaultPage(context, self.request, context))): return 'navTreeCurrentItem' else: return ''
def _simplelayout_context(self): context = aq_inner(self.context) if ISimpleLayoutCapable.providedBy(context): return context if isDefaultPage(context, self.request): return aq_parent(context) else: return context
def update(self): """ only grab second level of links. For instance, if you are in the root, do not show this, but if you are in a folder inside the root, show this. Examples, root/future students -will show and future students will be base root/future students/undergraduate/file -same as earlier root/ -will not show """ super(CurrentSectionNav, self).update() site = self.portal_state.portal() context = aq_inner(self.context) utils = getToolByName(context, 'plone_utils') self.shoulddisplay = True if utils.isDefaultPage( context, self.request) or not utils.isStructuralFolder(context): context = aq_parent(context) if not ISectionNavigation.providedBy(context): self.shoulddisplay = False return context_path = context.getPhysicalPath() site_path = site.getPhysicalPath() nav_path = context_path[0:len(site_path) + 1] selected_item_path = context_path[0:len(site_path) + 2] #need this for the title of the nav self.nav_context = site.unrestrictedTraverse('/'.join(nav_path)) #need this to find the current item self.selected_item = site.unrestrictedTraverse( '/'.join(selected_item_path)) self.portal_tabs = buildFolderTree(context, obj=context, query={ 'query': '/'.join(nav_path), 'navtree': 1, 'navtree_start': 1, 'path': '/'.join(nav_path) }) # need to make this all one call right here for some reason, # otherwise it can't figure out the absolute_url self.nav_context_url = site.unrestrictedTraverse( '/'.join(nav_path)).absolute_url()
def available(self, info): """Only make available on definition context """ if info['settings'].get('is_local', False): compare_context = self.context if isDefaultPage(self.context, self.request): compare_context = aq_parent(aq_inner(self.context)) if '/'.join(compare_context.getPhysicalPath()) != info['key']: return False return True
def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ( {'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: if container.portal_type == "Scheda" and utils.isDefaultPage(container, request): # if the parent is a Scheda and is set as default page, it # doesn't appears in the breadcrums, so we need to use context # absolute_url instead simple concatenation item_url = context.absolute_url() else: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation # root if not utils.isDefaultPage(context, request) \ and not rootPath.startswith(itemPath): base += ( {'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) return base
def __init__(self, context): self.context = context annotations = IAnnotations(context.getCanonical()) mapping = annotations.get(KEY) if mapping is None: mapping = annotations[KEY] = PersistentDict({'locations': []}) self.mapping = mapping self.is_external = False if isDefaultPage(context, context.REQUEST): self.url = parent(context).absolute_url() else: self.url = context.absolute_url()
def show_checkout_action(self, obj): """ whether to show the action Tab 'Create Working Copy'""" iterate_control = getMultiAdapter( (obj, self.request), name='iterate_control') if iterate_control.checkout_allowed(): if isDefaultPage(obj, self.request): urls = ILinkList(self.context).urls if not urls: return True else: return True return False
def update(self): """ only grab second level of links. For instance, if you are in the root, do not show this, but if you are in a folder inside the root, show this. Examples, root/future students -will show and future students will be base root/future students/undergraduate/file -same as earlier root/ -will not show """ super(CurrentSectionNav, self).update() site = self.portal_state.portal() context = aq_inner(self.context) utils = getToolByName(context, 'plone_utils') self.shoulddisplay = True if utils.isDefaultPage(context, self.request) or not utils.isStructuralFolder(context): context = aq_parent(context) if not ISectionNavigation.providedBy(context): self.shoulddisplay = False return context_path = context.getPhysicalPath() site_path = site.getPhysicalPath() nav_path = context_path[0:len(site_path)+1] selected_item_path = context_path[0:len(site_path)+2] #need this for the title of the nav self.nav_context = site.unrestrictedTraverse('/'.join(nav_path)) #need this to find the current item self.selected_item = site.unrestrictedTraverse('/'.join(selected_item_path)) self.portal_tabs = buildFolderTree( context, obj=context, query={ 'query' : '/'.join(nav_path), 'navtree' : 1, 'navtree_start' : 1, 'path': '/'.join(nav_path) } ) # need to make this all one call right here for some reason, # otherwise it can't figure out the absolute_url self.nav_context_url = site.unrestrictedTraverse('/'.join(nav_path)).absolute_url()
def index(self): portal_title = safe_unicode(self.portal_title()) page_title = safe_unicode(self.page_title()) if page_title == portal_title: return u"<title>%s</title>" % (escape(portal_title)) else: if isDefaultPage(self.context, self.request) and not \ INavigationRoot.providedBy(aq_parent(self.context)): titles = self.getParentTitles(aq_parent(self.context)) else: titles = self.getParentTitles(self.context) titles.reverse() title_string = " — ".join(titles) return u"<title>%s — %s</title>" % ( escape(portal_title), title_string )
def breadcrumbs(self): def getTitle(context): try: if hasattr(context, 'hasProperty'): if context.hasProperty('short_breadcrumb'): alt_title = context.getProperty('short_breadcrumb') if alt_title: return alt_title except TypeError: pass return utils.pretty_title_or_id(context, context) context = aq_inner(self.context) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ({'absolute_url': item_url, 'Title': getTitle(context),}, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation root if not utils.isDefaultPage(context, request) and not rootPath.startswith(itemPath): base += ({'absolute_url': item_url, 'Title': getTitle(context), }, ) return base
def addTranslation(self, language, *args, **kwargs): """Adds a translation.""" canonical = self.getCanonical() parent = aq_parent(aq_inner(self)) if ITranslatable.providedBy(parent): parent = parent.getTranslation(language) or parent if self.hasTranslation(language): translation = self.getTranslation(language) raise AlreadyTranslated, translation.absolute_url() id = canonical.getId() while not parent.checkIdAvailable(id): id = '%s-%s' % (id, language) kwargs[config.KWARGS_TRANSLATION_KEY] = canonical if kwargs.get('language', None) != language: kwargs['language'] = language o = _createObjectByType(self.portal_type, parent, id, *args, **kwargs) # If there is a custom factory method that doesn't add the # translation relationship, make sure it is done now. if o.getCanonical() != canonical: o.addTranslationReference(canonical) self.invalidateTranslationCache() # Copy over the language independent fields schema = canonical.Schema() independent_fields = schema.filterFields(languageIndependent=True) for field in independent_fields: accessor = field.getEditAccessor(canonical) if not accessor: accessor = field.getAccessor(canonical) data = accessor() translation_mutator = getattr(o, field.translation_mutator) translation_mutator(data) # If this is a folder, move translated subobjects aswell. if self.isPrincipiaFolderish: moveids = [] for obj in self.objectValues(): if ITranslatable.providedBy(obj) and \ obj.getLanguage() == language: lockable = ILockable(obj, None) if lockable is not None and lockable.can_safely_unlock(): lockable.unlock() moveids.append(obj.getId()) if moveids: o.manage_pasteObjects(self.manage_cutObjects(moveids)) o.reindexObject() if isDefaultPage(canonical, self.REQUEST): o._lp_default_page = True
def update(self): super(AcquisitionBarViewlet, self).update() chain = self.getAcquisitionChain() pp = getToolByName(self.context, 'portal_properties').site_properties urltool = getToolByName(self.context, 'portal_url') url_not_to_list = [urltool() + '/' + path\ for path in getattr(pp,'path_not_to_list', [])] self.breadcrumbs = [] for ob in chain: if utils.isDefaultPage(ob,self.request, self.context):continue url = ob.absolute_url() if url in url_not_to_list:continue self.breadcrumbs.append({'absolute_url':ob.absolute_url(), 'Title':ob.Title()}) self.breadcrumbs.reverse() self.breadcrumbs.pop(0) #remove the first because its the root
def _latest_examples(self): """Return the latest OSH related tool examples contained in this folder (and subfolders). OSH related examples have sorting precedence over the others. """ if not isDefaultPage(self.context, self.request): return # OSH related examples should come first # (NOTE: items in list are already sorted by date) osh_related, others = [], [] for item in get_examples(aq_parent(self.context), limit=LIMIT): if item.OSH_related: osh_related.append(item) else: others.append(item) return osh_related + others
def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) name, item_url = get_view_url(context) if container is None: return ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), 'ct_class': 'contenttype-{}'.format(context.portal_type) }, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation # root if not utils.isDefaultPage(context, request) \ and not rootPath.startswith(itemPath): portal_type = context.portal_type if base_hasattr(context, '_link_portal_type'): portal_type = context._link_portal_type base += ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), 'ct_class': 'contenttype-{}'.format(portal_type) }, ) return base
def breadcrumbs(self): """ Breadcrumbs """ if ISiteRoot.providedBy(self.context): return () context = aq_inner(self.context) request = self.request container = utils.parent(context) try: name, item_url = get_view_url(context) except AttributeError: print context raise if container is None: return ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) # don't show default pages in breadcrumbs if not utils.isDefaultPage(context, request): base += ({ 'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), }, ) return base
def breadcrumbs(self): context = aq_inner(self.context) request = self.request ct = getToolByName(context, 'portal_catalog') query = {} # Check to see if the current page is a folder default view, if so # get breadcrumbs from the parent folder if utils.isDefaultPage(context, request): currentPath = '/'.join(utils.parent(context).getPhysicalPath()) else: currentPath = '/'.join(context.getPhysicalPath()) query['path'] = {'query': currentPath, 'navtree': 1, 'depth': 0} rawresult = ct(**query) # Sort items on path length dec_result = [(len(r.getPath()), r) for r in rawresult] dec_result.sort() rootPath = getNavigationRoot(context) # Build result dict result = [] for r_tuple in dec_result: item = r_tuple[1] # Don't include it if it would be above the navigation root itemPath = item.getPath() if rootPath.startswith(itemPath): continue id, item_url = get_view_url(item) data = { 'Title': utils.pretty_title_or_id(context, item), 'absolute_url': item_url } result.append(data) return result
def breadcrumbs(self): context = aq_inner(self.context) catalog = getToolByName(context, 'portal_catalog') query = {} # Check to see if the current page is a folder default view, if so # get breadcrumbs from the parent folder if utils.isDefaultPage(context, self.request): currentPath = '/'.join(utils.parent(context).getPhysicalPath()) else: currentPath = '/'.join(context.getPhysicalPath()) query['path'] = {'query': currentPath, 'navtree': 1, 'depth': 0} rawresult = catalog(**query) # Sort items on path length dec_result = [(len(r.getPath()), r) for r in rawresult] dec_result.sort() rootPath = getNavigationRoot(context) # Build result dict result = [] for r_tuple in dec_result: item = r_tuple[1] # Don't include it if it would be above the navigation root itemPath = item.getPath() if rootPath.startswith(itemPath): continue cid, item_url = get_view_url(item) data = { 'Title': utils.pretty_title_or_id(context, item), 'absolute_url': item_url } result.append(data) return result
def breadcrumbs(self): """ Breadcrumbs """ if ISiteRoot.providedBy(self.context): return () context = aq_inner(self.context) request = self.request container = utils.parent(context) try: name, item_url = get_view_url(context) except AttributeError: print context raise if container is None: return ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) # don't show default pages in breadcrumbs if not utils.isDefaultPage(context, request): base += ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), },) return base
def breadcrumbs(self): context = aq_inner(self.context) view_utils = Utils(self.context, self.request) crumbs = [] while context is not None: if ISiteRoot.providedBy(context): break try: if utils.isDefaultPage(context, self.request): context = utils.parent(context) continue except AttributeError: break # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): context = utils.parent(context) continue item_url = view_utils.get_object_url(context) try: state = api.content.get_state(obj=context) except WorkflowException: state = None label = getattr(context, 'navigation_label', None) if not label: label = utils.pretty_title_or_id(context, context) crumbs.append({ 'absolute_url': item_url, 'Title': label, 'state': state }) context = utils.parent(context) return list(reversed(crumbs))
def breadcrumbs(self): context = aq_inner(self.context) request = self.request container = utils.parent(context) try: name, item_url = get_view_url(context) except AttributeError: print context raise if hasattr(context,"UID"): if callable(context.UID): theuid = context.UID() else: theuid = context.UID else: theuid = '' if container is None: return [{'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context), 'applications':None, 'UID': theuid, 'portal_type': context.portal_type }] view = getMultiAdapter((container, request), name='breadcrumbs_view') base = view.breadcrumbs() # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): return base if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) rootPath = getNavigationRoot(context) itemPath = '/'.join(context.getPhysicalPath()) # don't show default pages in breadcrumbs or pages above the navigation root if not utils.isDefaultPage(context, request) and not rootPath.startswith(itemPath): if not base: base = [] tempapps = [] tempobj = {} tempobj['absolute_url'] = item_url tempobj['Title'] = utils.pretty_title_or_id(context,context) tempobj['UID'] = theuid tempobj['portal_type'] = context.portal_type tempobj['applications'] = [] try: if hasattr(context,'listApplications'): tempobj['applications'] = context.listApplications() except AttributeError: pass base.append(tempobj) return base
def getTopicRelativeUrl(self): if CMFPloneUtils.isDefaultPage(self.context, self.request): return '/' + aq_parent(aq_inner(self.context)).absolute_url(relative=1) else: return '/' + self.context.absolute_url(relative=1)
def getsubtab(self,context,tab): query={} result=[] portal_properties = getToolByName(context, 'portal_properties') portal_catalog = getToolByName(context, 'portal_catalog') navtree_properties = getattr(portal_properties, 'navtree_properties') site_properties = getattr(portal_properties, 'site_properties') rootPath = getNavigationRoot(context) dpath='/'.join([rootPath,tab['id']]) query['path'] = {'query' : dpath, 'depth' : 1} query['portal_type'] = utils.typesToList(context) sortAttribute = navtree_properties.getProperty('sortAttribute', None) if sortAttribute is not None: query['sort_on'] = sortAttribute sortOrder = navtree_properties.getProperty('sortOrder', None) if sortOrder is not None: query['sort_order'] = sortOrder if navtree_properties.getProperty('enable_wf_state_filtering', False): query['review_state'] = navtree_properties.getProperty('wf_states_to_show', []) query['is_default_page'] = False if site_properties.getProperty('disable_nonfolderish_sections', False): query['is_folderish'] = True # Get ids not to list and make a dict to make the search fast idsNotToList = navtree_properties.getProperty('idsNotToList', ()) excludedIds = {} for id in idsNotToList: excludedIds[id]=1 rawresult = portal_catalog.searchResults(**query) request = getattr(context, 'REQUEST', {}) objPath = None objPhysicalPath = None if context is not None: objPhysicalPath = context.getPhysicalPath() if utils.isDefaultPage(context, request): objPhysicalPath = objPhysicalPath[:-1] objPath = '/'.join(objPhysicalPath) # now add the content to results for item in rawresult: if not (excludedIds.has_key(item.getId) or item.exclude_from_nav): id, item_url = get_view_url(item) itemPath = item.getPath() isCurrent = False if objPath is not None: if objPath.startswith(itemPath): isCurrent = True data = {'name' : utils.pretty_title_or_id(context, item), 'id' : item.getId, 'url' : item_url, 'description': item.Description, 'is_current' : isCurrent} result.append(data) return result
def __init__(self, context, request): super(InvalidateCache, self).__init__(context, request) self.parent = context if utils.isDefaultPage(context, request): self.parent = aq_parent(aq_inner(context))
def buildFolderTree(context, obj=None, query={}, strategy=NavtreeStrategyBase()): """Create a tree structure representing a navigation tree. By default, it will create a full "sitemap" tree, rooted at the portal, ordered by explicit folder order. If the 'query' parameter contains a 'path' key, this can be used to override this. To create a navtree rooted at the portal root, set query['path'] to: {'query' : '/'.join(context.getPhysicalPath()), 'navtree' : 1} to start this 1 level below the portal root, set query['path'] to: {'query' : '/'.join(obj.getPhysicalPath()), 'navtree' : 1, 'navtree_start' : 1} to create a sitemap with depth limit 3, rooted in the portal: {'query' : '/'.join(obj.getPhysicalPath()), 'depth' : 3} The parameters: - 'context' is the acquisition context, from which tools will be acquired - 'obj' is the current object being displayed. - 'query' is a catalog query to apply to find nodes in the tree. - 'strategy' is an object that can affect how the generation works. It should be derived from NavtreeStrategyBase, if given, and contain: rootPath -- a string property; the physical path to the root node. If not given, it will default to any path set in the query, or the portal root. Note that in a navtree query, the root path will default to the portal only, possibly adjusted for any navtree_start set. If rootPath points to something not returned by the query by the query, a dummy node containing only an empty 'children' list will be returned. showAllParents -- a boolean property; if true and obj is given, ensure that all parents of the object, including any that would normally be filtered out are included in the tree. supplimentQuery -- a dictionary property; provides additional query terms which, if not already present in the query, are added. Useful, for example, to affect default sorting or default page behavior. nodeFilter(node) -- a method returning a boolean; if this returns False, the given node will not be inserted in the tree subtreeFilter(node) -- a method returning a boolean; if this returns False, the given (folderish) node will not be expanded (its children will be pruned off) decoratorFactory(node) -- a method returning a dict; this can inject additional keys in a node being inserted. showChildrenOf(object) -- a method returning True if children of the given object (normally the root) should be returned Returns tree where each node is represented by a dict: item - A catalog brain of this item depth - The depth of this item, relative to the startAt level currentItem - True if this is the current item currentParent - True if this is a direct parent of the current item children - A list of children nodes of this node Note: Any 'decoratorFactory' specified may modify this list, but the 'children' property is guaranteed to be there. Note: If the query does not return the root node itself, the root element of the tree may contain *only* the 'children' list. Note: Folder default-pages are not included in the returned result. If the 'obj' passed in is a default-page, its parent folder will be used for the purposes of selecting the 'currentItem'. """ portal_url = getToolByName(context, 'portal_url') portal_catalog = getToolByName(context, 'portal_catalog') rootPath = strategy.rootPath request = getattr(context, 'REQUEST', {}) # Find the object's path. Use parent folder if context is a default-page objPath = None objPhysicalPath = None if obj is not None: objPhysicalPath = obj.getPhysicalPath() if utils.isDefaultPage(obj, request): objPhysicalPath = objPhysicalPath[:-1] objPath = '/'.join(objPhysicalPath) portalPath = portal_url.getPortalPath() portalObject = portal_url.getPortalObject() # Calculate rootPath from the path query if not set. if 'path' not in query: if rootPath is None: rootPath = portalPath query['path'] = rootPath elif rootPath is None: pathQuery = query['path'] if type(pathQuery) == StringType: rootPath = pathQuery else: # Adjust for the fact that in a 'navtree' query, the actual path # is the path of the current context if pathQuery.get('navtree', False): navtreeLevel = pathQuery.get('navtree_start', 1) if navtreeLevel > 1: navtreeContextPath = pathQuery['query'] navtreeContextPathElements = navtreeContextPath[ len(portalPath) + 1:].split('/') # Short-circuit if we won't be able to find this path if len(navtreeContextPathElements) < (navtreeLevel - 1): return {'children': []} rootPath = portalPath + '/' + '/'.join( navtreeContextPathElements[:navtreeLevel - 1]) else: rootPath = portalPath else: rootPath = pathQuery['query'] rootDepth = len(rootPath.split('/')) # Determine if we need to prune the root (but still force the path to) # the parent if necessary pruneRoot = False if strategy is not None: rootObject = portalObject.unrestrictedTraverse(rootPath, None) if rootObject is not None: pruneRoot = not strategy.showChildrenOf(rootObject) # Allow the strategy to suppliment the query for keys not already # present in the query such as sorting and omitting default pages for key, value in six.iteritems(strategy.supplimentQuery): if key not in query: query[key] = value results = portal_catalog.searchResults(query) # We keep track of a dict of item path -> node, so that we can easily # find parents and attach children. If a child appears before its # parent, we stub the parent node. # This is necessary because whilst the sort_on parameter will ensure # that the objects in a folder are returned in the right order relative # to each other, we don't know the relative order of objects from # different folders. So, if /foo comes before /bar, and /foo/a comes # before /foo/b, we may get a list like (/bar/x, /foo/a, /foo/b, /foo, # /bar,). itemPaths = {} # Add an (initially empty) node for the root itemPaths[rootPath] = {'children': []} # If we need to "prune" the parent (but still allow showAllParent to # force some children), do so now if pruneRoot: itemPaths[rootPath]['_pruneSubtree'] = True def insertElement(itemPaths, item, forceInsert=False): """Insert the given 'item' brain into the tree, which is kept in 'itemPaths'. If 'forceInsert' is True, ignore node- and subtree- filters, otherwise any node- or subtree-filter set will be allowed to block the insertion of a node. """ itemPath = item.getPath() itemInserted = (itemPaths.get(itemPath, {}).get('item', None) is not None) # Short-circuit if we already added this item. Don't short-circuit # if we're forcing the insert, because we may have inserted but # later pruned off the node if not forceInsert and itemInserted: return itemPhysicalPath = itemPath.split('/') parentPath = '/'.join(itemPhysicalPath[:-1]) parentPruned = (itemPaths.get(parentPath, {}).get('_pruneSubtree', False)) # Short-circuit if we know we're pruning this item's parent # XXX: We could do this recursively, in case of parent of the # parent was being pruned, but this may not be a great trade-off # There is scope for more efficiency improvement here: If we knew we # were going to prune the subtree, we would short-circuit here each # time. In order to know that, we'd have to make sure we inserted each # parent before its children, by sorting the catalog result set # (probably manually) to get a breadth-first search. if not forceInsert and parentPruned: return isCurrent = isCurrentParent = False if objPath is not None: objpath_startswith_itempath = objPath.startswith(itemPath + '/') objpath_bigger_than_itempath = \ len(objPhysicalPath) > len(itemPhysicalPath) if objPath == itemPath: isCurrent = True elif objpath_startswith_itempath and objpath_bigger_than_itempath: isCurrentParent = True relativeDepth = len(itemPhysicalPath) - rootDepth newNode = { 'item': item, 'depth': relativeDepth, 'currentItem': isCurrent, 'currentParent': isCurrentParent, } insert = True if not forceInsert and strategy is not None: insert = strategy.nodeFilter(newNode) if insert: if strategy is not None: newNode = strategy.decoratorFactory(newNode) # Tell parent about this item, unless an earlier subtree filter # told us not to. If we're forcing the insert, ignore the # pruning, but avoid inserting the node twice if parentPath in itemPaths: itemParent = itemPaths[parentPath] if forceInsert: nodeAlreadyInserted = False for i in itemParent['children']: if i['item'].getPath() == itemPath: nodeAlreadyInserted = True break if not nodeAlreadyInserted: itemParent['children'].append(newNode) elif not itemParent.get('_pruneSubtree', False): itemParent['children'].append(newNode) else: itemPaths[parentPath] = {'children': [newNode]} # Ask the subtree filter (if any), if we should be expanding this # node if strategy.showAllParents and isCurrentParent: # If we will be expanding this later, we can't prune off # children now expand = True else: expand = getattr(item, 'is_folderish', True) if expand and (not forceInsert and strategy is not None): expand = strategy.subtreeFilter(newNode) children = newNode.setdefault('children', []) if expand: # If we had some orphaned children for this node, attach # them if itemPath in itemPaths: children.extend(itemPaths[itemPath]['children']) else: newNode['_pruneSubtree'] = True itemPaths[itemPath] = newNode # Add the results of running the query for r in results: insertElement(itemPaths, r) # If needed, inject additional nodes for the direct parents of the # context. Note that we use an unrestricted query: things we don't normally # have permission to see will be included in the tree. if strategy.showAllParents and objPath is not None: objSubPathElements = objPath[len(rootPath) + 1:].split('/') parentPaths = [] haveNode = (itemPaths.get(rootPath, {}).get('item', None) is None) if not haveNode: parentPaths.append(rootPath) parentPath = rootPath for i in range(len(objSubPathElements)): nodePath = rootPath + '/' + '/'.join(objSubPathElements[:i + 1]) node = itemPaths.get(nodePath, None) # If we don't have this node, we'll have to get it, if we have it # but it wasn't connected, re-connect it if node is None or 'item' not in node: parentPaths.append(nodePath) else: nodeParent = itemPaths.get(parentPath, None) if nodeParent is not None: nodeAlreadyInserted = False for i in nodeParent['children']: if i['item'].getPath() == nodePath: nodeAlreadyInserted = True break if not nodeAlreadyInserted: nodeParent['children'].append(node) parentPath = nodePath # If we were outright missing some nodes, find them again if len(parentPaths) > 0: query = {'path': {'query': parentPaths, 'depth': 0}} results = portal_catalog.unrestrictedSearchResults(query) for r in results: insertElement(itemPaths, r, forceInsert=True) # Return the tree starting at rootPath as the root node. return itemPaths[rootPath]
def buildFolderTree(context, obj=None, query={}, strategy=NavtreeStrategyBase()): """Create a tree structure representing a navigation tree. By default, it will create a full "sitemap" tree, rooted at the portal, ordered by explicit folder order. If the 'query' parameter contains a 'path' key, this can be used to override this. To create a navtree rooted at the portal root, set query['path'] to: {'query' : '/'.join(context.getPhysicalPath()), 'navtree' : 1} to start this 1 level below the portal root, set query['path'] to: {'query' : '/'.join(obj.getPhysicalPath()), 'navtree' : 1, 'navtree_start' : 1} to create a sitemap with depth limit 3, rooted in the portal: {'query' : '/'.join(obj.getPhysicalPath()), 'depth' : 3} The parameters: - 'context' is the acquisition context, from which tools will be acquired - 'obj' is the current object being displayed. - 'query' is a catalog query to apply to find nodes in the tree. - 'strategy' is an object that can affect how the generation works. It should be derived from NavtreeStrategyBase, if given, and contain: rootPath -- a string property; the physical path to the root node. If not given, it will default to any path set in the query, or the portal root. Note that in a navtree query, the root path will default to the portal only, possibly adjusted for any navtree_start set. If rootPath points to something not returned by the query by the query, a dummy node containing only an empty 'children' list will be returned. showAllParents -- a boolean property; if true and obj is given, ensure that all parents of the object, including any that would normally be filtered out are included in the tree. nodeFilter(node) -- a method returning a boolean; if this returns False, the given node will not be inserted in the tree subtreeFilter(node) -- a method returning a boolean; if this returns False, the given (folderish) node will not be expanded (its children will be pruned off) decoratorFactory(node) -- a method returning a dict; this can inject additional keys in a node being inserted. showChildrenOf(object) -- a method returning True if children of the given object (normally the root) should be returned Returns tree where each node is represented by a dict: item - A catalog brain of this item depth - The depth of this item, relative to the startAt level currentItem - True if this is the current item currentParent - True if this is a direct parent of the current item children - A list of children nodes of this node Note: Any 'decoratorFactory' specified may modify this list, but the 'children' property is guaranteed to be there. Note: If the query does not return the root node itself, the root element of the tree may contain *only* the 'children' list. Note: Folder default-pages are not included in the returned result. If the 'obj' passed in is a default-page, its parent folder will be used for the purposes of selecting the 'currentItem'. """ portal_url = getToolByName(context, 'portal_url') portal_catalog = getToolByName(context, 'portal_catalog') showAllParents = strategy.showAllParents rootPath = strategy.rootPath request = getattr(context, 'REQUEST', {}) # Find the object's path. Use parent folder if context is a default-page objPath = None objPhysicalPath = None if obj is not None: objPhysicalPath = obj.getPhysicalPath() if utils.isDefaultPage(obj, request): objPhysicalPath = objPhysicalPath[:-1] objPath = '/'.join(objPhysicalPath) portalPath = portal_url.getPortalPath() portalObject = portal_url.getPortalObject() # Calculate rootPath from the path query if not set. if 'path' not in query: if rootPath is None: rootPath = portalPath query['path'] = rootPath elif rootPath is None: pathQuery = query['path'] if type(pathQuery) == StringType: rootPath = pathQuery else: # Adjust for the fact that in a 'navtree' query, the actual path # is the path of the current context if pathQuery.get('navtree', False): navtreeLevel = pathQuery.get('navtree_start', 1) if navtreeLevel > 1: navtreeContextPath = pathQuery['query'] navtreeContextPathElements = navtreeContextPath[len(portalPath)+1:].split('/') # Short-circuit if we won't be able to find this path if len(navtreeContextPathElements) < (navtreeLevel - 1): return {'children': []} rootPath = portalPath + '/' + '/'.join(navtreeContextPathElements[:navtreeLevel-1]) else: rootPath = portalPath else: rootPath = pathQuery['query'] rootDepth = len(rootPath.split('/')) # Determine if we need to prune the root (but still force the path to) # the parent if necessary pruneRoot = False if strategy is not None: rootObject = portalObject.unrestrictedTraverse(rootPath, None) if rootObject is not None: pruneRoot = not strategy.showChildrenOf(rootObject) # Default sorting and threatment of default-pages if 'sort_on' not in query: query['sort_on'] = 'getObjPositionInParent' if 'is_default_page' not in query: query['is_default_page'] = False results = portal_catalog.searchResults(query) # We keep track of a dict of item path -> node, so that we can easily # find parents and attach children. If a child appears before its # parent, we stub the parent node. # This is necessary because whilst the sort_on parameter will ensure # that the objects in a folder are returned in the right order relative # to each other, we don't know the relative order of objects from # different folders. So, if /foo comes before /bar, and /foo/a comes # before /foo/b, we may get a list like (/bar/x, /foo/a, /foo/b, /foo, # /bar,). itemPaths = {} # Add an (initially empty) node for the root itemPaths[rootPath] = {'children': []} # If we need to "prune" the parent (but still allow showAllParent to # force some children), do so now if pruneRoot: itemPaths[rootPath]['_pruneSubtree'] = True def insertElement(itemPaths, item, forceInsert=False): """Insert the given 'item' brain into the tree, which is kept in 'itemPaths'. If 'forceInsert' is True, ignore node- and subtree- filters, otherwise any node- or subtree-filter set will be allowed to block the insertion of a node. """ itemPath = item.getPath() itemInserted = (itemPaths.get(itemPath, {}).get('item', None) is not None) # Short-circuit if we already added this item. Don't short-circuit # if we're forcing the insert, because we may have inserted but # later pruned off the node if not forceInsert and itemInserted: return itemPhysicalPath = itemPath.split('/') parentPath = '/'.join(itemPhysicalPath[:-1]) parentPruned = (itemPaths.get(parentPath, {}).get('_pruneSubtree', False)) # Short-circuit if we know we're pruning this item's parent # XXX: We could do this recursively, in case of parent of the # parent was being pruned, but this may not be a great trade-off # There is scope for more efficiency improvement here: If we knew we # were going to prune the subtree, we would short-circuit here each time. # In order to know that, we'd have to make sure we inserted each parent # before its children, by sorting the catalog result set (probably # manually) to get a breadth-first search. if not forceInsert and parentPruned: return isCurrent = isCurrentParent = False if objPath is not None: if objPath == itemPath: isCurrent = True elif objPath.startswith(itemPath + '/') and len(objPhysicalPath) > len(itemPhysicalPath): isCurrentParent = True relativeDepth = len(itemPhysicalPath) - rootDepth newNode = {'item': item, 'depth': relativeDepth, 'currentItem': isCurrent, 'currentParent': isCurrentParent, } insert = True if not forceInsert and strategy is not None: insert = strategy.nodeFilter(newNode) if insert: if strategy is not None: newNode = strategy.decoratorFactory(newNode) # Tell parent about this item, unless an earlier subtree filter # told us not to. If we're forcing the insert, ignore the # pruning, but avoid inserting the node twice if parentPath in itemPaths: itemParent = itemPaths[parentPath] if forceInsert: nodeAlreadyInserted = False for i in itemParent['children']: if i['item'].getPath() == itemPath: nodeAlreadyInserted = True break if not nodeAlreadyInserted: itemParent['children'].append(newNode) elif not itemParent.get('_pruneSubtree', False): itemParent['children'].append(newNode) else: itemPaths[parentPath] = {'children': [newNode]} # Ask the subtree filter (if any), if we should be expanding this node if strategy.showAllParents and isCurrentParent: # If we will be expanding this later, we can't prune off children now expand = True else: expand = getattr(item, 'is_folderish', True) if expand and (not forceInsert and strategy is not None): expand = strategy.subtreeFilter(newNode) children = newNode.setdefault('children', []) if expand: # If we had some orphaned children for this node, attach # them if itemPath in itemPaths: children.extend(itemPaths[itemPath]['children']) else: newNode['_pruneSubtree'] = True itemPaths[itemPath] = newNode # Add the results of running the query for r in results: insertElement(itemPaths, r) # If needed, inject additional nodes for the direct parents of the # context. Note that we use an unrestricted query: things we don't normally # have permission to see will be included in the tree. if strategy.showAllParents and objPath is not None: objSubPathElements = objPath[len(rootPath)+1:].split('/') parentPaths = [] haveNode = (itemPaths.get(rootPath, {}).get('item', None) is None) if not haveNode: parentPaths.append(rootPath) parentPath = rootPath for i in range(len(objSubPathElements)): nodePath = rootPath + '/' + '/'.join(objSubPathElements[:i+1]) node = itemPaths.get(nodePath, None) # If we don't have this node, we'll have to get it, if we have it # but it wasn't connected, re-connect it if node is None or 'item' not in node: parentPaths.append(nodePath) else: nodeParent = itemPaths.get(parentPath, None) if nodeParent is not None: nodeAlreadyInserted = False for i in nodeParent['children']: if i['item'].getPath() == nodePath: nodeAlreadyInserted = True break if not nodeAlreadyInserted: nodeParent['children'].append(node) parentPath = nodePath # If we were outright missing some nodes, find them again if len(parentPaths) > 0: query = {'path': {'query': parentPaths, 'depth': 0}} results = portal_catalog.unrestrictedSearchResults(query) for r in results: insertElement(itemPaths, r, forceInsert=True) # Return the tree starting at rootPath as the root node. return itemPaths[rootPath]
def _get_context(ctx, req): if not ctx: return None if isDefaultPage(ctx, req): return _get_context(aq_parent(ctx), req) return ctx
def isPortalOrDefaultChild(self): context = aq_inner(self.context) root = self.getNavRoot() return (aq_base(root) == aq_base(context) or (aq_base(root) == aq_base(aq_parent(aq_inner(context))) and utils.isDefaultPage(context, self.request, context)))
def getTopicRelativeUrl(self): if CMFPloneUtils.isDefaultPage(self.context, self.request): return '/' + aq_parent(aq_inner( self.context)).absolute_url(relative=1) else: return '/' + self.context.absolute_url(relative=1)
def has_folderish_default(self): if not IFolderishType.providedBy(self.context): return False return isDefaultPage(self.context, self.request)