def reindex_neutral(obj, event): # we need to look for the parent that is already indexed if IPloneSiteRoot.providedBy(obj) \ or (not is_shared(obj) and not is_shared_original(obj)): return parent = aq_parent(obj) if ILanguageRootFolder.providedBy(parent): # If it's parent is language root folder no need to reindex return site = getSite() language_tool = getToolByName(site, 'portal_languages') language_infos = language_tool.supported_langs if IPloneSiteRoot.providedBy(parent): # It's plone site root we need to look at LRF for language_info in language_infos: lrf_to_reindex = getattr(parent, language_info, None) to_reindex = getattr(lrf_to_reindex, obj.id, None) if to_reindex is not None: to_reindex.reindexObject() else: content_id = IUUID(parent).split('-')[0] pc = getToolByName(site, 'portal_catalog') for language_info in language_infos: brains = pc.unrestrictedSearchResults( UID=content_id + '-' + language_info) if len(brains): obj.unrestrictedTraverse( brains[0].getPath() + '/' + obj.id).reindexObject() return
def get_urls(self): urls = [] urls.append({'rel': 'self', 'template': self.context.absolute_url() + '/' + self.__name__, 'type': 'application/opensearchdescription+xml', 'indexOffset' : None}) urls.append({'rel': 'results', 'template': self.context.absolute_url() + '/opensearch_rss.xml?SearchableText={searchTerms}&b_start:int={startIndex?}&b_size:int={count?}', 'type': 'application/rss+xml', 'indexOffset' : '0'}) urls.append({'rel': 'results', 'template': self.context.absolute_url() + '/opensearch_atom.xml?SearchableText={searchTerms}&b_start:int={startIndex?}&b_size:int={count?}', 'type': 'application/atom+xml', 'indexOffset' : '0'}) if self.settings.suggestion_limit > 0 and IPloneSiteRoot.providedBy(self.context): urls.append({'rel': 'suggestions', 'template': self.context.absolute_url() + '/opensearch_suggestions?command={searchTerms}', 'type': 'application/x-suggestions+json', 'indexOffset' : None}) if IPloneSiteRoot.providedBy(self.context): urls.append({'rel': 'results', 'template': self.context.absolute_url() + '/search?SearchableText={searchTerms}', 'type': 'text/html', 'indexOffset' : '0'}) elif IATTopic.providedBy(self.context): urls.append({'rel': 'results', 'template': self.context.absolute_url() + '/opensearch_html.html?SearchableText={searchTerms}', 'type': '"text/html', 'indexOffset' : '0'}) return urls
def find_content_with_wrong_language(content): """log non-default content with different languages than their parents Used to make sure we cleaned up everything. In part stolen and adapted from plone.app.multilingual.browser.migrator.moveContentToProperRLF.findContent """ # only handle portal content from plone.dexterity.interfaces import IDexterityContent from Products.Archetypes.interfaces import IBaseObject from Acquisition import aq_base from Acquisition import aq_parent try: from Products.LinguaPlone.interfaces import ITranslatable except ImportError: from plone.app.multilingual.interfaces import ITranslatable if not IDexterityContent.providedBy(content)\ and not IBaseObject.providedBy(content)\ and not IPloneSiteRoot.providedBy(content): return if hasattr(aq_base(content), 'objectIds'): for id in content.objectIds(): find_content_with_wrong_language(getattr(content, id)) if ITranslatable.providedBy(content): # The content parent has the same language? if not IPloneSiteRoot.providedBy(aq_parent(content)) \ and aq_parent(content).Language() != content.Language(): log.info('Obj %s (%s) not same language as parent (%s)' % (content.absolute_url_path(), content.Language(), aq_parent(content).Language())) # noqa: E501
def listPloneSites(zope): out = [] for item in zope.values(): if IFolder.providedBy(item) and not IPloneSiteRoot.providedBy(item): for site in item.values(): if IPloneSiteRoot.providedBy(site): out.append(site) elif IPloneSiteRoot.providedBy(item): out.append(item) return out
def listPloneSites(zope): """ List the available plonesites to be used by other function """ out = [] for item in zope.values(): if IFolder.providedBy(item) and not IPloneSiteRoot.providedBy(item): for site in item.values(): if IPloneSiteRoot.providedBy(site): out.append(site) elif IPloneSiteRoot.providedBy(item): out.append(item) return out
def client_id_cachekey(method): """chackekey for the get_client_id, wich is unique for every plone site. So a setup with multiple opengever sites on one plone instance is possible. """ context = getSite() if not IPloneSiteRoot.providedBy(context): for obj in context.aq_chain: if IPloneSiteRoot.providedBy(obj): context = obj break return 'get_client_id:%s' % (context.id)
def admin_unit_cachekey(method): """chackekey for `get_current_admin_unit` wich is unique for every plone site. This makes a setup with multiple opengever sites on one zope possible. """ context = getSite() if not IPloneSiteRoot.providedBy(context): for obj in context.aq_chain: if IPloneSiteRoot.providedBy(obj): context = obj break return 'get_current_admin_unit:%s' % (context.id)
def update(self): if IPloneSiteRoot.providedBy(self.context): self.site_title = self.site_title_setting return portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') if IPloneSiteRoot.providedBy(portal_state.navigation_root()): portal_title = self.site_title_setting else: portal_title = escape( safe_unicode(portal_state.navigation_root_title())) if self.page_title == portal_title: self.site_title = portal_title else: self.site_title = self.sep.join([self.page_title, portal_title])
def get_portlet_assingment(context, uid): context_orgin = context for name in [u"plone.leftcolumn", u"plone.rightcolumn", u"collective.teaser.portletmanager"]: manager = getUtility(IPortletManager, name=name) for category in manager.values(): for group in category.values(): for assignment in group.values(): if ITeaserPortlet.providedBy(assignment): if uid == str(assignment.uid): return assignment context = aq_inner(context_orgin) while True: try: assignment_mapping = getMultiAdapter( (context, manager), IPortletAssignmentMapping ) except: return for assignment in assignment_mapping.values(): if ITeaserPortlet.providedBy(assignment): if uid == str(assignment.uid): return assignment if IPloneSiteRoot.providedBy(context): break context = aq_parent(aq_inner(context)) raise KeyError(u"Portlet assignment for uid '%s' not found." % uid)
def _findSource(self, fieldname, search_refs=True): """Find a parent item that contains valid information in [fieldname]""" item = self.context source = None while not (source or INavigationRoot.providedBy(item) or IPloneSiteRoot.providedBy(item)): if hasattr(item, 'markedAs') and item.markedAs.lower() == u"dossier": # check whether item has field filled in if item.Schema()[fieldname].get(item): source = item else: if search_refs: # find theme through ref catalog theme = item.reference_catalog(targetUID=item.UID(), relationship='itemsInTheme') # Reference to Dossier found in Theme if theme: # Assume a Dossier is always related to ONE theme source = theme[0].getObject().getSourceObject() if not source: item = item.aq_parent return source
def handle_remove_event(context, event): """ Before a object is remvoed the event handler crates a remove job. """ # the event is notified for every subobject, but we only want to check # the top object which the users tries to delete if context is not event.object: return if is_sl_contentish(context): # Do not delete sl contentish objects, they are deleted when the # associated sl container is published. return # Find the workflow object by walking up. We may be deleting a file # within a file-block within a page, where file and file-block have no # workflow and we check the page workflow. obj = context state = None while not IPloneSiteRoot.providedBy(obj): state = getMultiAdapter((obj, context.REQUEST), IPublisherContextState) if state.has_workflow(): break else: obj = aq_parent(aq_inner(obj)) if not state.has_workflow() or not state.has_publisher_config(): # plone site reached without finding a workflow, therefore # the object was never published. return context.restrictedTraverse('@@publisher.delete')(no_response=True)
def get_acquired_base_object(minisite_obj, path): obj = minisite_obj path = path.split('@@')[0] contents = path.strip('/').split('/') parent_id = contents[0] child_id = len(contents) > 1 and contents[1] or None while not IPloneSiteRoot.providedBy(obj): parent = aq_parent(aq_inner(obj)) if parent is None: break obj = parent if safe_hasattr(aq_base(obj), parent_id): if not child_id: return obj container = getattr(aq_base(obj), parent_id) if safe_hasattr(container, child_id): try: obj_url = '/'.join(obj.getPhysicalPath()) full_url = "{0}{1}".format( obj_url, path, ) api.content.get(full_url) except Unauthorized: continue except NotFound: continue else: return obj
def get_tinymce_options(context, field, request): args = {'pattern_options': {}} folder = context if not IFolderish.providedBy(context): folder = aq_parent(context) if IPloneSiteRoot.providedBy(folder): initial = None else: initial = IUUID(folder, None) portal_url = get_portal_url(context) current_path = folder.absolute_url()[len(portal_url):] utility = getToolByName(aq_inner(context), 'portal_tinymce', None) if utility: # Plone 4.3 config = utility.getConfiguration(context=context, field=field, request=request) config['content_css'] = config['portal_url'] + '/base.css' del config['customplugins'] del config['plugins'] del config['theme'] config[ 'content_css'] = '++resource++plone.app.widgets-tinymce-content.css' args['pattern_options'] = { 'relatedItems': { 'vocabularyUrl': config['portal_url'] + '/@@getVocabulary?name=plone.app.vocabularies.Catalog' }, 'upload': { 'initialFolder': initial, 'currentPath': current_path, 'baseUrl': config['document_base_url'], 'relativePath': '@@fileUpload', 'uploadMultiple': False, 'maxFiles': 1, 'showTitle': False }, 'tiny': config, # This is for loading the languages on tinymce 'loadingBaseUrl': '++resource++plone.app.widgets.tinymce', 'prependToUrl': 'resolveuid/', 'linkAttribute': 'UID', 'prependToScalePart': '/@@images/image/', 'folderTypes': utility.containsobjects.replace('\n', ','), 'imageTypes': utility.imageobjects.replace('\n', ','), 'anchorSelector': utility.anchor_selector, 'linkableTypes': utility.linkable.replace('\n', ',') } else: # Plone 5 # They are set on the body pattern_options = getMultiAdapter( (context, request, field), name="tinymce_settings")()['data-pat-tinymce'] args['pattern_options'] = json.loads(pattern_options) return args
def parent_url(self): """ """ context = aq_inner(self.context) portal_membership = getToolByName(context, 'portal_membership') obj = context checkPermission = portal_membership.checkPermission # Abort if we are at the root of the portal if IPloneSiteRoot.providedBy(context): return None # Get the parent. If we can't get it (unauthorized), use the portal parent = aq_parent(obj) # # We may get an unauthorized exception if we're not allowed to access# # the parent. In this case, return None try: if getattr(parent, 'getId', None) is None or \ parent.getId() == 'talkback': # Skip any Z3 views that may be in the acq tree; # Skip past the talkback container if that's where we are parent = aq_parent(parent) if not checkPermission('List folder contents', parent): return None return parent.absolute_url() except Unauthorized: return None
def get_portlet_assingment(context, uid): context_orgin = context for name in [ u"plone.leftcolumn", u"plone.rightcolumn", u"collective.teaser.portletmanager" ]: manager = getUtility(IPortletManager, name=name) for category in manager.values(): for group in category.values(): for assignment in group.values(): if ITeaserPortlet.providedBy(assignment): if uid == str(assignment.uid): return assignment context = aq_inner(context_orgin) while True: try: assignment_mapping = getMultiAdapter((context, manager), IPortletAssignmentMapping) except: return for assignment in assignment_mapping.values(): if ITeaserPortlet.providedBy(assignment): if uid == str(assignment.uid): return assignment if IPloneSiteRoot.providedBy(context): break context = aq_parent(aq_inner(context)) raise KeyError(u"Portlet assignment for uid '%s' not found." % uid)
def get_parent_uids(self): uids = [] context = self.context while not IPloneSiteRoot.providedBy(context): uids.append(IUUID(context, None)) context = aq_parent(context) return [uid for uid in uids if uid is not None]
def language_filter(query): if query.get('Language') == 'all': del query['Language'] return for key in NO_FILTER: # any "nofilter" indexing prevent mangling if key in query: return site = getSite() languageTool = getToolByName(site, 'portal_languages', None) if languageTool is None: return query['Language'] = [languageTool.getPreferredLanguage(), LANGUAGE_INDEPENDENT] old_path = query.get('path', None) # In case is a depth path search if isinstance(old_path, dict) and 'query' in old_path and IPloneSiteRoot.providedBy(site): old_path_url = old_path['query'] # We are going to check if is language root root_path = '/'.join(site.getPhysicalPath()) # Check if it is a language root folder to add the shared folder # fgr: when location query can be a list (for now maybe only in oldstyle collections # but I expect new style collections may get the option of multiple paths as well # in that case no SHARED_NAME needs to be added, because the path criterions are # defined either with languagefolder or language neutral context already. # may be this fix is somewhat dirty ... -fgr if old_path and old_path['query']: if isinstance(old_path['query'],str) and \ old_path['query'].split('/')[-1] in _languagelist: old_path['query'] = [old_path_url, root_path + '/' + SHARED_NAME]
def getObjectsFromLinks(base, links): """ determine actual objects refered to by given links """ intids = getUtility(IIntIds) objects = set() url = base.absolute_url() scheme, host, path, query, frag = urlsplit(url) for link in links: s, h, path, q, f = urlsplit(link) # relative or local url if (not s and not h) or (s == scheme and h == host): # Paths should always be strings if isinstance(path, unicode): path = path.encode('utf-8') obj, extra = findObject(base, path) if obj and not IPloneSiteRoot.providedBy(obj): try: objid = intids.getId(obj) except KeyError: try: intids.register(obj) objid = intids.getId(obj) except NotYet: # if we get a NotYet error, the object is not # attached yet and we will need to get links # at a later time when the object has an intid continue relation = RelationValue(objid) objects.add(relation) return objects
def getThemeCentre(context): """ Looks up the closest theme centre. """ count = 0 while context and not IPloneSiteRoot.providedBy(context) and \ not IThemeCentre.providedBy(context): # plone4 migration # If type(context) == 'plone.keyring.keyring.Keyring' # enters a infinite cycle or # context is <plone.app.portlets.portlets.navigation .. # Below there are some cases trated not to enter a infinite cycle. # This happens only on tests. count += 1 if count == 50: break context_id = getattr(context, 'getId', None) if context_id: context_id = context_id() if context_id in ['navigation']: break elif '++' in context_id: break if context == [None, None, None, None]: break context = aq_parent(context) if IThemeCentre.providedBy(context): return context return None
def render(self): portal = getSite() current_user = api.user.get_current() userid = current_user.id tag = self.request.form['tag'] soup_tags = get_soup('user_subscribed_tags', portal) exist = [r for r in soup_tags.query(Eq('id', userid))] if not exist: record = Record() record.attrs['id'] = userid record.attrs['tags'] = [tag] soup_tags.add(record) else: subscribed = [True for utag in exist[0].attrs['tags'] if utag == tag] if subscribed: exist[0].attrs['tags'].remove(tag) else: exist[0].attrs['tags'].append(tag) soup_tags.reindex() if IPloneSiteRoot.providedBy(self.context): self.request.response.redirect(self.context.absolute_url() + '/alltags') else: self.request.response.redirect(self.context.absolute_url())
def parent_info(self): """query parent url for back to overview link""" portal_url = getToolByName(self.context, 'portal_url') plone_utils = getToolByName(self.context, 'plone_utils') portal_membership = getToolByName(self.context, 'portal_membership') obj = self.context checkPermission = portal_membership.checkPermission # There is no parent if we are at the root of the portal if IPloneSiteRoot.providedBy(self.context): return None # Get the parent: we may get an unauthorized exception if we are # not allowed to access the parent. In this case, use the portal parent = aq_parent(aq_inner(obj)) try: if getattr(parent, 'getId', None) is None or parent.getId() == 'talkback': # Skip past the discussion items, aka the talkback container parent = aq_parent(aq_inner(parent)) if not checkPermission('List folder contents', parent): return None return [dict(title=parent.Title, url=parent.absolute_url)] except Unauthorized: return None
def get_context(self, context): """helper for get the context, even no context is given.""" if not context or not IPloneSiteRoot.providedBy(context): context = api.portal.get() return context
def language_filter(query): if query.get('Language') == 'all': del query['Language'] return for key in NO_FILTER: # any "nofilter" indexing prevent mangling if key in query: return site = getSite() languageTool = getToolByName(site, 'portal_languages', None) if languageTool is None: return query['Language'] = [ languageTool.getPreferredLanguage(), LANGUAGE_INDEPENDENT ] old_path = query.get('path', None) # In case is a depth path search if isinstance(old_path, dict) and 'query' in old_path and\ IPloneSiteRoot.providedBy(site): old_path_url = old_path['query'] # We are going to check if is language root root_path = '/'.join(site.getPhysicalPath()) # Check is a language root folder to add the shared folder if old_path['query'].split('/')[-1] in _languagelist: old_path['query'] = [old_path_url, root_path + '/' + SHARED_NAME]
def __init__(self, context): permissions = [MANAGE_SHOP_PERMISSION] super(ShopPortletControlpanelLink, self).__init__( context, view_permissions=permissions) # Find the nearest context, where this functionality can be bound to. def _find_context(ctx): return ctx\ if ISite.providedBy(ctx)\ else _find_context(aq_parent(ctx)) context = _find_context(context) if IPloneSiteRoot.providedBy(context): self.title = _( 'shop_controlpanel_global', default=u'Shop Controlpanel (global)' ) elif ISite.providedBy(context): self.title = _( 'shop_controlpanel_site', default=u'Shop Controlpanel (site-wide)' ) self.url = '%s/@@shop_controlpanel' % context.absolute_url() self.order = 50 self.cssclass = 'controlpanel'
def collector_vocabulary(context): terms = [] # get local floor first site = get_site() # do not process local configuration if the current site is PloneSite if not IPloneSiteRoot.providedBy(site): utility = component.queryUtility(ILocalNewsletterLookup, name=get_name_for_site(site)) if utility is not None: local_lookup_utility=utility.get('newsletter_lookup',None) if local_lookup_utility: for collector in local_lookup_utility.local_collectors(): terms.append( zope.schema.vocabulary.SimpleTerm( value=collector, token='/'.join(collector.getPhysicalPath()), title=collector.title)) # get global collectors (original vocabulary code) root = component.getUtility(IPloneSiteRoot) collectors = root['portal_newsletters']['collectors'].objectValues() for collector in collectors: terms.append( zope.schema.vocabulary.SimpleTerm( value=collector, token='/'.join(collector.getPhysicalPath()), title=collector.title)) return zope.schema.vocabulary.SimpleVocabulary(terms)
def collector_vocabulary(context): terms = [] # get local floor first site = get_site() # do not process local configuration if the current site is PloneSite if not IPloneSiteRoot.providedBy(site): utility = component.queryUtility(ILocalNewsletterLookup, name=get_name_for_site(site)) if utility is not None: local_lookup_utility = utility.get("newsletter_lookup", None) if local_lookup_utility: for collector in local_lookup_utility.local_collectors(): terms.append( zope.schema.vocabulary.SimpleTerm( value=collector, token="/".join(collector.getPhysicalPath()), title=collector.title ) ) # get global collectors (original vocabulary code) root = component.getUtility(IPloneSiteRoot) collectors = root["portal_newsletters"]["collectors"].objectValues() for collector in collectors: terms.append( zope.schema.vocabulary.SimpleTerm( value=collector, token="/".join(collector.getPhysicalPath()), title=collector.title ) ) return zope.schema.vocabulary.SimpleVocabulary(terms)
def parent_url(self): """ This method is copied from plone.app.content.browser.foldercontents view """ portal_membership = getToolByName(self.context, "portal_membership") obj = self.context checkPermission = portal_membership.checkPermission # Abort if we are at the root of the portal if IPloneSiteRoot.providedBy(self.context): return None # Get the parent. If we can't get it (unauthorized), use the portal parent = aq_parent(aq_inner(obj)) # # We may get an unauthorized exception if we're not allowed to access# # the parent. In this case, return None try: if getattr(parent, "getId", None) is None or parent.getId() == "talkback": # Skip any Z3 views that may be in the acq tree; # Skip past the talkback container if that's where we are parent = aq_parent(aq_inner(parent)) if not checkPermission("List folder contents", parent): return None return parent.absolute_url() except Unauthorized: return None
def getObjectsFromLinks(base, links): """ determine actual objects refered to by given links """ intids = getUtility(IIntIds) objects = set() url = base.absolute_url() scheme, host, path, query, frag = urlsplit(url) for link in links: s, h, path, q, f = urlsplit(link) # relative or local url if (not s and not h) or (s == scheme and h == host): # Paths should always be strings if isinstance(path, six.text_type): path = path.encode('utf-8') obj, extra = findObject(base, path) if obj and not IPloneSiteRoot.providedBy(obj): objid = ensure_intid(obj, intids) if objid is None: # if we get a NotYet error, the object is not # attached yet and we will need to get links # at a later time when the object has an intid continue relation = RelationValue(objid) objects.add(relation) return objects
def _relativePath(context, row): # Walk through the tree obj = context values = row.values depthstr = "" if '::' in values: values, _depth = values.split('::', 1) depthstr = "::%s" % _depth for x in [r for r in values.split('/') if r]: if x == "..": if IPloneSiteRoot.providedBy(obj): break parent = aq_parent(obj) if parent: obj = parent else: if base_hasattr(obj, x): child = getattr(obj, x, None) if child and base_hasattr(child, "getPhysicalPath"): obj = child row = Row(index=row.index, operator=row.operator, values='/'.join(obj.getPhysicalPath()) + depthstr) return _absolutePath(context, row)
def page_title(self): ''' Get the page title. If we are in the portal_factory we want use the "Add $FTI_TITLE" form (see #12117). NOTE: other implementative options can be: - to use "Untitled" instead of "Add" or - to check the isTemporary method of the edit view instead of the creation_flag ''' if (hasattr(aq_base(self.context), 'isTemporary') and self.context.isTemporary()): # if we are in the portal_factory we want the page title to be # "Add fti title" portal_types = getToolByName(self.context, 'portal_types') fti = portal_types.getTypeInfo(self.context) return translate('heading_add_item', domain='plone', mapping={'itemtype': fti.Title()}, context=self.request, default='Add ${itemtype}') # If we are on portal root, look up the portal title from registry if IPloneSiteRoot.providedBy(self.context): return self.site_title_setting context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') return escape(safe_unicode(context_state.object_title()))
def render(self): portal = getSite() current_user = api.user.get_current() userid = current_user.id tag = self.request.form['tag'] soup_tags = get_soup('user_subscribed_tags', portal) exist = [r for r in soup_tags.query(Eq('id', userid))] if not exist: record = Record() record.attrs['id'] = userid record.attrs['tags'] = [tag] soup_tags.add(record) else: subscribed = [ True for utag in exist[0].attrs['tags'] if utag == tag ] if subscribed: exist[0].attrs['tags'].remove(tag) else: exist[0].attrs['tags'].append(tag) soup_tags.reindex() if IPloneSiteRoot.providedBy(self.context): self.request.response.redirect(self.context.absolute_url() + '/alltags') else: self.request.response.redirect(self.context.absolute_url())
def __call__(self): data = json_body(self.request) sharing_view = getMultiAdapter((self.context, self.request), name="sharing") # inherit roles inherit_reindex = False # block can be None, so we might get False or None, so we test # for a marker. inherit = data.get("inherit", marker) if inherit is not marker: inherit_reindex = sharing_view.update_inherit(status=inherit, reindex=False) # roles roles_reindex = False new_roles = data.get("entries", None) if new_roles is not None: # the roles are converted into a FrozenSet so we have to filter # the data structure we get. for user in new_roles: roles_list = [ key for key in user["roles"] if user["roles"][key] ] user["roles"] = roles_list roles_reindex = sharing_view.update_role_settings(new_roles, reindex=False) # reindex object security can_reindex = ICatalogAware( self.context, None) or IPloneSiteRoot.providedBy(self.context) if can_reindex and (inherit_reindex or roles_reindex): self.context.reindexObjectSecurity() if LOCALROLES_MODIFIED_EVENT_AVAILABLE: notify(LocalrolesModifiedEvent(self.context, self.request))
def get_context(self, context): """Helper to get the context, even if no context is given. """ if not context or not IPloneSiteRoot.providedBy(context): context = api.portal.get() return context
def get_context(self, context): """helper for get the context, even no context is given.""" if not context: context = getSite() # special handling for kks vailidationrequest # the context ist set to the Z3CFormValidation object and can't be used # so we get the PloneSiteRoot from the aq_chain if not IPloneSiteRoot.providedBy(context): for obj in context.aq_chain: if IPloneSiteRoot.providedBy(obj): context = obj break return context
def __call__(self, expand=False): result = { "eea.relations": { "@id": "{}/@eea.relations".format(self.context.absolute_url()) } } if not expand: return result if IPloneSiteRoot.providedBy(self.context): return result objrview = self.context.restrictedTraverse('eea.relations.macro', None) relations = objrview and objrview.forward_backward_auto() or None relations_dict = {} if relations: wftool = getToolByName(self.context, 'portal_workflow') for relation_tuples in relations: res_list = [] relation_label = relation_tuples[0] relations_list = relation_tuples[1] for obj in relations_list: obj_dict = { 'title': obj.Title(), '@type': obj.portal_type, '@id': obj.absolute_url(), 'description': obj.Description(), 'is_expired': obj.isExpired(), 'review_state': wftool.getInfoFor(obj, 'review_state') } res_list.append(obj_dict) relations_dict[relation_label] = res_list result["eea.relations"]['items'] = json_compatible(relations_dict) return result
def __init__(self, context): permissions = [MANAGE_TEAMPLETS_PERMISSION] super(ShopPortletMailTemplatesLink, self).__init__( context, view_permissions=permissions) # Find the nearest context, where this functionality can be bound to. def _find_context(ctx): return ctx\ if ISite.providedBy(ctx) or IVendor.providedBy(ctx)\ else _find_context(aq_parent(ctx)) context = _find_context(context) if IPloneSiteRoot.providedBy(context): self.title = _( 'mailtemplates_global', default=u'Notification Templates (global)' ) elif ISite.providedBy(context): self.title = _( 'mailtemplates_site', default=u'Notification Templates (site-wide)' ) elif IVendor.providedBy(context): self.title = _( 'mailtemplates_vendor', default=u'Notification Templates (vendor specific)' ) self.url = '%s/@@mailtemplates' % context.absolute_url() self.order = 50 self.cssclass = 'mailtemplates'
def inherited_portlets(self): """Return the list of portlets inherited by the current context. Invisible (hidden) portlets are excluded. """ context = aq_inner(self.context) data = [] while not IPloneSiteRoot.providedBy(context): if IAcquirer.providedBy(context): context = aq_parent(aq_inner(context)) else: context = context.__parent__ # we get the contextual portlets view to access its utility methods view = queryMultiAdapter((context, self.request), name=self.__parent__.__name__) if view is not None: assignments = view.getAssignmentsForManager(self.manager) is_visible = lambda a: IPortletAssignmentSettings(a).get('visible', True) assignments_to_show = [a for a in assignments if is_visible(a)] base_url = view.getAssignmentMappingUrl(self.manager) data.extend(self.portlets_for_assignments(assignments_to_show, self.manager, base_url)) assignable = queryMultiAdapter((context, self.manager), ILocalPortletAssignmentManager) if assignable is not None and assignable.getBlacklistStatus(CONTEXT_CATEGORY): # Current context has blocked inherited portlets, stop. break return data
def get_manager_and_assignments(self, manager_name): context = self.context # Prepare a list of objects by walking up the path. contexts = [context] while not IPloneSiteRoot.providedBy(context): context = aq_parent(aq_inner(context)) contexts.append(context) # Prepare a list of tuples in the form `(manager, assignments)`. managers_and_assignments = [] for context in contexts: manager = getUtility( IPortletManager, name=manager_name, context=context) assignments = getMultiAdapter( (context, manager), IPortletAssignmentMapping, context=context) if assignments is not None: managers_and_assignments.append((manager, assignments)) return managers_and_assignments
def handle_remove_event(context, event): """ Before a object is remvoed the event handler crates a remove job. """ # the event is notified for every subobject, but we only want to check # the top object which the users tries to delete if context is not event.object: return if belongs_to_parent(context): # Do not delete objects belonging to the parent, # they are deleted when the parent is published. return # Find the workflow object by walking up. We may be deleting a file # within a file-block within a page, where file and file-block have no # workflow and we check the page workflow. obj = context state = None while not IPloneSiteRoot.providedBy(obj): state = getMultiAdapter((obj, context.REQUEST), IPublisherContextState) if state.has_workflow(): break else: obj = aq_parent(aq_inner(obj)) if not state.has_workflow() or not state.has_publisher_config(): # plone site reached without finding a workflow, therefore # the object was never published. return context.restrictedTraverse('@@publisher.delete')(no_response=True)
def __init__(self, context): permissions = [VIEW_ORDERS_PERMISSION] super(ShopPortletOrdersLink, self).__init__( context, view_permissions=permissions) # check if authenticated user is vendor if self.display and not get_vendors_for(): self.display = False # Find the nearest context, where this functionality can be bound to. def _find_context(ctx): return ctx\ if ISite.providedBy(ctx) or IVendor.providedBy(ctx)\ else _find_context(aq_parent(ctx)) context = _find_context(context) if IPloneSiteRoot.providedBy(context): self.title = _( 'orders_global', default=u'Orders (global)' ) elif ISite.providedBy(context): self.title = _( 'orders_site', default=u'Orders (site-wide)' ) elif IVendor.providedBy(context): self.title = _( 'orders_vendor', default=u'Orders (vendor specific)' ) self.url = '%s/@@orders' % context.absolute_url() self.order = 10 self.cssclass = 'orders'
def getOrdering(self): if IPloneSiteRoot.providedBy(self.context): return self.context ordering = self.context.getOrdering() if not IExplicitOrdering.providedBy(ordering): return None return ordering
def tinymce(self): """ data-pat-tinymce : JSON.stringify({ relatedItems: { vocabularyUrl: config.portal_url + '/@@getVocabulary?name=plone.app.vocabularies.Catalog' }, tiny: config, prependToUrl: 'resolveuid/', linkAttribute: 'UID', prependToScalePart: '/@@images/image/' }) """ generator = TinyMCESettingsGenerator(self.context, self.request) settings = generator.settings folder = aq_inner(self.context) # Test if we are currently creating an Archetype object if IFactoryTempFolder.providedBy(aq_parent(folder)): folder = aq_parent(aq_parent(aq_parent(folder))) if not IFolderish.providedBy(folder): folder = aq_parent(folder) if IPloneSiteRoot.providedBy(folder): initial = None else: initial = IUUID(folder, None) current_path = folder.absolute_url()[len(generator.portal_url):] image_types = settings.image_objects or [] folder_types = settings.contains_objects or [] configuration = { 'relatedItems': { 'vocabularyUrl': '%s/@@getVocabulary?name=plone.app.vocabularies.Catalog' % ( generator.portal_url) }, 'upload': { 'initialFolder': initial, 'currentPath': current_path, 'baseUrl': generator.portal_url, 'relativePath': '@@fileUpload', 'uploadMultiple': False, 'maxFiles': 1, 'showTitle': False }, 'base_url': self.context.absolute_url(), 'tiny': generator.get_tiny_config(), # This is for loading the languages on tinymce 'loadingBaseUrl': '%s/++plone++static/components/tinymce-builded/js/tinymce' % generator.portal_url, # noqa 'prependToUrl': '{0}/resolveuid/'.format(generator.portal_url), 'linkAttribute': 'UID', 'prependToScalePart': '/@@images/image/', 'folderTypes': folder_types, 'imageTypes': image_types # 'anchorSelector': utility.anchor_selector, } return {'data-pat-tinymce': json.dumps(configuration)}
def get_redirect_url(context): """return the url where the editing_document view was called from It should be a document listing.""" referer = context.REQUEST.environ.get('HTTP_REFERER') portal_url = '/'.join(context.portal_url().split('/')[:-1]) if referer: obj_path = referer[len(portal_url):] try: obj = context.restrictedTraverse(obj_path) except KeyError: return '%s#overview' % context.absolute_url() # redirect to right tabbedview-tab if ITask.providedBy(obj): return '%s#relateddocuments' % (obj.absolute_url()) elif IPloneSiteRoot.providedBy(obj): return '%s#mydocuments' % (obj.absolute_url()) elif IDossierMarker.providedBy(obj): return '%s#documents' % (obj.absolute_url()) else: return obj.absolute_url() else: return '%s#overview' % context.absolute_url()
def objects(self): """Returns the data to create the sitemap.""" catalog = getToolByName(self.context, 'portal_catalog') query = {} utils = getToolByName(self.context, 'plone_utils') query['portal_type'] = utils.getUserFriendlyTypes() ptool = getToolByName(self, 'portal_properties') siteProperties = getattr(ptool, 'site_properties') typesUseViewActionInListings = frozenset( siteProperties.getProperty('typesUseViewActionInListings', []) ) is_plone_site_root = IPloneSiteRoot.providedBy(self.context) if not is_plone_site_root: query['path'] = '/'.join(self.context.getPhysicalPath()) query['is_default_page'] = True default_page_modified = OOBTree() for item in catalog.searchResults(query, Language='all'): key = item.getURL().rsplit('/', 1)[0] value = (item.modified.micros(), item.modified.ISO8601()) default_page_modified[key] = value # The plone site root is not catalogued. if is_plone_site_root: loc = self.context.absolute_url() date = self.context.modified() # Comparison must be on GMT value modified = (date.micros(), date.ISO8601()) default_modified = default_page_modified.get(loc, None) if default_modified is not None: modified = max(modified, default_modified) lastmod = modified[1] yield { 'loc': loc, 'lastmod': lastmod, #'changefreq': 'always', # hourly/daily/weekly/monthly/yearly/never #'prioriy': 0.5, # 0.0 to 1.0 } query['is_default_page'] = False for item in catalog.searchResults(query, Language='all'): loc = item.getURL() date = item.modified # Comparison must be on GMT value modified = (date.micros(), date.ISO8601()) default_modified = default_page_modified.get(loc, None) if default_modified is not None: modified = max(modified, default_modified) lastmod = modified[1] if item.portal_type in typesUseViewActionInListings: loc += '/view' yield { 'loc': loc, 'lastmod': lastmod, #'changefreq': 'always', # hourly/daily/weekly/monthly/yearly/never #'prioriy': 0.5, # 0.0 to 1.0 }
def language_filter(query): if query.get('Language') == 'all': del query['Language'] return for key in NO_FILTER: # any "nofilter" indexing prevent mangling if key in query: return site = getSite() languageTool = getToolByName(site, 'portal_languages', None) if languageTool is None: return query['Language'] = [languageTool.getPreferredLanguage(), LANGUAGE_INDEPENDENT] old_path = query.get('path', None) # In case is a depth path search if isinstance(old_path, dict) and 'query' in old_path and\ IPloneSiteRoot.providedBy(site): old_path_url = old_path['query'] # We are going to check if is language root root_path = '/'.join(site.getPhysicalPath()) # Check is a language root folder to add the shared folder if old_path['query'].split('/')[-1] in _languagelist: old_path['query'] = [old_path_url, root_path + '/' + SHARED_NAME]
def tinymce(self): """ data-pat-tinymce : JSON.stringify({ relatedItems: { vocabularyUrl: config.portal_url + '/@@getVocabulary?name=plone.app.vocabularies.Catalog' }, tiny: config, prependToUrl: 'resolveuid/', linkAttribute: 'UID', prependToScalePart: '/@@images/image/' }) """ generator = TinyMCESettingsGenerator(self.context, self.request) settings = generator.settings folder = aq_inner(self.context) # Test if we are currently creating an Archetype object if IFactoryTempFolder.providedBy(aq_parent(folder)): folder = aq_parent(aq_parent(aq_parent(folder))) if not IFolderish.providedBy(folder): folder = aq_parent(folder) if IPloneSiteRoot.providedBy(folder): initial = None else: initial = IUUID(folder, None) current_path = folder.absolute_url()[len(generator.portal_url):] image_types = settings.image_objects or [] folder_types = settings.contains_objects or [] configuration = { 'relatedItems': { 'vocabularyUrl': '%s/@@getVocabulary?name=plone.app.vocabularies.Catalog' % ( generator.portal_url), 'folderTypes': folder_types }, 'upload': { 'initialFolder': initial, 'currentPath': current_path, 'baseUrl': generator.portal_url, 'relativePath': '@@fileUpload', 'uploadMultiple': False, 'maxFiles': 1, 'showTitle': False }, 'base_url': self.context.absolute_url(), 'tiny': generator.get_tiny_config(), # This is for loading the languages on tinymce 'loadingBaseUrl': '%s/++plone++static/components/tinymce-builded/js/tinymce' % generator.portal_url, # noqa 'prependToUrl': '{0}/resolveuid/'.format(generator.portal_url), 'linkAttribute': 'UID', 'prependToScalePart': '/@@images/image/', 'imageTypes': image_types # 'anchorSelector': utility.anchor_selector, } return {'data-pat-tinymce': json.dumps(configuration)}
def unindex(obj, event): """Un-index mirrored folder content for all mirrors and master Mirror folder content objects are indexed once for each mirror and the master with different, mirror-specific, UUID for each. When ever a mirrored folder content object is removed in some mirror or master, we must un-index it for all the other mirrors and master as well. """ if IObjectWillBeAddedEvent.providedBy(event): return if IPloneSiteRoot.providedBy(event.object): return info = mirror_info(obj) if info == NOT_MIRRORED: return uuid = IUUID(obj).split('@')[0] uuids = [uuid] + [f'{uuid}@{mirror_id}' for mirror_id in info.mirror_ids] cat = api.portal.get_tool('portal_catalog') for uuid in uuids: brains = cat.unrestrictedSearchResults(UID=uuid) for brain in brains: brain.getObject().unindexObject()
def get_query(self): url_tool = getToolByName(self.context, "portal_url") portal_path = url_tool.getPortalPath() query = {"object_provides": {"query": ["ftw.news.interfaces.INews"]}} parent = aq_parent(aq_inner((self.context))) if self.context.current_context: path = "/".join(parent.getPhysicalPath()) query["path"] = {"query": path} elif self.context.filter_by_path: cat_path = [] for item in self.context.filter_by_path: cat_path.append("/".join([portal_path, item])) query["path"] = {"query": cat_path} subjects = self.context.subjects if subjects: query["Subject"] = map(make_utf8, subjects) if self.context.maximum_age > 0: date = DateTime() - self.context.maximum_age query["start"] = {"query": date, "range": "min"} news_on_homepage = getattr(self.context, "news_on_homepage", False) if news_on_homepage and IPloneSiteRoot.providedBy(parent): query["object_provides"]["operator"] = "and" query["object_provides"]["query"].append(IShowOnHomepage.__identifier__) query["sort_on"] = "start" query["sort_order"] = "descending" return query
def itemsInFolder(self): """Count the items in the screen """ folder = self.contextState.folder() if IPloneSiteRoot.providedBy(folder): return len(folder.contentIds()) # XXX: Assumes other folders behave well and only contain content return len(folder)
def iterate_until_root(obj): """ Iterate over object parents until reaching the Plone Site Root object """ result = [obj] obj = aq_parent(obj) while obj and not IPloneSiteRoot.providedBy(obj): result.append(obj) obj = aq_parent(obj) return result