def testSchemaDisplay(self): self.assertEqual( component.queryMultiAdapter((ob, request), name='view.html'), None) xmlconfig(StringIO(template % (''' <view type="zope.publisher.interfaces.browser.IBrowserRequest" for="zope.schema.interfaces.IField" provides="zope.formlib.interfaces.IDisplayWidget" factory="zope.app.form.browser.DisplayWidget" permission="zope.Public" /> <browser:schemadisplay for="zope.app.form.browser.tests.test_directives.IC" schema="zope.app.form.browser.tests.test_directives.Schema" name="view.html" label="View a ZPT page" fields="text" permission="zope.Public" /> '''))) v = component.queryMultiAdapter((ob, request), name='view.html') # expect to fail as standard macros are not configured self.assertRaises(TraversalError, v)
def publishTraverse(self, request, name): # 1. Look for a named traverser plugin. named_traverser = queryMultiAdapter((self.context, request), interfaces.ITraverserPlugin, name=name) if named_traverser is not None: try: return named_traverser.traverse(name) except NotFound: pass # 2. Named traverser plugin was of no use, let's try a generic one. traverser = queryMultiAdapter((self.context, request), interfaces.ITraverserPlugin) if traverser is not None: try: return traverser.traverse(name) except NotFound: pass # 3. The traversers did not have an answer, so let's see whether it is # a view. view = queryMultiAdapter((self.context, request), name=name) if view is not None: return view raise NotFound(self.context, name, request)
def testSchemaDisplayWithWidget(self): self.assertEqual( component.queryMultiAdapter((ob, request), name='view.html'), None) xmlconfig(StringIO(template % (''' <view type="zope.publisher.interfaces.browser.IBrowserRequest" for="zope.schema.interfaces.IField" provides="zope.formlib.interfaces.IDisplayWidget" factory="zope.app.form.browser.DisplayWidget" permission="zope.Public" /> <browser:schemadisplay for="zope.app.form.browser.tests.test_directives.IC" schema="zope.app.form.browser.tests.test_directives.Schema" name="view.html" label="View a ZPT page" fields="text" permission="zope.Public"> <browser:widget field="text" class="zope.app.form.browser.tests.test_directives.SomeWidget" displayWidth="30" extra="foo" /> </browser:schemadisplay> '''))) view = component.queryMultiAdapter((ob, request), name='view.html') self.assert_(hasattr(view, 'text_widget')) self.assert_(isinstance(view.text_widget, SomeWidget)) self.assertEqual(view.text_widget.extra, u'foo') self.assertEqual(view.text_widget.displayWidth, 30)
def testView(self): self.assertEqual( component.queryMultiAdapter((ob, request), name='test'), None) xmlconfig.file("xmlrpc.zcml", xmlrpc.tests) view = component.queryMultiAdapter((ob, request), name='test') self.assert_(V1 in view.__class__.__bases__) self.assert_(xmlrpc.MethodPublisher in view.__class__.__bases__)
def findView(tile, viewName): """Find the view to use for portlet/viewlet context lookup.""" view = tile prequest = tile.request.get('PARENT_REQUEST', None) # Attempt to determine the underlying view name from the parent request # XXX: This won't work if using ESI rendering or any other # technique that doesn't use plone.subrequest if viewName is None and prequest is not None: ppublished = prequest.get('PUBLISHED', None) if IView.providedBy(ppublished): viewName = prequest['PUBLISHED'].__name__ context = tile.context request = tile.request if prequest is not None: request = prequest if viewName is not None: view = queryMultiAdapter((context, request), name=viewName) if view is None: view = tile # Decide whether to mark the view # XXX: Again, this probably won't work well if not using plone.subrequest layoutPolicy = queryMultiAdapter((context, request), name='plone_layout') if layoutPolicy is not None: layoutPolicy.mark_view(view) return view
def get_previews(self, **kwargs): catalog = getToolByName(self.context, 'portal_catalog') result = catalog(self._query(**kwargs)) batch = BaseBatch(result, self.bsize, start=self.bstart) previews = [] if self.bstart >= batch.end: return '' for brain in batch: obj = brain.getObject() adapter = queryMultiAdapter((obj, obj.REQUEST), IWorkspacePreview) # Try to get a specific preview adapter for extension in self.get_extensions(obj.getContentType()): specific = queryMultiAdapter( (obj, obj.REQUEST), IWorkspacePreview, name=extension) if specific is not None: adapter = specific break previews.append(adapter) return previews
def __call__(self): support = queryMultiAdapter((self.context, self.request), name="epub.support") if not getattr(support, "can_download", lambda: False)(): raise NotFound(self.context, self.__name__, self.request) # Fallback ePub provided if self.fallback: return self.request.response.redirect(self.fallback) epub = queryMultiAdapter((self.context, self.request), name="epub.body") body = epub() css = epub.css() ecover = queryMultiAdapter((self.context, self.request), name="epub.cover") cover = ecover(header=False, safe=True) output = StringIO() html2epub = queryUtility(IHtml2EPub) html2epub( body, cover, output, title=self.context.Title(), base_url=self.context.absolute_url(), css=css, cookies=self.request.cookies, ) response = self.request.response response.setHeader("Content-Type", "application/xml+epub") response.setHeader("Content-Disposition", "attachment; filename=%s.epub" % self.context.id) output.seek(0) return output.read()
def handleApply(self, action): data, errors = self.extractData() type_id = data['type'] portal = getSite() base_url = self.context.absolute_url() adding_view = queryMultiAdapter((self.context, self.request), name='+') t = getattr(portal.portal_types, type_id, None) if t: # XXX: Added to support CMF 2.2 style add view actions context_state = getMultiAdapter((self.context, self.request), name='plone_context_state') addActionsById = dict([(a['id'], a['url'],) for a in context_state.actions().get('folder/add', []) if a['available'] and a['allowed']]) # XXX: Added to support CMF 2.2 style add view actions if addActionsById.get(type_id, ''): # we have a non-empty URL url = addActionsById[type_id] elif adding_view and queryMultiAdapter((adding_view, self.request), name=t.factory): url = '%s/+/%s' % (base_url, t.factory) else: url = '%s/createObject?type_name=%s' % (base_url, quote_plus(type_id)) self.request.response.redirect(url)
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 findViewletManager(self, name): managerObj = queryMultiAdapter((self.context, self.request, self), IViewletManager, name) if not managerObj: # Here's where we go totally off the deep end... # Since we can't find this viewlet manager with the basic (self.context, self.request, self) # multiadapter lookup, this must be some sort of custom manager, registered to other interfaces. # In order to find it, we need to do a bit of reverse engineering... # Since Plone's generic setup process for viewlets constrains us to one viewlet manager / name, # we're going to assume that the adapter with this name, and a provided interface that is or extends IViewletManger # is the one we're looking for. # So, start with a search of the adapter registry... reg = [reg for reg in getGlobalSiteManager().registeredAdapters() if reg.name == name][0] # So far, I think we're stuck with context and request being the first two interfaces. providedClasses = [self.context, self.request] # Now, we take a look at the required interfaces... # And create some dummy classes that implement them. for iface in reg.required[2:]: tempClass = classobj("dummy", (object,), {}) classImplements(tempClass, iface) providedClasses.append(tempClass()) # Now just do a basic multiadapter lookup using our new objects providing the correct interfaces... managerObj = queryMultiAdapter(tuple(providedClasses), reg.provided, name) return managerObj
def getTileViewByName(self, tile_name): """We look up for adapter from ``(context, request, tileType)`` to an appropriate interface. The default is to use the unnamed adapter, but this can be overridden by registering a named adapter with the name of the tile type. This way, a custom add/edit view can be registered for a particular type of tile. """ tile_info = queryUtility(ITileType, name=tile_name) if tile_info is None: raise KeyError(tile_name) view = queryMultiAdapter((self.context, self.request, tile_info), self.targetInterface, name=tile_name) if view is None: view = queryMultiAdapter((self.context, self.request, tile_info), self.targetInterface) if view is None: raise KeyError(tile_name) view.__name__ = tile_name view.__parent__ = self.context return view
def test_ct_views(self): zcml.load_config('testing.zcml', collective.carousel) # test tile for a Page obj = getattr(self.folder, 'carousel-doc') tile = queryMultiAdapter((obj, self.app.REQUEST), name="carousel-view") self.failUnless('PAGE' in tile(), obj) # test tile for a News Item obj = getattr(self.folder, 'carousel-news-item') tile = queryMultiAdapter((obj, self.app.REQUEST), name="carousel-view") self.failUnless('NEWS ITEM' in tile(), obj) # test tile for an Event. # Since we don't have any special view registered for Event in # zcml we should get default view for an object of this content type obj = getattr(self.folder, 'carousel-event') tile = queryMultiAdapter((obj, self.app.REQUEST), name="carousel-view") self.failUnless('DEFAULT' in tile(), obj) # test tile for a Page in a carousel portlet # since we don't have any special view for Page in the carousel portlet # we should get default tile for the carousel portlet that is the same # as for a carousel in the viewlet obj = getattr(self.folder, 'carousel-doc') tile = queryMultiAdapter((obj, self.app.REQUEST), name="carousel-portlet-view") self.failUnless('<p>This is a DEFAULT tile</p>' in tile(), obj)
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 test_portlet_inheritance(self): portal = self.layer['portal'] folder = portal.folder2 request = folder.REQUEST view = folder.restrictedTraverse('@@plone') alsoProvides(view, IViewView) self.assertTrue(IViewView.providedBy(view)) viewlet_manager = queryMultiAdapter( (folder, request, view), IContentProvider, 'plone.abovecontentbody') viewlet = queryMultiAdapter( (folder, request, view, viewlet_manager), IViewlet, 'collective.calltoaction') self.assertTrue(viewlet is not None) viewlet.update() # The portlet from the test fixture is blocked. self.assertEqual(len(viewlet.data), 0) # Show the action globally. This ignores portlet inheritance. registry = getUtility(IRegistry) settings = registry.forInterface( ICollectiveCalltoactionSettings, check=False) self.assertFalse(settings.show_global) settings.show_global = True # Now we should see the portlet viewlet.update() self.assertEqual(len(viewlet.data), 1)
def testUpgradeTinyMCE(self): # skip test in new Plones that don't install tinymce to begin with if 'portal_tinymce' not in self.portal: return alphas.upgradeTinyMCE(self.portal.portal_setup) jstool = getToolByName(self.portal, 'portal_javascripts') jsresourceids = jstool.getResourceIds() self.assertTrue('jquery.tinymce.js' in jsresourceids) for ne in ['tiny_mce.js', 'tiny_mce_init.js']: self.assertFalse(ne in jsresourceids) ksstool = getToolByName(self.portal, 'portal_kss', None) if ksstool is not None: kssresourceids = ksstool.getResourceIds() self.assertFalse( '++resource++tinymce.kss/tinymce.kss' in kssresourceids) request = self.app.REQUEST plone_view = queryMultiAdapter((self.portal, request), name="plone") manager = queryMultiAdapter( (self.portal, request, plone_view), IContentProvider, 'plone.htmlhead') viewlets = getAdapters( (manager.context, manager.request, manager.__parent__, manager), IViewlet) self.assertFalse(u'tinymce.configuration' in dict(viewlets))
def setgridstate(self): """Stores the current grid configuration (visible columns, column order, grouping, sorting etc.) persistent in dictstorage. """ if not self.user_is_logged_in(): return # extract the data state = self.request.get('gridstate', None) if not state or not isinstance(state, str): return if state == '{}': state = '' # get the tab view view_name = self.request.get('view_name', None) if not view_name: return listing_view = queryMultiAdapter((self.context, self.request), name='tabbedview_view-%s' % view_name) if not listing_view: return # get the key for storing the state generator = queryMultiAdapter( (self.context, listing_view, self.request), IGridStateStorageKeyGenerator) key = generator.get_key() # store the data storage = IDictStorage(listing_view) storage.set(key, state)
def __init__(self, context, request): self.context = context self.request = request self.tools = queryMultiAdapter((self.context, self.request), name="plone_tools") self.pps = queryMultiAdapter((self.context, self.request), name="plone_portal_state") self.sitemaps = [i.getObject() for i in self.tools.catalog()(portal_type='Sitemap')]
def publishTraverse(self, request, name): try: obj = super(RESTTraverse, self).publishTraverse(request, name) if (not IContentish.providedBy(obj) and not IService.providedBy(obj)): if isinstance(obj, VirtualHostMonster): return obj else: raise KeyError except KeyError: # No object, maybe a named rest service service = queryMultiAdapter((self.context, request), name=request._rest_service_id + name) if service is None: # No service, fallback to regular view view = queryMultiAdapter((self.context, request), name=name) if view is not None: return view raise return service if name.startswith(request._rest_service_id): return obj # Do not handle view namespace if '@@' in request['PATH_INFO'] or '++view++' in request['PATH_INFO']: return obj # Wrap object to ensure we handle further traversal return RESTWrapper(obj, request)
def update(self): self.portal_state = queryMultiAdapter((self.context, self.request), name='plone_portal_state') # noqa self.context_state = queryMultiAdapter((self.context, self.request), name='plone_context_state') # noqa self.request.form = encode_dict(self.request.form) request_params = self._get_params self._get_listings(request_params)
def testUpgradeTinyMCE(self): alphas.upgradeTinyMCE(self.portal.portal_setup) jstool = getToolByName(self.portal, 'portal_javascripts') jsresourceids = jstool.getResourceIds() self.assertIn('jquery.tinymce.js', jsresourceids) for ne in ['tiny_mce.js', 'tiny_mce_init.js']: self.assertNotIn(ne, jsresourceids, ne) ksstool = getToolByName(self.portal, 'portal_kss', None) if ksstool is not None: kssresourceids = ksstool.getResourceIds() self.assertNotIn('++resource++tinymce.kss/tinymce.kss', kssresourceids) request = self.app.REQUEST plone_view = queryMultiAdapter((self.portal, request), name="plone") manager = queryMultiAdapter( (self.portal, request, plone_view), IContentProvider, 'plone.htmlhead') viewlets = getAdapters( (manager.context, manager.request, manager.__parent__, manager), IViewlet) self.assertIn(u'tinymce.configuration', dict(viewlets)) storage = getUtility(IViewletSettingsStorage) skinname = self.portal.getCurrentSkinName() order_by_name = storage.getOrder('plone.htmlhead', skinname) self.assertEqual(order_by_name[-1], u'tinymce.configuration')
def subtype(obj, evt): """ Subtype as faceted navigable """ context = obj portal_type = getattr(context, 'portal_type', None) if portal_type != 'EEARelationsContentType': return # Subtype as faceted navigable subtyper = queryMultiAdapter((context, context.REQUEST), name=u'faceted_search_subtyper', default=queryMultiAdapter( (context, context.REQUEST), name=u'faceted_subtyper')) if subtyper: subtyper.enable() # Add default widgets widgets = queryMultiAdapter((context, context.REQUEST), name=u'default_widgets.xml') if not widgets: return xml = widgets() environ = SnapshotImportContext(context, 'utf-8') importer = queryMultiAdapter((context, environ), IBody) if not importer: return importer.body = xml
def move(self, pos): """ Move the item. x and y are in view coordinates. """ super(DropZoneInMotion, self).move(pos) item = self.item view = self.view x, y = pos current_parent = view.canvas.get_parent(item) over_item = view.get_item_at_point((x, y), selected=False) if not over_item: view.dropzone_item = None view.window.set_cursor(None) return if current_parent and not over_item: # are we going to remove from parent? adapter = component.queryMultiAdapter((current_parent, item), IGroup) if adapter: view.window.set_cursor(OUT_CURSOR) view.dropzone_item = current_parent current_parent.request_update(matrix=False) if over_item: # are we going to add to parent? adapter = component.queryMultiAdapter((over_item, item), IGroup) if adapter and adapter.can_contain(): view.dropzone_item = over_item view.window.set_cursor(IN_CURSOR) over_item.request_update(matrix=False)
def publishTraverse(self, request, name): # Try to get an object using default traversal adapter = DefaultPublishTraverse(self.context, request) try: obj = adapter.publishTraverse(request, name) if (not IContentish.providedBy(obj) and not IService.providedBy(obj)): raise KeyError # If there's no object with the given name, we get a KeyError. # In a non-folderish context a key lookup results in an AttributeError. except (KeyError, AttributeError): # No object, maybe a named rest service service = queryMultiAdapter((self.context, request), name=request._rest_service_id + name) if service is None: # No service, fallback to regular view view = queryMultiAdapter((self.context, request), name=name) if view is not None: return view raise return service else: # Wrap object to ensure we handle further traversal return RESTWrapper(obj, request)
def restful_query_view(request, obj, name=""): method = request.method target = methods.get(method) result = queryMultiAdapter((obj, request), target, name=name) if result is None and method != FALLBACK: result = queryMultiAdapter((obj, request), target, name=name) return result
def testEditFormWithMenu(self): self.assertEqual( component.queryMultiAdapter((ob, request), name='edit.html'), None) xmlconfig(StringIO(template % (''' <browser:menu id="test_menu" title="Test menu"/> <view type="zope.publisher.interfaces.browser.IBrowserRequest" for="zope.schema.interfaces.ITextLine" provides="zope.formlib.interfaces.IInputWidget" factory="zope.app.form.browser.TextWidget" permission="zope.Public" /> <browser:editform for="zope.app.form.browser.tests.test_directives.IC" schema="zope.app.form.browser.tests.test_directives.Schema" name="edit.html" label="Edit a ZPT page" fields="text" permission="zope.Public" menu="test_menu" title="Test View" /> '''))) v = component.queryMultiAdapter((ob, request), name='edit.html') # expect to fail as standard macros are not configured self.assertRaises(TraversalError, v)
def test_foo(self): index = queryMultiAdapter((Spionisto(), TestRequest()), name='index') self.assertNotEqual(index, None) # There is no view called 'index2' index2 = queryMultiAdapter((Spionisto(), TestRequest()), name='index2') self.assertEqual(index2, None)
def __call__(self): alsoProvides(self, IViewView) manager = queryMultiAdapter( (self.context, self.request, self), IViewletManager, name='plone.belowcontent' ) viewlet = queryMultiAdapter( (self.context, self.request, self, manager), IViewlet, name='plone.comments' ) if viewlet is not None: viewlet.form = TileCommentForm viewlet.update() if isinstance(viewlet.form, TileCommentForm): viewlet.form.action = self.url # Fix submit redirect from tile to context if 'location' in self.request.response.headers: location = self.request.response.getHeader('location') self.request.response.redirect(''.join([ self.context.absolute_url(), '#', location.split('#')[-1] ])) return protect(u'<html><body>%s</body></html>' % viewlet.render()) else: return u'<html><body></body></html>'
def test_viewlet(self): request = self.folder.REQUEST view = self.folder.restrictedTraverse('@@plone') alsoProvides(view, IViewView) self.assertTrue(IViewView.providedBy(view)) viewlet_manager = queryMultiAdapter( (self.folder, request, view), IContentProvider, 'plone.abovecontentbody') viewlet = queryMultiAdapter( (self.folder, request, view, viewlet_manager), IViewlet, 'collective.calltoaction') self.assertTrue(viewlet is not None) viewlet.update() # We expect data from the portlet assignment in # profiles/testfixture/portlets.xml. self.assertEqual(len(viewlet.data), 1) portlet = viewlet.data[0] self.assertIn('assignment', portlet.keys()) self.assertIn('html', portlet.keys()) assignment = portlet['assignment'] self.assertEqual(assignment.milli_seconds_until_overlay, 1000) portlet_html = portlet['html'] self.assertIn('portletCallToAction', portlet_html) self.assertIn('portletCallToAction', portlet_html) viewlet_html = viewlet.render() self.assertIn(portlet_html, viewlet_html) self.assertIn('data-timeout="1000"', viewlet_html)
def query(self, default=None): request = self.request content = self.getLocation() if content is None: return item = IItem(content, None) title = u'' description = u'' if item is not None: title = item.title description = item.description view = queryMultiAdapter((content, request), IContentViewView) if view is not None: url = '%s/%s'%(absoluteURL(content, request), view.name) else: url = '%s/'%absoluteURL(content, request) return {'url': url, 'title': title or _('[No title]'), 'content': content, 'icon': queryMultiAdapter((content, request), name='zmi_icon'), 'description': description or u''}
def publishTraverse(self, request, name): """Allow traversal to @@<view>/tilename/tileid """ # 1. Look up the view, but keep this view as the traversal context in # anticipation of an id if self.view is None: tile_info = queryUtility(ITileType, name=name) if tile_info is None: raise KeyError(name) self.view = queryMultiAdapter((self.context, self.request, tile_info), self.targetInterface, name=name) if self.view is None: self.view = queryMultiAdapter((self.context, self.request, tile_info), self.targetInterface) if self.view is None: raise KeyError(name) self.view.__name__ = name self.view.__parent__ = self.context return self # 2. Set the id and return the view we looked up in the previous # traversal step. elif getattr(self.view, 'tileId', None) is None: self.view.tileId = name return self.view raise KeyError(name)
def __bobo_traverse__(self, REQUEST, name): try: return self[name] except KeyError: pass if hasattr(aq_base(self), name): return getattr(self, name) # webdav method = REQUEST.get('REQUEST_METHOD', 'GET').upper() if (method not in ('GET', 'POST') and not isinstance(REQUEST.RESPONSE, xmlrpc.Response) and REQUEST.maybe_webdav_client and not REQUEST.path): return ReflectoNullResource(self, name, REQUEST).__of__(self) # try to find a view subobject = queryMultiAdapter((self, REQUEST), Interface, name) if subobject is not None: return subobject.__of__(self) # finally try acquired objects return getattr(self, name)
def have_portlets(self, manager_name, view=None): """Determine whether a column should be shown. The left column is called plone.leftcolumn; the right column is called plone.rightcolumn. """ force_disable = self.request.get('disable_' + manager_name, None) if force_disable is not None: return not bool(force_disable) context = self.context if view is None: view = self manager = queryUtility(IPortletManager, name=manager_name) if manager is None: return False renderer = queryMultiAdapter(( context, self.request, view, manager), IPortletManagerRenderer) if renderer is None: renderer = getMultiAdapter(( context, self.request, self, manager), IPortletManagerRenderer) return renderer.visible
def importResRegistry(context, reg_id, reg_title, filename): """Import resource registry. """ site = context.getSite() logger = context.getLogger('resourceregistry') body = context.readDataFile(filename) if body is None: return res_reg = getToolByName(site, reg_id) importer = queryMultiAdapter((res_reg, context), IBody) if importer is None: logger.warning("%s: Import adapter missing." % reg_title) return try: importer.registry = getToolByName(site, 'portal_registry') except AttributeError: # Upgrade 3.x no registry there importer.registry = None importer.body = body logger.info("%s imported." % reg_title)
def transformIterable(self, result, encoding): if self.published is None or \ not self.request.get('plone.app.blocks.enabled', False) or \ not isinstance(result, XMLSerializer): return None context = aq_parent(aq_base(self.published)) or api.portal.get() layout = queryMultiAdapter((context, self.request), name='plone_layout') root = result.tree.getroot() body = root.find('body') if layout and body is not None: class_ = layout.bodyClass(None, self.published) body.attrib['class'] = ' '.join( body.attrib.get('class', '').split() + class_.split()) gridSystem = xpath1(gridXPath, result.tree) if body is not None and gridSystem is None: body.attrib['class'] = ' '.join( (body.attrib.get('class', ' '), 'mosaic-grid')) return result
def _initSettings(self, obj, profile_id, obj_path): stool = queryUtility(ISetupTool) if stool is None: return context = stool._getImportContext(profile_id) file_ids = context.listDirectory('workflows') for file_id in file_ids or (): filename = 'workflows/%s/definition.xml' % file_id body = context.readDataFile(filename) if body is None: continue root = parseString(body).documentElement if not root.getAttribute('workflow_id') == obj_path[0]: continue importer = queryMultiAdapter((obj, context), IBody) if importer is None: continue importer.body = body return
def locked_icon(self): if not getSecurityManager().checkPermission('Modify portal content', self.context): return "" locked = False lock_info = queryMultiAdapter((self.context, self.request), name='plone_lock_info') if lock_info is not None: locked = lock_info.is_locked() else: context = aq_inner(self.context) lockable = getattr(context.aq_explicit, 'wl_isLocked', None ) is not None locked = lockable and context.wl_isLocked() if not locked: return "" portal = self.portal_state.portal() icon = portal.restrictedTraverse('lock_icon.png') return icon.tag(title='Locked')
def setResult(self, result): 'See IHTTPResponse' if IResult.providedBy(result): r = result else: r = component.queryMultiAdapter((result, self._request), IResult) if r is None: if isinstance(result, basestring): r = result elif result is None: r = '' else: raise TypeError( 'The result should be None, a string, or adaptable to ' 'IResult.') if isinstance(r, basestring): r, headers = self._implicitResult(r) self._headers.update(dict((k, [v]) for (k, v) in headers)) r = (r,) # chunking should be much larger than per character self._result = r if not self._status_set: self.setStatus(200)
def annotateBrainInfo(info, request, urlOnly=None): """Adds details about the object taken from its brain Note on the optimization that this achieves: There are a couple of cases where there are a lot of results (for example from a catalog search of "same theme") that are trimmed down to a couple of objects. We don't want to compute getObjectInfo for each, because that's expensive. Instead we first call getBrainInfo for each brain, trim the result and then call annotateBrainInfo for each brain. """ if info.get('brain'): brain = info['brain'] obj = brain.getObject() state = getMultiAdapter((obj, request), name="plone_context_state") url = state.view_url() if not urlOnly: imgview = queryMultiAdapter((obj, request), name="imgview") info['has_img'] = (imgview is not None and imgview.display() is True) info['item_mimetype'] = obj.get_content_type() info['url'] = url
def get_portlet_assignment_xml(context, prefix): doc = PrettyDocument() node = doc.createElement('portlets') for manager_name, manager in getUtilitiesFor(IPortletManager): mapping = queryMultiAdapter((context, manager), IPortletAssignmentMapping) if mapping is None: continue mapping = mapping.__of__(context) key = '/'.join(context.getPhysicalPath()) if key.startswith(prefix): key = key[len(prefix):] key = key or '/' extract_mapping(doc, node, manager_name, CONTEXT_CATEGORY, key, mapping) doc.appendChild(node) xml = patch_portlets_xml(doc.toprettyxml(' '), prefix) doc.unlink() return xml
def test_initial_tab_is_reseted_on_every_request(self): portal = self.layer['portal'] foobar_view = queryMultiAdapter((portal, portal.REQUEST), name='tabbed_view') key_generator = getMultiAdapter((portal, foobar_view, portal.REQUEST), IDefaultTabStorageKeyGenerator) key = key_generator.get_key() # first call IDictStorage(foobar_view)[key] = 'footab' html = foobar_view() doc = pq(html) initial_tab = doc('#tabbedview-header .tabbedview-tabs a.initial') self.assertEqual(1, len(initial_tab)) self.assertEqual('MyTitle', initial_tab.text()) # second call IDictStorage(foobar_view)[key] = 'notranslation' html = foobar_view() doc = pq(html) initial_tab = doc('#tabbedview-header .tabbedview-tabs a.initial') self.assertEqual(1, len(initial_tab)) self.assertEqual('notranslation', initial_tab.text())
def get_default_traversal(self, request, ob): """Get the default traversal steps for an object. Returns (next_object, steps). """ if request.form_action: # Do not follow default traversal when a form action was # provided. return ob, None if IBrowserPublisher.providedBy(ob): # ob is already proxied, so the result of calling a method # will be too. return ob.browserDefault(request) adapter = queryMultiAdapter((ob, request), IBrowserPublisher) if adapter is not None: ob, path = adapter.browserDefault(request) ob = self.proxy_factory(ob) return ob, path # ob is already proxied return ob, None
def zpublisher_exception_hook_wrapper(published, REQUEST, t, v, traceback): """ wrapper around the zope2 zpublisher's error hook """ try: # if we got a retry exception, we just propagate it instead of # trying to log it (like FiveException does) if t is Retry: v.reraise() # first we try to find a view/adapter for the current exception and # let the original function try to handle the exception if we can't # find one... view = queryMultiAdapter((v, REQUEST), name='index.html', default=None) if view is None: zpublisher_exception_hook(published, REQUEST, t, v, traceback) else: # otherwise render the view and raise the rendered string like # raise_standardErrorMessage does... view = view.__of__(published) message = view() if isinstance(message, unicode): message = message.encode('utf-8') raise t, message, traceback finally: traceback = None
def catalog_object(self, object, uid, idxs=None, update_metadata=1, pghandler=None): if idxs is None: idxs = [] w = object if not IIndexableObject.providedBy(object): # This is the CMF 2.2 compatible approach, which should be used going forward wrapper = component.queryMultiAdapter((object, self), IIndexableObject) if wrapper is not None: w = wrapper ZCatalog.catalog_object(self, w, uid, idxs, update_metadata, pghandler=pghandler)
def siteGroups(self): '''The site and groups that the user is in :returns: A list of sites (:class:`.interfaces.ISiteGroups`) that the user is a member of at least one group in the site. :rtype: list''' retval = [] groupIds = [ s.split('_member')[0] for s in self.userInfo.user.getGroups() ] siteIds = [sid for sid in groupIds if sid in self.sites()] content = self.context.site_root().Content if siteIds: siteGroups = [ queryMultiAdapter((self.userInfo, getattr(content, s)), ISiteGroups) for s in siteIds ] retval = [ sg for sg in siteGroups if sg and (sg.groupInfos is not []) ] assert type(retval) == list return retval
def test_add_portlet(self): portal = self.layer['portal'] request = self.layer['request'] request.environ['HTTP_X_BRIDGE_ORIGIN'] = 'client-one' request.form['path'] = '@@watcher-feed?uid=567891234' view = queryMultiAdapter((portal, request), name='add-watcher-portlet') self.assertEqual(len(self._get_portlets()), 0) self.assertEqual(view(), 'OK') portlets = self._get_portlets() self.assertEqual(len(portlets), 1) self.assertEqual(portlets[0].client_id, 'client-one') self.assertEqual(portlets[0].path, '@@watcher-feed?uid=567891234') self.assertEqual(view(), 'OK') self.assertEqual(len(self._get_portlets()), 2) self.assertEqual(view(), 'OK') self.assertEqual(len(self._get_portlets()), 3)
def migrate_dashboards(context): """ Migrate single dashboard settings to multiple-dashboards """ ctool = getToolByName(context, 'portal_catalog') brains = ctool( object_provides=('eea.app.visualization.subtypes.interfaces.' 'IVisualizationEnabled')) logger.info('Migrating %s Google Dashboards ...', len(brains)) for brain in brains: doc = brain.getObject() migrate = queryMultiAdapter((doc, doc.REQUEST), name=u'migrate-dashboards') if not migrate: continue info = migrate() if info: logger.info(info) else: logger.info('Skipping %s', brain.getURL()) logger.info('Migrating Google Dashboards ... DONE')
def encode(self, value, charset='utf-8', primary=False): if value is None: return None valueTypeMarshaler = queryMultiAdapter( (self.context, self.field.value_type,), IFieldMarshaler) if valueTypeMarshaler is None: return None ascii = True value_lines = [] for item in value: marshaledValue = valueTypeMarshaler.encode( item, charset=charset, primary=primary) if marshaledValue is None: marshaledValue = '' value_lines.append(marshaledValue) if not valueTypeMarshaler.ascii: ascii = False self.ascii = ascii return '||'.join(value_lines)
def catalog_object(self, obj, uid=_deprecated, idxs=None, update_metadata=1, pghandler=None): # Wraps the object with workflow and accessibility # information just before cataloging. # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool if IIndexableObject.providedBy(obj): w = obj else: w = queryMultiAdapter((obj, self), IIndexableObject) if w is None: # BBB w = IndexableObjectWrapper(obj, self) ZCatalog.catalog_object(self, w, uid=_deprecated, idxs=idxs, update_metadata=update_metadata, pghandler=pghandler)
def trash(self): if not _checkPermission('opengever.trash: Trash content', self.context): raise Unauthorized() folder = aq_parent(aq_inner(self.context)) if not _checkPermission('opengever.trash: Trash content', folder): raise Unauthorized() if ITrashed.providedBy(self.context): raise TrashError('Already trashed') manager = queryMultiAdapter((self.context, self.context.REQUEST), ICheckinCheckoutManager) if manager and manager.get_checked_out_by(): raise TrashError('Document checked out') alsoProvides(self.context, ITrashed) # Trashed objects will be filtered from catalog search results by # default via a monkey patch somewhere in opengever.base.monkey self.reindex() notify(TrashedEvent(self.context))
def setup_personal_folder(site): from plone.portlets.interfaces import ILocalPortletAssignmentManager from plone.portlets.interfaces import IPortletManager from Products.CMFPlone.utils import _createObjectByType from intranett.policy.config import PERSONAL_FOLDER_ID personal_folder_title = _(u'Personal folders') title = translate(personal_folder_title, target_language=site.Language()) portal = getToolByName(site, 'portal_url').getPortalObject() _createObjectByType('Folder', portal, id=PERSONAL_FOLDER_ID, title=title) folder = portal[PERSONAL_FOLDER_ID] folder.setExcludeFromNav(True) folder.processForm() # Fire events workflow = getToolByName(portal, 'portal_workflow') workflow.doActionFor(folder, 'publish') # Block all portlets for manager_name in ('plone.leftcolumn', 'plone.rightcolumn'): manager = queryUtility(IPortletManager, name=manager_name) if manager is not None: assignable = queryMultiAdapter((folder, manager), ILocalPortletAssignmentManager) assignable.setBlacklistStatus('context', True) assignable.setBlacklistStatus('group', True) assignable.setBlacklistStatus('content_type', True)
def counters(self, **kwargs): """ Return current counters """ if self.request: kwargs.update(self.request.form) if not self.visible(**kwargs): return "[]" handler = queryMultiAdapter((self.context, self.request), name=u'faceted_query') criteria = queryAdapter(self.context, ICriteria) res = [] for cid, criterion in criteria.items(): widget = criteria.widget(cid=cid) widget = widget(self.context, self.request, criterion) if not isinstance(widget, CountableWidget): continue if widget.hidden: continue if not widget.countable: continue rep = {} props = kwargs.copy() props.pop(cid, None) title = criterion.get('title', None) or criterion.getId() rep[title] = handler.criteria(sort=False, **props) res.append(rep) if not res: return "[]" return pformat(res)
def testNamedViewPageViewsWithDefault(self): self.assertEqual( component.queryMultiAdapter((ob, self.request), name='test'), None) test3 = os.path.join(tests_path, u'testfiles', u'test3.pt') xmlconfig( StringIO(template % u''' <browser:view name="test" class="zope.browserpage.tests.test_page.V1" for="zope.browserpage.tests.test_page.IC" permission="zope.Public" > <browser:defaultPage name="test.html" /> <browser:page name="index.html" attribute="index" /> <browser:page name="action.html" attribute="action" /> <browser:page name="test.html" template="%s" /> </browser:view> ''' % test3)) view = component.getMultiAdapter((ob, self.request), name='test') view = removeSecurityProxy(view) self.assertEqual( view.browserDefault(self.request)[1], (u'test.html', )) v = view.publishTraverse(self.request, 'index.html') v = removeSecurityProxy(v) self.assertEqual(v(), 'V1 here') v = view.publishTraverse(self.request, 'action.html') v = removeSecurityProxy(v) self.assertEqual(v(), 'done') v = view.publishTraverse(self.request, 'test.html') v = removeSecurityProxy(v) self.assertEqual( str(v()).replace('\r\n', '\n'), "<html><body><p>done</p></body></html>\n")
def _initSettings(self, obj, profile_id, obj_path): stool = getToolByName(self, 'portal_setup', None) if stool is None: return context = stool._getImportContext(profile_id) file_ids = context.listDirectory('types') for file_id in file_ids or (): if not file_id.endswith('.xml'): continue filename = 'types/%s' % file_id body = context.readDataFile(filename) if body is None: continue root = parseString(body).documentElement new_id = str(root.getAttribute('name')) if not new_id: # BBB: for CMF 1.5 profiles new_id = str(root.getAttribute('id')) if new_id != obj_path[0]: continue # BBB: for CMF 1.5 profiles meta_type = str(root.getAttribute('kind')) if not meta_type: meta_type = str(root.getAttribute('meta_type')) if meta_type != self.klass.meta_type: continue importer = queryMultiAdapter((obj, context), IBody) if importer is None: continue importer.body = body return
def serialize(self, obj): results = [] errorLog = '' serializer = queryMultiAdapter((obj, self.request), ISerializeToJson) data = serializer() # del MUST_EXCLUDED_ATTRIBUTES from data self.exclude_attributes(data) # Get relative path of contxt portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state') site = portal_state.portal() site_path = site.getPhysicalPath() context_path = obj.getPhysicalPath() relative_path = context_path[len(site_path):] data['path'] = "/".join(relative_path) # record required data if data.get('@type', None) != 'Plone Site': results = [data] for member in obj.objectValues(): # FIXME: default plone config @portal_type? if member.portal_type != 'Plone Site': try: objData = self.serialize(member) results += objData[:-1] if objData[-1] != '': errorLog += objData[-1] except Exception as e: errorLog += str('Error: ' + repr(e) + ' for ' + str(member.absolute_url_path()[1:]) + '\n') results.append(errorLog) return results
def test_checkout_and_edit(self, browser): self.login(self.regular_user, browser) manager = queryMultiAdapter( (self.document, self.portal.REQUEST), ICheckinCheckoutManager, ) self.assertEquals( None, manager.get_checked_out_by(), 'Didn\'t expect the document to be checked out yet.' ) browser.open(self.document, view='tabbedview_view-overview') browser.find('Checkout and edit').click() self.assertEquals( self.document.absolute_url(), browser.url, 'editing_document should redirect back to document', ) self.assertEquals( 'kathi.barfuss', manager.get_checked_out_by(), 'The document should be checked out by the test user now.', ) self.assertIn( '/'.join(( self.document.absolute_url(), 'external_edit' )), browser.css('script.redirector').first.text, 'Redirector should open external_edit.', )
def write(self, subReport=False, **kwargs): """ AT to surf """ resource = self.resource context = self.context language = context.Language() question = context.getQuestion() if context.portal_type == 'DiversityReport': question = vocab.long_diversity_questions.get(question, question) elif context.portal_type == 'CommonalityReport': question = vocab.long_questions.get(question, question) resource.soer_question = (question, language) resource.soer_geoCoverage = rdflib.URIRef(context.getGeoCoverage()) resource.soer_hasFigure = [] if subReport: resource.soer_sortOrder = \ context.aq_parent.getObjectPosition(context.getId()) + 1 for obj in context.objectValues(): surfObj = queryMultiAdapter((obj, self.session), interface=IObject2Surf) if surfObj is not None: if obj.portal_type == 'Image': resource.soer_hasFigure.append(surfObj.resource) elif obj.portal_type in ['DataSourceLink', 'Link']: # We allowed normal links as data source pre 0.5 resource.soer_dataSource.append(surfObj.resource) elif obj.portal_type == 'RelatedIndicatorLink': resource.soer_relatedEuropeanIndicator.append( (rdflib.URIRef(obj.getRemoteUrl()), language)) else: # Current resource has the sort order 0 since it is # parent to the other reports resource.soer_sortOrder = 0 surfObj.write(subReport=True) resource.save() return resource
def extract_text(block, obj, request): """Extract text information from a block. This function tries the following methods, until it finds a result: 1. searchableText attribute 2. Server side adapter 3. Subblocks The decision to use the server side adapter before the subblocks traversal allows addon developers to choose this implementation when they want a more granular control of the indexing. :param block: Dictionary with block information. :param obj: Context to be used to get a IBlockSearchableText. :param request: Current request. :returns: A string with text found in the block. """ result = "" block_type = block.get("@type", "") # searchableText is the conventional way of storing # searchable info in a block searchableText = block.get("searchableText", "") if searchableText: # TODO: should we evaluate in some way this value? maybe passing # it into html/plain text transformer? return searchableText # Use server side adapters to extract the text data adapter = queryMultiAdapter((obj, request), IBlockSearchableText, name=block_type) result = adapter(block) if adapter is not None else "" if not result: subblocks = extract_subblocks(block) for subblock in subblocks: tmp_result = extract_text(subblock, obj, request) result = f"{result}\n{tmp_result}" return result
def __call__(self, version=None): version = 'current' if version is None else version obj = self.getVersion(version) parent = aq_parent(aq_inner(obj)) parent_summary = getMultiAdapter((parent, self.request), ISerializeToJsonSummary)() result = { # '@context': 'http://www.w3.org/ns/hydra/context.jsonld', '@id': obj.absolute_url(), 'id': obj.id, '@type': obj.portal_type, 'parent': parent_summary, 'created': json_compatible(obj.created()), 'modified': json_compatible(obj.modified()), 'review_state': self._get_workflow_state(obj), 'UID': obj.UID(), 'version': version, 'layout': self.context.getLayout(), } for schema in iterSchemata(obj): read_permissions = mergedTaggedValueDict(schema, READ_PERMISSIONS_KEY) for name, field in getFields(schema).items(): if not self.check_permission(read_permissions.get(name), obj): continue serializer = queryMultiAdapter((field, obj, self.request), IFieldSerializer) value = serializer() result[json_compatible(name)] = value return result
def _get_viewlets(self, provider, role="_ZenCommon_Permission"): """ In the case of a NotFound, there is no authenticated user available, so we just have to use the lowest common denominator, specified as C{role}. In the case of another exception type, we have the user, but security isn't entirely set up correctly, so we have to make this view appear to be in the context (it actually has none, not being an Acquisition.Implicit). The upshot of all this is that for exceptions, nav will appear as it normally would for the user. For NotFound, it'll appear as it would for any user with ZenCommon permission. """ # Check to see if we're authenticated userid = getSecurityManager().getUser().getId() if userid is None: # Not authenticated, force some local roles for the Anonymous user self.__ac_local_roles__ = {userid: [role]} else: # Authenticated, force this view to be in a working context self._parent = self.dmd # Look up the viewlets mgr = queryMultiAdapter((self.dmd, self.request, self), IViewletManager, provider) # Activate the viewlets mgr.update() if userid is None: # No security stuff is in place, because we're not authenticated, # so the manual permission checking in # ZenUI3.navigation.menuitem.PrimaryNavigationMenuItem.render will # cause nothing to be returned. Short-circuit permissions, since # dmd doesn't have them set anyway. Since we're already using the most # restrictive authenticated role there is, this won't cause # anything to display that shouldn't. for viewlet in mgr.viewlets: viewlet.__ac_permissions__ = None return mgr.render()
def form_widgets(self, fields): default_icon = self.api.static_url + '/images/defaultUser.gif' system_name = get_setting(self.context, 'system_name', 'KARL') widgets = { 'biography': karlwidgets.RichTextWidget(), 'password': formish.Password(), 'password_confirm': formish.Password(), 'country': formish.SelectChoice(countries), 'photo': karlwidgets.PhotoImageWidget(filestore=self.filestore, url_base=resource_url( self.context, self.request, 'photo'), image_thumbnail_default=default_icon), 'date_format': formish.SelectChoice(cultures), 'websites': formish.TextArea(rows=3, converter_options={'delimiter': '\n'}), } r = queryMultiAdapter((self.context, self.request), IInvitationBoilerplate) if r is None: r = DefaultInvitationBoilerplate(self.context) terms_text = r.terms_and_conditions if terms_text: widgets['terms_and_conditions'] = (karlwidgets.AcceptFieldWidget( terms_text, 'the %s Terms and Conditions' % system_name)) privacy_text = r.privacy_statement if privacy_text: widgets['accept_privacy_policy'] = (karlwidgets.AcceptFieldWidget( privacy_text, 'the %s Privacy Policy' % system_name)) return widgets