def index(self): try: site_title = aq_acquire(self.context, 'site_title') org_title = "Penn State College of Ag Sciences" except AttributeError: site_title = self.portal_title() org_title = "Penn State University" try: org_title = aq_acquire(self.context, 'org_title') except AttributeError: org_title = org_title portal_title = safe_unicode(site_title) page_title = safe_unicode(self.page_title()) org_title = safe_unicode(org_title) if not org_title or org_title.lower() == 'none': return u"<title>%s — %s</title>" % ( escape(safe_unicode(page_title)), escape(safe_unicode(portal_title))) elif page_title == portal_title: return u"<title>%s — %s</title>" % (escape(portal_title), escape(org_title)) else: return u"<title>%s — %s — %s</title>" % ( escape(safe_unicode(page_title)), escape(safe_unicode(portal_title)), escape(safe_unicode(org_title)))
def _exc_view_created_response(exc, request, response): view = queryMultiAdapter((exc, request), name=u'index.html') parents = request.get('PARENTS') if view is None and parents: # Try a fallback based on the old standard_error_message # DTML Method in the ZODB view = queryMultiAdapter((exc, request), name=u'standard_error_message') root_parent = parents[0] try: aq_acquire(root_parent, 'standard_error_message') except (AttributeError, KeyError): view = None if view is not None: # Wrap the view in the context in which the exception happened. if parents: view.__parent__ = parents[0] # Set status and headers from the exception on the response, # which would usually happen while calling the exception # with the (environ, start_response) WSGI tuple. response.setStatus(exc.__class__) if hasattr(exc, 'headers'): for key, value in exc.headers.items(): response.setHeader(key, value) # Set the response body to the result of calling the view. response.setBody(view()) return True return False
def update(self): self.portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') self.anonymous = self.portal_state.anonymous() try: layout = self.context.getLayout() except: layout = None if homepage_views.count(layout) > 0: self.isHomePage = True else: self.isHomePage = False try: self.homepage_h1 = aq_acquire(self.context, 'homepage_h1') except AttributeError: self.homepage_h1 = None try: self.homepage_h2 = aq_acquire(self.context, 'homepage_h2') except AttributeError: self.homepage_h2 = None # Determine if we should hide breadcrumbs try: if aq_acquire(self.context, 'hide_breadcrumbs'): self.hide_breadcrumbs = True except AttributeError: if self.homepage_h1 or self.homepage_h2: self.hide_breadcrumbs = True else: self.hide_breadcrumbs = False
def update(self): super(PathBarViewlet, self).update() self.navigation_root_url = self.portal_state.navigation_root_url() self.is_rtl = self.portal_state.is_rtl() breadcrumbs_view = getMultiAdapter((self.context, self.request), name='breadcrumbs_view') self.breadcrumbs = breadcrumbs_view.breadcrumbs() self.isHomePage = isHomePage(self.context) # Get the site id self.site = getSite()['id'] # Determine if we should hide breadcrumbs try: if aq_acquire(self.context, 'hide_breadcrumbs'): self.hide_breadcrumbs = True except AttributeError: self.hide_breadcrumbs = False try: if aq_acquire(self.context, 'homepage_h1'): self.hide_breadcrumbs = True except AttributeError: pass try: if aq_acquire(self.context, 'homepage_h2'): self.hide_breadcrumbs = True except AttributeError: pass
def safe_render(self, portlet_renderer): try: return portlet_renderer.render() except (ConflictError, Retry): raise except Exception: logger.exception('Error while rendering %r' % (self, )) aq_acquire(self, 'error_log').raising(sys.exc_info()) return self.error_message()
def safe_render(self, portlet_renderer): try: return portlet_renderer.render() except ConflictError: raise except Exception: logger.exception('Error while rendering %r' % self) aq_acquire(self, 'error_log').raising(sys.exc_info()) return self.error_message()
def guarded_getattr(inst, name, default=_marker): """Retrieves an attribute, checking security in the process. Raises Unauthorized if the attribute is found but the user is not allowed to access the attribute. """ if name[:1] == '_': raise Unauthorized, name # Try to get the attribute normally so that unusual # exceptions are caught early. try: v = getattr(inst, name) except AttributeError: if default is not _marker: return default raise try: container = v.im_self except AttributeError: container = aq_parent(aq_inner(v)) or inst assertion = Containers(type(container)) if isinstance(assertion, dict): # We got a table that lets us reason about individual # attrs assertion = assertion.get(name) if assertion: # There's an entry, but it may be a function. if callable(assertion): return assertion(inst, name) # Nope, it's boolean return v raise Unauthorized, name if assertion: if callable(assertion): factory = assertion(name, v) if callable(factory): return factory(inst, name) assert factory == 1 else: assert assertion == 1 return v # See if we can get the value doing a filtered acquire. # aq_acquire will either return the same value as held by # v or it will return an Unauthorized raised by validate. validate = getSecurityManager().validate aq_acquire(inst, name, aq_validate, validate) return v
def guarded_getattr(inst, name, default=_marker): """Retrieves an attribute, checking security in the process. Raises Unauthorized if the attribute is found but the user is not allowed to access the attribute. """ if name[:1] == '_': raise Unauthorized, name # Try to get the attribute normally so that unusual # exceptions are caught early. try: v = getattr(inst, name) except AttributeError: if default is not _marker: return default raise try: container = v.im_self except AttributeError: container = aq_parent(aq_inner(v)) or inst assertion = Containers(type(container)) if isinstance(assertion, dict): # We got a table that lets us reason about individual # attrs assertion = assertion.get(name) if assertion: # There's an entry, but it may be a function. if callable(assertion): return assertion(inst, name) # Nope, it's boolean return v raise Unauthorized, name if assertion: if callable(assertion): factory = assertion(name, v) if callable(factory): return factory(inst, name) assert factory == 1 else: assert assertion == 1 return v # See if we can get the value doing a filtered acquire. # aq_acquire will either return the same value as held by # v or it will return an Unauthorized raised by validate. validate = SecurityManagement.getSecurityManager().validate aq_acquire(inst, name, aq_validate, validate) return v
def safe_render(self): try: return self.renderResults() except ConflictError: raise except Exception: logger.exception("Error while rendering %r" % self) aq_acquire(self.context, "error_log").raising(sys.exc_info()) if getSecurityManager().checkPermission(ModifyPortalContent, self.context): return self.error_template() return self.error_message
def safe_render(self): try: return self.renderResults() except ConflictError: raise except Exception: logger.exception('Error while rendering %r' % self) aq_acquire(self.context, 'error_log').raising(sys.exc_info()) if getSecurityManager().checkPermission(ModifyPortalContent, self.context): return self.error_template() return self.error_message
def translate(self, domain, msgid, mapping, context, target_language, default): util = TestMessageFallbackDomain(domain) if context is not None: context = aq_acquire(context, 'REQUEST', None) return util.translate(msgid, mapping, context, target_language, default)
def show_read_more(self): try: show_read_more = aq_acquire(self.getSettingsObject(), 'show_read_more') except AttributeError: show_read_more = False return show_read_more
def __call__(self): portal = api.portal.get() catalog = portal.portal_catalog tool = portal.portal_plonemeeting logger.info('Sending mails linked to annexes on PV added today.') now = DateTime() start = DateTime(now.Date()) date_query = {'query': start, 'range': 'min'} # This is made to return links with correct URL as cron4plone tasks breaks the absolute_url machinery request = aq_acquire(self, 'REQUEST') request['SERVER_URL'] = tool.getPublicUrl() annexCpt = 0 brains = catalog.searchResults(meta_type='MeetingFile', Date=date_query) for brain in brains: annex = brain.getObject() if annex.findRelatedTo() == "item_pv": annexCpt += 1 annexType = annex.getMeetingFileType( theRealObject=True).getName() sendMailToCopyGroupsIfRelevant(annex.getParent(), 'event_add_pv_annex', mapping={ 'itemType': annexType, }) logger.info('mails sent about ' + str(annexCpt) + ' new annexes on PV')
def translate(self, domain, msgid, mapping=None, context=None, target_language=None, default=None): if isinstance(msgid, Message): domain = msgid.domain default = msgid.default mapping = msgid.mapping if default is None: default = unicode(msgid) if domain: util = queryUtility(ITranslationDomain, domain) if util is None: util = queryUtility(IFallbackTranslationDomainFactory) if util is not None: util = util(domain) else: util = queryUtility(IFallbackTranslationDomainFactory) if util is not None: util = util() if util is None: # fallback to translation service that was registered, # DummyTranslationService the worst ts = _fallback_translation_service return ts.translate(domain, msgid, mapping=mapping, context=context, target_language=target_language, default=default) # in Zope3, context is adapted to IUserPreferredLanguages, # which means context should be the request in this case. if context is not None: context = aq_acquire(context, 'REQUEST', None) return util.translate(msgid, mapping=mapping, context=context, target_language=target_language, default=default)
def customBodyClass(self): context = aq_base(self.context) body_classes = [] if hasattr(context, 'two_column') and context.two_column: body_classes.append('custom-two-column') try: if hasattr(context, 'folder_text'): body_text = str(context.folder_text) elif hasattr(context, 'getText'): body_text = str(context.getText()) else: body_text = '' except: body_text = '' if body_text and '<h2' in body_text.lower() and '<h3' not in body_text.lower(): body_classes.append('custom-h2-as-h3') try: custom_class = aq_acquire(self.context, 'custom_class') body_classes.extend(['custom-%s' % str(x) for x in custom_class.split()]) except AttributeError: pass return ' '.join(body_classes)
def update(self): super(KeywordsViewlet, self).update() context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') tools = getMultiAdapter((self.context, self.request), name=u'plone_tools') sm = getSecurityManager() self.user_actions = context_state.actions().get('user', None) plone_utils = getToolByName(self.context, 'plone_utils') self.getIconFor = plone_utils.getIconFor anonymous = portal_state.anonymous() if anonymous: try: self.show_tags = aq_acquire(self.context, 'show_tags') except AttributeError: self.show_tags = False else: self.show_tags = True
def unknown_starttag(self, tag, attrs): """Here we've got the actual conversion of links and images. Convert UUID's to absolute URLs, and process captioned images to HTML. """ if tag in ['a', 'img', 'area']: # Only do something if tag is a link, image, or image map area. attributes = dict(attrs) if tag == 'a': self.in_link = True if (tag == 'a' or tag == 'area') and 'href' in attributes: href = attributes['href'] scheme = urlsplit(href)[0] if not scheme and not href.startswith('/') \ and not href.startswith('mailto<') \ and not href.startswith('#'): obj, subpath, appendix = self.resolve_link(href) if obj is not None: href = obj.absolute_url() if subpath: href += '/' + subpath href += appendix elif resolveuid_re.match(href) is None: # absolutize relative URIs; this text isn't necessarily # being rendered in the context where it was stored relative_root = self.context if not getattr( self.context, 'isPrincipiaFolderish', False): relative_root = aq_parent(self.context) actual_url = relative_root.absolute_url() href = urljoin(actual_url + '/', subpath) + appendix attributes['href'] = href attrs = attributes.iteritems() elif tag == 'img': src = attributes.get('src', '') image, fullimage, src, description = self.resolve_image(src) attributes["src"] = src caption = description # Check if the image needs to be captioned if (self.captioned_images and image is not None and caption and 'captioned' in attributes.get('class', '').split(' ')): self.handle_captioned_image(attributes, image, fullimage, caption) return True if fullimage is not None: # Check to see if the alt / title tags need setting title = aq_acquire(fullimage, 'Title')() attributes['alt'] = title if 'title' not in attributes: attributes['title'] = description or title attrs = attributes.iteritems() # Add the tag to the result strattrs = "".join([' %s="%s"' % (key, escape(value)) for key, value in attrs]) if tag in singleton_tags: self.append_data("<%s%s />" % (tag, strattrs)) else: self.append_data("<%s%s>" % (tag, strattrs))
def translate(self, domain, msgid, mapping=None, context=None, target_language=None, default=None): """ Translate a message using Unicode. """ if not msgid: # refuse to translate an empty msgid return default # ZPT passes the object as context. That's wrong according to spec. if not IBrowserRequest.providedBy(context): context = aq_acquire(context, 'REQUEST') text = msgid catalogs = self.getCatalogsForTranslation(context, domain, target_language) for catalog in catalogs: try: text = getMessage(catalog, msgid, default) except KeyError: # it's not in this catalog, try the next one continue # found! break else: # Did the fallback fail? Sigh, use the default if it is not None. if default is not None: text = default # Now we need to do the interpolation return self.interpolate(text, mapping)
def __call__(self, *args, **kw): view = aq_acquire(self.context, self.context.getDefaultLayout()) if "main" in view.macros.names: self.main_macro = view.macros["main"] else: self.main_macro = view.macros["content-core"] return self.index()
def absolute_url(self, relative=0): """Return the absolute URL of the object. This a canonical URL based on the object's physical containment path. It is affected by the virtual host configuration, if any, and can be used by external agents, such as a browser, to address the object. If the relative argument is provided, with a true value, then the value of virtual_url_path() is returned. Some Products incorrectly use '/'+absolute_url(1) as an absolute-path reference. This breaks in certain virtual hosting situations, and should be changed to use absolute_url_path() instead. """ if relative: return self.virtual_url_path() spp = self.getPhysicalPath() try: toUrl = aq_acquire(self, 'REQUEST').physicalPathToURL except AttributeError: return path2url(spp[1:]) return toUrl(spp)
def translate(self, domain, msgid, mapping=None, context=None, target_language=None, default=None): if isinstance(msgid, MessageID): domain = msgid.domain default = msgid.default mapping = msgid.mapping util = zapi.queryUtility(ITranslationDomain, domain) if util is None: # fallback to translation service that was registered, # DummyTranslationService the worst ts = _fallback_translation_service return ts.translate(domain, msgid, mapping=mapping, context=context, target_language=target_language, default=default) # in Zope3, context is adapted to IUserPreferredLanguages, # which means context should be the request in this case. if context is not None: context = aq_acquire(context, 'REQUEST', None) return util.translate(msgid, mapping=mapping, context=context, target_language=target_language, default=default)
def update(self): try: topMenu = aq_acquire(self.context, 'top-menu') except AttributeError: topMenu = 'topnavigation' self.topnavigation = self.context_state.actions().get(topMenu, None) # URL that contains the section self.container_url = None if self.topnavigation: matches = [] for t in self.topnavigation: t_url = t.get('url') portal_url = self.context.portal_url() context_url = self.context.absolute_url() # Remove trailing / to normalize if t_url.endswith("/"): t_url = t_url[0:-1] if portal_url.endswith("/"): portal_url = portal_url[0:-1] if context_url.endswith("/"): context_url = context_url[0:-1] if portal_url != t_url and context_url.startswith(t_url): matches.append(t_url) # Remove trailing slash if matches: self.container_url = sorted(matches, key=lambda x:len(x), reverse=True)[0]
def update(self): syntool = getToolByName(self.context, 'portal_syndication') self.isSyndicationAllowed = syntool.isSyndicationAllowed(self.context) portal_type = getattr(self.context, 'portal_type', None) if portal_type == 'FSDPerson': self.isPerson = True else: self.isPerson = False ptool = getToolByName(self.context, "portal_properties") self.hide_addthis = not ptool.agcommon_properties.enable_addthis try: self.hide_addthis = aq_acquire(self.context, 'hide_addthis') except AttributeError: pass # If in folder_full_view_item, hide it on the individual items. if self.isFolderFullView: self.hide_addthis = True
def show_read_more(self): try: show_read_more = aq_acquire(self.context, 'show_read_more') except AttributeError: show_read_more = False return show_read_more
def get_error_log(self): log = None published = self.__parent__ if published: try: error_log = aq_acquire(published, '__error_log__', containment=1) error_type, error_value, tb = sys.exc_info() error_log_url = error_log.raising( (error_type, error_value, tb)) log = { 'url': error_log_url, 'errorid': error_log_url.split('?id=')[1], 'traceback': ''.join( traceback.format_exception(error_type, error_value, tb)) } except AttributeError: log = None return log
def utranslate(domain, msgid, mapping=None, context=None, target_language=None, default=None): # We used to pass an object as context. if not IBrowserRequest.providedBy(context): context = aq_acquire(context, "REQUEST") # The signature of zope.i18n's translate has the msgid and domain switched return translate( msgid, domain=domain, mapping=mapping, context=context, target_language=target_language, default=default )
def __call__(self, data): data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data) soup = BeautifulSoup(safe_unicode(data), 'html.parser') for elem in soup.find_all(['a', 'area']): attributes = elem.attrs href = attributes.get('href') # an 'a' anchor element has no href if not href: continue url_parts = urlsplit(href) scheme = url_parts[0] # we are only interested in path and beyond /foo/bar?x=2#abc path_parts = urlunsplit(['', ''] + list(url_parts[2:])) if not href.startswith('mailto<') \ and not href.startswith('mailto:') \ and not href.startswith('tel:') \ and not href.startswith('#'): obj, subpath, appendix = self.resolve_link(path_parts) if obj is not None: href = obj.absolute_url() if subpath: href += '/' + subpath href += appendix elif resolveuid_re.match(href) is None \ and not scheme \ and not href.startswith('/'): # absolutize relative URIs; this text isn't necessarily # being rendered in the context where it was stored relative_root = self.context if not getattr(self.context, 'isPrincipiaFolderish', False): relative_root = aq_parent(self.context) actual_url = relative_root.absolute_url() href = urljoin(actual_url + '/', subpath) + appendix attributes['href'] = href for elem in soup.find_all('img'): attributes = elem.attrs src = attributes.get('src', '') image, fullimage, src, description = self.resolve_image(src) attributes["src"] = src if fullimage is not None: # Check to see if the alt / title tags need setting title = safe_unicode(aq_acquire(fullimage, 'Title')()) if not attributes.get('alt'): # XXX alt attribute contains *alternate* text attributes['alt'] = description or title if 'title' not in attributes: attributes['title'] = title caption = description # Check if the image needs to be captioned if (self.captioned_images and image is not None and caption and 'captioned' in attributes.get('class', [])): self.handle_captioned_image(attributes, image, fullimage, elem, caption) return six.text_type(soup)
def maybe_report_exception(context, request, exc_type, exc, traceback): if is_exception_type_ignored(exc_type): return exc_info = exc_type, exc, traceback try: client = get_raven_client() if client is None: return try: data = { 'request': prepare_request_infos(request), 'user': prepare_user_infos(context, request), 'extra': prepare_extra_infos(context, request), 'modules': prepare_modules_infos(), 'tags': prepare_tags(exc) } release = get_release() if release: data['release'] = release except: LOG.error('Error while preparing sentry data.') raise try: client.captureException(exc_info=exc_info, data=data) except: LOG.error('Error while reporting to sentry.') raise except: if context: aq_acquire(context, 'error_log').raising(sys.exc_info()) try: get_raven_client().captureException( data={ 'extra': { 'raven_meta_error': 'Error occured while reporting' ' another error.' } }) except: LOG.error('Failed to report error occured while reporting error.')
def newsletter_title(self): try: newsletter_title = aq_acquire(self.context, 'newsletter_title') except AttributeError: newsletter_title = None try: site_title = aq_acquire(self.context, 'site_title') except AttributeError: site_title = None context_title = self.context.Title(); if newsletter_title: return newsletter_title elif site_title: return '%s: %s' % (site_title, context_title) else: return context_title
def factory(inst, name): """ Check function used with ContainerAssertions checked by cAccessControl. """ access = _safe_class_attribute_dict.get(inst, 0) # The next 'dict' only checks the access configuration type if access == 1 or (isinstance(access, dict) and access.get(name, 0) == 1): pass elif isinstance(access, dict) and callable(access.get(name, 0)): guarded_method = access.get(name) return guarded_method(inst, name) elif callable(access): # Only check whether the access configuration raise error or not access(inst, name) else: # fallback to default security aq_acquire(inst, name, aq_validate, getSecurityManager().validate) return v
def _translate(context, msg): """helper to translate a term if its a messageid """ if not isinstance(msg, Message): return msg if not IBrowserRequest.providedBy(context): context = aq_acquire(context, 'REQUEST') msg = translate(msg, context=context).strip() msg = '\n'.join([_.strip() for _ in msg.split('\n')]) # needed if vdex return msg
def hide_breadcrumbs(self): # Determine if we should hide breadcrumbs if self.homepage_h1 or self.homepage_h2: return True try: return aq_acquire(self.context, 'hide_breadcrumbs') except AttributeError: return False
def update(self): try: self.page_title = self.view.page_title except AttributeError: self.page_title = self.context_state.object_title self.portal_title = self.portal_state.portal_title try: self.site_title = aq_acquire(self.context, 'site_title') self.org_title = "Penn State College of Ag Sciences" except AttributeError: self.site_title = self.portal_title() self.org_title = "Penn State University" try: self.org_title = aq_acquire(self.context, 'org_title') except AttributeError: self.org_title = ""
def update(self): context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') try: topMenu = aq_acquire(self.context, 'top-menu') except AttributeError: topMenu = 'topnavigation' self.topnavigation = context_state.actions().get(topMenu, None)
def update(self): context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') try: show_date = aq_acquire(self.context, 'show_date') except AttributeError: show_date = False self.show_date = show_date
def absolute_url(self, relative=0): if not IChildSite.providedBy(self): return self._absolute_url(relative) elif relative: self.virtual_url_path() url = map_url('/'.join(self.getPhysicalPath()), aq_acquire(self, 'REQUEST')) return url
def substituteEventLocation(self, item): try: show_event_location = aq_acquire(self.context, 'show_event_location') except AttributeError: show_event_location = False if show_event_location and (item.portal_type == 'Event' or item.portal_type == 'TalkEvent') and item.location.strip(): return item.location.strip() else: return None
def ZCacheable_getManager(self): '''Returns the currently associated cache manager.''' manager_id = self.__manager_id if manager_id is None: return None try: return aq_acquire( self, manager_id, containment=1, filter=filterCacheManagers, extra=None, default=None) except AttributeError: return None
def test_utilitiesHaveProperAcquisitionContext(self): dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, dummy) # let's see if we can acquire something all the way from the # root (Application) object; we need to be careful to choose # something that's only available from the root object from Acquisition import aq_acquire dummy = zapi.getUtility(IDummyUtility) acquired = aq_acquire(dummy, 'ZopeAttributionButton', None) self.failUnless(acquired is not None) name, dummy = zapi.getUtilitiesFor(IDummyUtility).next() acquired = aq_acquire(dummy, 'ZopeAttributionButton', None) self.failUnless(acquired is not None) dummy = zapi.getAllUtilitiesRegisteredFor(IDummyUtility).next() acquired = aq_acquire(dummy, 'ZopeAttributionButton', None) self.failUnless(acquired is not None)
def all_meta_types(self, interfaces=None): if interfaces is None: if hasattr(self, '_product_interfaces'): interfaces = self._product_interfaces elif hasattr(self, 'aq_acquire'): try: interfaces = aq_acquire(self, '_product_interfaces') except Exception: pass return ObjectManager.all_meta_types(self, interfaces)
def absolute_url_path(self): """Return the path portion of the absolute URL of the object. This includes the leading slash, and can be used as an 'absolute-path reference' as defined in RFC 2396. """ spp = self.getPhysicalPath() try: toUrl = aq_acquire(self, 'REQUEST').physicalPathToURL except AttributeError: return path2url(spp) or '/' return toUrl(spp, relative=1) or '/'
def virtual_url_path(self): """Return a URL for the object, relative to the site root. If a virtual host is configured, the URL is a path relative to the virtual host's root object. Otherwise, it is the physical path. In either case, the URL does not begin with a slash. """ spp = self.getPhysicalPath() try: toVirt = aq_acquire(self, 'REQUEST').physicalPathToVirtualPath except AttributeError: return path2url(spp[1:]) return path2url(toVirt(spp))
def utranslate(domain, msgid, mapping=None, context=None, target_language=None, default=None): # We used to pass an object as context. if not IBrowserRequest.providedBy(context): context = aq_acquire(context, 'REQUEST') # The signature of zope.i18n's translate has the msgid and domain switched return translate(msgid, domain=domain, mapping=mapping, context=context, target_language=target_language, default=default)
def branch(self): if self.state == 0: return {'link': None, 'img': ' '} if self.state < 0: setst = 'expand' exnum = self.__parent__.expansion_number else: setst = 'collapse' exnum = self.expansion_number obid = self.id pre = aq_acquire(self, 'tree_pre') return {'link': '?%s-setstate=%s,%s,%s#%s' % (pre, setst[0], exnum, obid, obid), 'img': ''}
def __call__(self, *args, **kw): """ Uses ac_aqcuire to return the specified page template """ if self.request.has_key("path"): path = self.request["path"] target_obj = None try: target_obj = self.context.restrictedTraverse(path) except KeyError: logger.log(logging.INFO, "Invalid path: %s" % path) raise NotFound if target_obj: context = self.context request = self.request view = "" try: # Strip the target_obj of context with aq_base. # Put the target in the context of self.context. # getDefaultLayout returns the name of the default # view method from the factory type information view = aq_acquire( aq_base(target_obj).__of__(context), target_obj.getDefaultLayout())(**kw) except AttributeError, message: logger.log(logging.ERROR, "Error acquiring template: %s, path: %s"\ %(message, path)) raise NotFound if view: # All images and links in the target document # which depend on the context e.g. images in News # items, will be broken, so we do a simple replace # to fix them. # I tried to be a bit more clever about this and # use the lxml soupparser, but it breaks the # layout severely when it is converted back to # html (deroiste) proxy_url = context.absolute_url() + "/" +\ target_obj.getId() target_url = target_obj.absolute_url() return view.replace(proxy_url, target_url)
def translate(self, domain, msgid, mapping=None, context=None, target_language=None, default=None): # Translate a message using Unicode. if not msgid: # refuse to translate an empty msgid return default # ZPT passes the object as context. That's wrong according to spec. if not IBrowserRequest.providedBy(context): context = aq_acquire(context, 'REQUEST') text = msgid return z3translate(msgid, domain, mapping, context, target_language, default)
def pt_getContext(self, instance, request, **kw): namespace = super(ViewPageTemplateFile, self).pt_getContext(instance, request, **kw) bound_names = namespace['options'].pop('bound_names') namespace.update(bound_names) context = aq_inner(instance.context) try: root = aq_acquire(context, 'getPhysicalRoot')() except AttributeError: raise # we can't access the root, probably because 'context' is # something that doesn't support Acquisition. You lose. root = None namespace.update({ 'context': context, 'here': context, 'container': context, 'root': root, 'user': AccessControl.getSecurityManager().getUser(), 'modules': SecureModuleImporter, }) return namespace
def http__processMatchHeaders(self, REQUEST=None): # Process if-match and if-none-match headers if REQUEST is None: REQUEST = aq_acquire(self, 'REQUEST') matchlist = self.http__parseMatchList(REQUEST, 'if-match') nonematch = self.http__parseMatchList(REQUEST, 'if-none-match') if matchlist is None: # There's no Matchlist, but 'if-none-match' might need processing pass elif ('*' in matchlist): return 1 # * matches everything elif self.http__etag() not in matchlist: # The resource etag is not in the list of etags required # to match, as specified in the 'if-match' header. The # condition fails and the HTTP Method may *not* execute. raise HTTPPreconditionFailed() elif self.http__etag() in matchlist: return 1 if nonematch is None: # There's no 'if-none-match' header either, so there's no # problem continuing with the request return 1 elif ('*' in nonematch): # if-none-match: * means that the operation should not # be performed if the specified resource exists raise HTTPPreconditionFailed() elif self.http__etag() in nonematch: # The opposite of if-match, the condition fails # IF the resources Etag is in the if-none-match list raise HTTPPreconditionFailed() elif self.http__etag() not in nonematch: return 1
def unknown_starttag(self, tag, attrs): """Here we've got the actual conversion of links and images. Convert UUID's to absolute URLs, and process captioned images to HTML. """ if tag in ['a', 'img', 'area']: # Only do something if tag is a link, image, or image map area. attributes = dict(attrs) if tag == 'a': self.in_link = True if (tag == 'a' or tag == 'area') and 'href' in attributes: href = attributes['href'] scheme = urlsplit(href)[0] if not scheme and not href.startswith('/') \ and not href.startswith('mailto<') \ and not href.startswith('#'): obj, subpath, appendix = self.resolve_link(href) if obj is not None: href = obj.absolute_url() if subpath: href += '/' + subpath href += appendix elif resolveuid_re.match(href) is None: # absolutize relative URIs; this text isn't necessarily # being rendered in the context where it was stored relative_root = self.context if not getattr( self.context, 'isPrincipiaFolderish', False): relative_root = aq_parent(self.context) actual_url = relative_root.absolute_url() href = urljoin(actual_url + '/', subpath) + appendix attributes['href'] = href attrs = attributes.iteritems() elif tag == 'img': src = attributes.get('src', '') image, fullimage, src, description = self.resolve_image(src) attributes["src"] = src caption = description # Check if the image needs to be captioned if (self.captioned_images and image is not None and caption and 'captioned' in attributes.get('class', '').split(' ')): self.handle_captioned_image(attributes, image, fullimage, caption) return True if fullimage is not None: # Check to see if the alt / title tags need setting title = aq_acquire(fullimage, 'Title')() if 'alt' not in attributes: attributes['alt'] = description or title if 'title' not in attributes: attributes['title'] = title attrs = attributes.iteritems() # Add the tag to the result strattrs = "".join([' %s="%s"' % (key, escape(value, quote=True)) for key, value in attrs]) if tag in self.singleton_tags: self.append_data("<%s%s />" % (tag, strattrs)) else: self.append_data("<%s%s>" % (tag, strattrs))
def resolve_image(self, src): description = '' if urlsplit(src)[0]: # We have a scheme return None, None, src, description base = self.context subpath = src appendix = '' def traversal_stack(base, path): if path.startswith('/'): base = getSite() path = path[1:] obj = base stack = [obj] components = path.split('/') while components: child_id = unquote(components.pop(0)) try: if hasattr(aq_base(obj), 'scale'): if components: child = obj.scale(child_id, components.pop()) else: child = obj.scale(child_id) else: # Do not use restrictedTraverse here; the path to the # image may lead over containers that lack the View # permission for the current user! # Also, if the image itself is not viewable, we rather # show a broken image than hide it or raise # unauthorized here (for the referring document). child = obj.unrestrictedTraverse(child_id) except ConflictError: raise except (AttributeError, KeyError, NotFound, ztkNotFound): return obj = child stack.append(obj) return stack def traverse_path(base, path): stack = traversal_stack(base, path) if stack is None: return return stack[-1] obj, subpath, appendix = self.resolve_link(src) if obj is not None: # resolved uid fullimage = obj image = traverse_path(fullimage, subpath) elif '/@@' in subpath: # split on view pos = subpath.find('/@@') fullimage = traverse_path(base, subpath[:pos]) if fullimage is None: return None, None, src, description image = traverse_path(fullimage, subpath[pos + 1:]) else: stack = traversal_stack(base, subpath) if stack is None: return None, None, src, description image = stack.pop() # if it's a scale, find the full image by traversing one less fullimage = image if not IContentish.providedBy(fullimage): stack.reverse() for parent in stack: if hasattr(aq_base(parent), 'tag'): fullimage = parent break if image is None: return None, None, src, description url = image.absolute_url() if isinstance(url, unicode): url = url.encode('utf8') src = url + appendix description = aq_acquire(fullimage, 'Description')() return image, fullimage, src, description
def __call__(self, published, REQUEST, t, v, traceback): try: if t is SystemExit or issubclass(t, Redirect): reraise(t, v, traceback) if issubclass(t, ConflictError): self.logConflicts(v, REQUEST) raise Retry(t, v, traceback) if t is Retry: try: v.reraise() except: # we catch the re-raised exception so that it gets # stored in the error log and gets rendered with # standard_error_message t, v, traceback = sys.exc_info() if issubclass(t, ConflictError): # ouch, a user saw this conflict error :-( self.unresolved_conflict_errors += 1 error_log_url = '' if not isinstance(published, list): try: log = aq_acquire(published, '__error_log__', containment=1) except AttributeError: pass else: if log is not None: error_log_url = log.raising((t, v, traceback)) if (REQUEST is None or (getattr(REQUEST.get('RESPONSE', None), '_error_format', '') != 'text/html')): reraise(t, v, traceback) # Lookup a view for the exception and render it, then # raise the rendered value as the exception value # (basically the same that 'raise_standardErrorMessage' # does. The view is named 'index.html' because that's what # zope.publisher uses as well. view = queryMultiAdapter((v, REQUEST), name=u'index.html') if view is not None: if (IAcquirer.providedBy(view) and IAcquirer.providedBy(published)): view = view.__of__(published) else: view.__parent__ = published v = view() if issubclass(t, Unauthorized): # Re-raise Unauthorized to make sure it is handled # correctly. We can't do that with all exceptions # because some don't work with the rendered v as # argument. reraise(t, v, traceback) response = REQUEST.RESPONSE response.setStatus(t) response.setBody(v) return response if (published is None or published is app or isinstance(published, list)): # At least get the top-level object published = app.__bobo_traverse__(REQUEST).__of__( RequestContainer(REQUEST)) published = getattr(published, 'im_self', published) while 1: f = getattr(published, self.raise_error_message, None) if f is None: published = aq_parent(published) if published is None: reraise(t, v, traceback) else: break client = published while 1: if getattr(client, self.error_message, None) is not None: break client = aq_parent(client) # If we are going in circles without getting the error_message # let the response handle it if client is None or aq_base(client) is aq_base(published): response = REQUEST.RESPONSE response.exception() return response if REQUEST.get('AUTHENTICATED_USER', None) is None: REQUEST['AUTHENTICATED_USER'] = AccessControl.User.nobody result = f(client, REQUEST, t, v, traceback, error_log_url=error_log_url) if result is not None: t, v, traceback = result if issubclass(t, Unauthorized): # Re-raise Unauthorized to make sure it is handled # correctly. We can't do that with all exceptions # because some don't work with the rendered v as # argument. reraise(t, v, traceback) response = REQUEST.RESPONSE response.setStatus(t) response.setBody(v) return response finally: traceback = None
def _exec(self, bound_data, args, kw): # Cook if we haven't already self._cook_check() # Get our caller's namespace, and set up our own. cns = bound_data['caller_namespace'] ns = self._Bindings_ns_class() push = ns._push ns.guarded_getattr = None ns.guarded_getitem = None req = None kw_bind = kw if cns: # Someone called us. push(cns) ns.level = cns.level + 1 ns.this = getattr(cns, 'this', None) # Get their bindings. Copy the request reference # forward, and include older keyword arguments in the # current 'keyword_args' binding. try: last_bound = ns[('current bindings', )] last_req = last_bound.get('REQUEST', None) if last_req: bound_data['REQUEST'] = last_req old_kw = last_bound['keyword_args'] if old_kw: kw_bind = old_kw.copy() kw_bind.update(kw) except Exception: pass else: # We're first, so get the REQUEST. try: req = aq_acquire(self, 'REQUEST') if hasattr(req, 'taintWrapper'): req = req.taintWrapper() except Exception: pass bound_data['REQUEST'] = req ns.this = bound_data['context'] # Bind 'keyword_args' to the complete set of keyword arguments. bound_data['keyword_args'] = kw_bind # Push globals, initialized variables, REQUEST (if any), # and keyword arguments onto the namespace stack for nsitem in (self.globals, self._vars, req, kw): if nsitem: push(nsitem) # Push the 'container' (default), 'context', or nothing. bind_to = self._Bindings_client if bind_to in ('container', 'client'): push(InstanceDict(bound_data[bind_to], ns)) # Push the name bindings, and a reference to grab later. push(bound_data) push({('current bindings', ): bound_data}) security = getSecurityManager() security.addContext(self) try: value = self.ZDocumentTemplate_beforeRender(ns, _marker) if value is _marker: try: result = render_blocks(self._v_blocks, ns) except DTReturn as v: result = v.v except AttributeError: if (type(sys.exc_info()[1]) == InstanceType and sys.exc_value.args[0] == "_v_blocks"): LOG.warn("DTML file '%s' could not be read" % self.raw) raise ValueError( "DTML file error: Check logfile for details") else: raise self.ZDocumentTemplate_afterRender(ns, result) return result else: return value finally: security.removeContext(self) # Clear the namespace, breaking circular references. while len(ns): ns._pop()
def applyBrowserLayers(site): request = aq_acquire(site, 'REQUEST') sm = getSiteManager(site) layers = sm.getAllUtilitiesRegisteredFor(ILocalBrowserLayerType) for layer in layers: alsoProvides(request, layer)