def test_show_on_home_factory_does_not_remove_other_interfaces(self): applyProfile(self.portal, 'ftw.news:show-on-homepage') page = create(Builder('sl content page')) newsfolder = create(Builder('news folder').within(page)) news = create(Builder('news') .within(newsfolder) .having(news_date=datetime(2011, 1, 2, 15, 0, 0))) class IDummyMarkerInterface(Interface): pass directlyProvides(news, IDummyMarkerInterface) self.assertEqual( [IDummyMarkerInterface], list(directlyProvidedBy(news)) ) IShowOnHomepageSchema(news).show_on_homepage = True self.assertEqual( [IDummyMarkerInterface, IShowOnHomepage], list(directlyProvidedBy(news)) ) IShowOnHomepageSchema(news).show_on_homepage = False self.assertEqual( [IDummyMarkerInterface], list(directlyProvidedBy(news)) )
def test_directlyProvides(self): class IA1(Interface): pass class IA2(Interface): pass class IB(Interface): pass class IC(Interface): pass class A(Odd): pass classImplements(A, IA1, IA2) class B(Odd): pass classImplements(B, IB) class C(A, B): pass classImplements(C, IC) ob = C() directlyProvides(ob, I1, I2) self.assertTrue(I1 in providedBy(ob)) self.assertTrue(I2 in providedBy(ob)) self.assertTrue(IA1 in providedBy(ob)) self.assertTrue(IA2 in providedBy(ob)) self.assertTrue(IB in providedBy(ob)) self.assertTrue(IC in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob)-I2) self.assertTrue(I1 in providedBy(ob)) self.assertFalse(I2 in providedBy(ob)) self.assertFalse(I2 in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob), I2) self.assertTrue(I2 in providedBy(ob))
def metadata_setup(node): path = metadata_path(node.path) if not exists(path): return meta = get_metadata(path) for key, value in meta.items(): setattr(node, key, value) # XXX factor this out. if key in ('local_roles', ) and value: directlyProvides(node, ILocalRoles, directlyProvidedBy(node)) uid = getattr(node, 'uid', None) if uid is not None: record = get_rdb_metadata(node, uid) if record is not None: for key in record.__slots__: if hasattr(node, key): continue setattr(node, key, getattr(record, key)) if not IMetadata.providedBy(node): directlyProvides(node, IMetadata, directlyProvidedBy(node)) # XXX factor this out. acquire_attr(node, 'right_column') portal_type = getattr(node, 'portal_type', None) interface = registry.get('type_markers', {}).get(portal_type) if portal_type is not None and interface is not None: directlyProvides(node, interface, directlyProvidedBy(node)) parent_path = '/' + '/'.join(traversal_path(parent(node))) marker = registry.get('containment_markers', {}).get(parent_path) if marker is not None: directlyProvides(node, marker, directlyProvidedBy(node))
def test_directlyProvides(self): class IA1(Interface): pass class IA2(Interface): pass class IB(Interface): pass class IC(Interface): pass class A(Odd): pass classImplements(A, IA1, IA2) class B(Odd): pass classImplements(B, IB) class C(A, B): pass classImplements(C, IC) ob = C() directlyProvides(ob, I1, I2) self.assert_(I1 in providedBy(ob)) self.assert_(I2 in providedBy(ob)) self.assert_(IA1 in providedBy(ob)) self.assert_(IA2 in providedBy(ob)) self.assert_(IB in providedBy(ob)) self.assert_(IC in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob)-I2) self.assert_(I1 in providedBy(ob)) self.failIf(I2 in providedBy(ob)) self.failIf(I2 in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob), I2) self.assert_(I2 in providedBy(ob))
def test_directlyProvides(self): class IA1(Interface): pass class IA2(Interface): pass class IB(Interface): pass class IC(Interface): pass class A(Odd): implements(IA1, IA2) class B(Odd): implements(IB) class C(A, B): implements(IC) ob = C() directlyProvides(ob, I1, I2) self.assert_(I1 in providedBy(ob)) self.assert_(I2 in providedBy(ob)) self.assert_(IA1 in providedBy(ob)) self.assert_(IA2 in providedBy(ob)) self.assert_(IB in providedBy(ob)) self.assert_(IC in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob)-I2) self.assert_(I1 in providedBy(ob)) self.failIf(I2 in providedBy(ob)) self.failIf(I2 in providedBy(ob)) directlyProvides(ob, directlyProvidedBy(ob), I2) self.assert_(I2 in providedBy(ob))
def _gpgAuthenticateEmail(mail, principal, person, signature_timestamp_checker): """Check GPG signature. :param principal: Claimed sender of the mail; to be checked against the actual signature. :returns: principal, either strongly or weakly authenticated. """ log = logging.getLogger('process-mail') signature = mail.signature email_addr = parseaddr(mail['From'])[1] if signature is None: # Mark the principal so that application code can check that the # user was weakly authenticated. log.debug('message has no signature; therefore weakly authenticated') directlyProvides( principal, directlyProvidedBy(principal), IWeaklyAuthenticatedPrincipal) setupInteraction(principal, email_addr) return principal gpghandler = getUtility(IGPGHandler) try: sig = gpghandler.getVerifiedSignature( canonicalise_line_endings(mail.signedContent), signature) log.debug("got signature %r" % sig) except GPGVerificationError as e: # verifySignature failed to verify the signature. message = "Signature couldn't be verified: %s" % e log.debug(message) raise InvalidSignature(message) if signature_timestamp_checker is None: signature_timestamp_checker = ensure_sane_signature_timestamp # If this fails, we return an error to the user rather than just treating # it as untrusted, so they can debug or understand the problem. signature_timestamp_checker( sig.timestamp, 'incoming mail verification') for gpgkey in person.gpg_keys: if gpgkey.fingerprint == sig.fingerprint: log.debug('gpg-signed message by key %r' % gpgkey.fingerprint) break else: # The key doesn't belong to the user. Mark the principal so that the # application code knows that the key used to sign the email isn't # associated with the authenticated user. log.debug('gpg-signed message but by no known key of principal') directlyProvides( principal, directlyProvidedBy(principal), IWeaklyAuthenticatedPrincipal) setupInteraction(principal, email_addr) return principal
def test_context_manager_adds_book_layers(self): thelist = list(directlyProvidedBy(self.portal.REQUEST)) with providing_book_layers(self.portal, self.portal.REQUEST): diff = [it for it in list( directlyProvidedBy(self.portal.REQUEST)) if it not in thelist] self.assertEquals( ['<InterfaceClass ftw.book.interfaces.IWithinBookLayer>'], [str(item) for item in diff]) self.assertEquals(thelist, list(directlyProvidedBy(self.portal.REQUEST)))
def _gpgAuthenticateEmail(mail, principal, person, signature_timestamp_checker): """Check GPG signature. :param principal: Claimed sender of the mail; to be checked against the actual signature. :returns: principal, either strongly or weakly authenticated. """ log = logging.getLogger('process-mail') signature = mail.signature email_addr = parseaddr(mail['From'])[1] if signature is None: # Mark the principal so that application code can check that the # user was weakly authenticated. log.debug('message has no signature; therefore weakly authenticated') directlyProvides(principal, directlyProvidedBy(principal), IWeaklyAuthenticatedPrincipal) setupInteraction(principal, email_addr) return principal gpghandler = getUtility(IGPGHandler) try: sig = gpghandler.getVerifiedSignature( canonicalise_line_endings(mail.signedContent), signature) log.debug("got signature %r" % sig) except GPGVerificationError as e: # verifySignature failed to verify the signature. message = "Signature couldn't be verified: %s" % e log.debug(message) raise InvalidSignature(message) if signature_timestamp_checker is None: signature_timestamp_checker = ensure_sane_signature_timestamp # If this fails, we return an error to the user rather than just treating # it as untrusted, so they can debug or understand the problem. signature_timestamp_checker(sig.timestamp, 'incoming mail verification') for gpgkey in person.gpg_keys: if gpgkey.fingerprint == sig.fingerprint: log.debug('gpg-signed message by key %r' % gpgkey.fingerprint) break else: # The key doesn't belong to the user. Mark the principal so that the # application code knows that the key used to sign the email isn't # associated with the authenticated user. log.debug('gpg-signed message but by no known key of principal') directlyProvides(principal, directlyProvidedBy(principal), IWeaklyAuthenticatedPrincipal) setupInteraction(principal, email_addr) return principal
def update(self): if 'ADD' in self.request: for interface in self.getIntrospector().getMarkerInterfaceNames(): if "add_%s" % interface in self.request: ob = self.context interface = getInterface(ob, interface) directlyProvides(removeAllProxies(ob), directlyProvidedBy(ob), interface) if 'REMOVE' in self.request: for interface in self.getIntrospector().getDirectlyProvidedNames(): if "rem_%s" % interface in self.request: ob = self.context interface = getInterface(ob, interface) directlyProvides(removeAllProxies(ob), directlyProvidedBy(ob)-interface)
def test_context_manager_adds_book_layers(self): thelist = list(directlyProvidedBy(self.portal.REQUEST)) with providing_book_layers(self.portal, self.portal.REQUEST): diff = [ it for it in list(directlyProvidedBy(self.portal.REQUEST)) if it not in thelist ] self.assertEquals( ['<InterfaceClass ftw.book.interfaces.IWithinBookLayer>'], [str(item) for item in diff]) self.assertEquals(thelist, list(directlyProvidedBy(self.portal.REQUEST)))
def migrate_class(self, obj, new_class): """Changes the class of a object and notifies the container so that the change is persistent. It has a special handling for BTreeFolder2Base based containers. Fires an event after class migration so that custom reference cleanup can be performed. """ obj.__class__ = new_class base = aq_base(obj) base._ofs_migrated = True base._p_changed = True parent = aq_base(aq_parent(obj)) id_ = base.getId() if isinstance(parent, BTreeFolder2Base): del parent._tree[id_] parent._tree[id_] = base else: parent._p_changed = True # Refresh provided interfaces cache directlyProvides(base, directlyProvidedBy(base)) notify(ClassMigratedEvent(obj))
def uninstall(context): marker = 'collective.opengraph_uninstall.txt' if context.readDataFile(marker) is None: return query = {'object_provides': 'collective.opengraph.interfaces.IOpengraphable'} catalog = api.portal.get_tool('portal_catalog') res = catalog(query) log.info("Removing interfaces from %s objects", len(res)) for item in res: ob = item.getObject() interface.directlyProvides( ob, interface.directlyProvidedBy(ob)-IOpengraphable-IOpengraphMarker) ob.reindexObject(idxs=['object_provides']) log.info("Unregistering utility") portal = api.portal.get() sm = portal.getSiteManager() try: util = sm.getUtility(IOpengraphMarkerUtility) del util except ComponentLookupError: pass sm.unregisterUtility(provided=IOpengraphMarkerUtility) sm.utilities.unsubscribe((), IOpengraphMarkerUtility) try: del sm.utilities.__dict__['_provided'][IOpengraphMarkerUtility] except KeyError: # already removed pass log.info("Committing transaction...") transaction.commit() log.info("done.")
def afterSetUp(self): # A hack to force gomobile.convergence install when running multiple tests on P3 name = "gomobile.convergence" qi = self.portal.portal_quickinstaller try: qi.uninstallProducts([name]) except: pass qi.installProduct(name) self.filter = getUtility(IConvergenceMediaFilter) # Set up convergence layer on HTTP request, # so that configure overrides kick in from plone.browserlayer import utils # TODO: Put following into a test case self.assertTrue(IConvergenceBrowserLayer in utils.registered_layers()) # Make sure that convergence layer is applied on the test request, # so that our custom views kick in #import pdb ; pdb.set_trace() directlyProvides(self.portal.REQUEST, [IConvergenceBrowserLayer] + list(directlyProvidedBy(self.portal.REQUEST)))
def mark_layer(site, event): """Mark the request with a layer corresponding to the current skin, as set in the portal_skins tool. """ if getattr(event.request, "_plonetheme_", False): return event.request._plonetheme_ = True portal_skins = getToolByName(site, 'portal_skins', None) if portal_skins is not None: skin_name = site.getCurrentSkinName() skin = queryUtility(IBrowserSkinType, name=skin_name) if skin is not None: layer_ifaces = [] default_ifaces = [] # We need to make sure IDefaultPloneLayer comes after # any other layers, even if they don't explicitly extend it. if IDefaultPloneLayer in skin.__iro__: default_ifaces += [IDefaultPloneLayer] for layer in directlyProvidedBy(event.request): if layer in default_layers: default_ifaces.append(layer) elif IBrowserSkinType.providedBy(layer): continue else: layer_ifaces.append(layer) ifaces = [ skin, ] + layer_ifaces + default_ifaces directlyProvides(event.request, *ifaces)
def getSkins(self, request=None): layout = self.getLayout() skins = [] if layout and request: request.debug = False ifaces = directlyProvidedBy(request) directlyProvides(request, ICollageBrowserLayer) target = self.context if ICollageAlias.providedBy(target): target = target.get_target() if not target: target = self.context view = getMultiAdapter((target, request), name=layout) skinInterfaces = getattr(view, "skinInterfaces", ()) for si in skinInterfaces: for name, utility in getUtilitiesFor(si): skins.append((name, utility.title)) # restore interfaces directlyProvides(request, ifaces) skins.sort(lambda x, y: cmp(x[0], y[0])) return skins
def providing_book_layers(book, request): original_interfaces = list(directlyProvidedBy(request)) provide_book_layers(book, request) try: yield finally: directlyProvides(request, *original_interfaces)
def _setWeakPrincipal(self): # Get the current principal to provide IWeaklyAuthenticatedPrincipal # this is set when the message is unsigned or the signature doesn't # match a key that the person has. cur_principal = get_current_principal() directlyProvides(cur_principal, directlyProvidedBy(cur_principal), IWeaklyAuthenticatedPrincipal)
def remove_marker_ifaces(context, ifaces): """Remove the given interfaces from all objects using a catalog query. context needs to either be the portal or be properly aq wrapped to allow for cmf catalog tool lookup. ifaces can be either a single interface or a sequence of interfaces. >>> from zope import interface >>> class ITest(interface.Interface): pass >>> class Mock(object): ... def __init__(self, id): self.id = id ... def getObject(self): return self ... def __repr__(self): return '<Mock id=%s>' % self.id >>> m = Mock('Portal Root') >>> objs = [Mock('m1'), Mock('m2'), Mock('m3')] >>> interface.directlyProvides(objs[1], ITest) >>> m.portal_catalog = lambda **kwargs: objs >>> remove_marker_ifaces(m, ITest) 1 >>> remove_marker_ifaces(m, [ITest]) 0 """ if not isinstance(ifaces, (tuple, list)): ifaces = [ifaces] count = 0 for iface in ifaces: for obj in objs_with_iface(context, iface): count += 1 provided = interface.directlyProvidedBy(obj) interface.directlyProvides(obj, provided - iface) return count
def configureXMLWidgets(root): """Configure XMLWidgets registries, editor, etc' """ # create the core widgets from the filesystem add_fss_directory_view(root, 'service_widgets', __file__, 'widgets') # create the editor service root.manage_addProduct['XMLWidgets'].manage_addEditorService( 'service_editor') # create the services for XMLWidgets for name in [ 'service_doc_editor', 'service_doc_previewer', 'service_doc_viewer', 'service_field_editor', 'service_field_viewer', 'service_nlist_editor', 'service_nlist_previewer', 'service_nlist_viewer', 'service_sub_editor', 'service_sub_previewer', 'service_sub_viewer', 'service_table_editor', 'service_table_viewer' ]: root.manage_addProduct['XMLWidgets'].manage_addWidgetRegistry(name) if IInvisibleService is not None: interface.directlyProvides( root[name], IInvisibleService, *interface.directlyProvidedBy(root[name])) # now register all widgets # XXX not really necessary; the "install" should take case of this registerCoreWidgets(root)
def objs_with_iface(context, iface): """Return all objects in the system as found by the nearest portal catalog that provides the given interface. The result will be a generator for scalability reasons. >>> from zope import interface >>> class ITest(interface.Interface): pass >>> class Mock(object): ... def __init__(self, id): self.id = id ... def getObject(self): return self ... def __repr__(self): return '<Mock id=%s>' % self.id >>> m = Mock('Portal Root') >>> objs = [Mock('m1'), Mock('m2'), Mock('m3')] >>> interface.directlyProvides(objs[1], ITest) >>> m.portal_catalog = lambda **kwargs: objs >>> [x for x in objs_with_iface(m, ITest)] [<Mock id=m2>] """ catalog = cmfutils.getToolByName(context, 'portal_catalog') for brain in catalog(object_provides=interfaceToName(context, iface)): obj = brain.getObject() if iface in interface.directlyProvidedBy(obj): yield brain.getObject()
def mark_layer(site, event): """Mark the request with a layer corresponding to the current skin, as set in the portal_skins tool. """ if getattr(event.request, "_plonetheme_", False): return event.request._plonetheme_=True portal_skins = getToolByName(site, 'portal_skins', None) if portal_skins is not None: skin_name = site.getCurrentSkinName() skin = queryUtility(IBrowserSkinType, name=skin_name) if skin is not None: layer_ifaces = [] default_ifaces = [] # We need to make sure IDefaultPloneLayer comes after # any other layers, even if they don't explicitly extend it. if IDefaultPloneLayer in skin.__iro__: default_ifaces += [IDefaultPloneLayer] for layer in directlyProvidedBy(event.request): if layer in default_layers: default_ifaces.append(layer) elif IBrowserSkinType.providedBy(layer): continue else: layer_ifaces.append(layer) ifaces = [skin, ] + layer_ifaces + default_ifaces directlyProvides(event.request, *ifaces)
def set_newsletter_state(self, state): if IPossibleNewsletter.providedBy(self.context): ifaces = interface.directlyProvidedBy(self.context) if state and not INewsletterEnhanced.providedBy(self.context): interface.alsoProvides(self.context, INewsletterEnhanced) elif not state and INewsletterEnhanced in ifaces: interface.directlyProvides(self.context, ifaces - INewsletterEnhanced)
def _set_activation(obj, possibleiface, enhancediface, activation): """Try to set the feature activation on the given object. """ if isinstance(possibleiface, basestring): raise NotImplementedError('Still need to locaate class via dotted ' 'path string') if isinstance(enhancediface, basestring): raise NotImplementedError('Still need to locaate class via ' 'dotted path string') if not possibleiface.providedBy(obj): raise ActivationException('The object denoted by %r does not ' 'provide the %r interface' % (repr(obj), repr(possibleiface))) if not activation and enhancediface.implementedBy(obj.__class__): raise ActivationException('It is not possible to remove %r from ' 'the %r since the class is the ' 'implementer' % (repr(possibleiface), repr(obj))) ifaces = interface.directlyProvidedBy(obj) if activation and not enhancediface.providedBy(obj): interface.alsoProvides(obj, enhancediface) event.notify(interfaces.FeatureActivatedEvent(enhancediface, obj)) elif not activation and enhancediface in ifaces: interface.directlyProvides(obj, ifaces - enhancediface) event.notify(interfaces.FeatureDeactivatedEvent(enhancediface, obj))
def contained(obj, parent=None, name=None): """An implementation of zope.app.container.contained.contained that doesn't generate events, for internal use. copied from SQLOS / z3c.zalchemy """ if (parent is None): raise TypeError('Must provide a parent') if not IContained.providedBy(obj): if ILocation.providedBy(obj): interface.directlyProvides(obj, IContained, interface.directlyProvidedBy(obj)) else: obj = ContainedProxy(obj) oldparent = obj.__parent__ oldname = obj.__name__ if (oldparent is None) or not (oldparent is parent or sameProxiedObjects(oldparent, parent)): obj.__parent__ = parent if oldname != name and name is not None: obj.__name__ = name return obj
def upgradeObj(self, obj, path=None): obj._p_activate() if self.delRemovedObj(obj, path): # Deleted don't do anything else return if '__implements__' in obj.__dict__: self.log('Deleting __implements__ instance attributre from %r' % obj) del obj.__dict__['__implements__'] obj._p_changed = True if zodb_ifaces.IBroken.providedBy(obj): self.log('Removing broken interfaces from %r: %r' % (obj, list(interface.directlyProvidedBy(obj)))) interface.noLongerProvides(obj, zodb_ifaces.IBroken) if not self.update_catalogs: return base = aq_base(obj) if ( not isinstance(obj, ZCatalog.ZCatalog) and callable(getattr(base, 'indexObject', None))): obj.indexObject() if callable(getattr(base, '_updateCatalog', None)): obj._updateCatalog(obj)
def interfaces_directlyProvidedBy(obj): """Dump out list of interfaces directlyProvidedBy obj. """ return """ interfaces directlyProvidedBy %s: %s""" % (repr(obj), "\n ".join( ["%s %s" % (i, id(i)) for i in interface.directlyProvidedBy(obj)] or ["</>"]))
def get_resource(self, resource): """ Get resource content """ # If resources are retrieved via GET, the request headers # are used for caching AND are mangled. # That can result in getting 304 responses # There is no API to extract the data from the view without # mangling the headers, so we must use a fake request # that can be modified without harm if resource.startswith('++resource++'): fake_request = TestRequest() # copy interfaces that may have been applied to the request to # the TestRequest: directlyProvides(fake_request, directlyProvidedBy(self.request)) traverser = getMultiAdapter((self.context, fake_request), name='resource') obj = traverser.traverse(resource[12:], None) else: obj = self.context.restrictedTraverse(resource, None) if not obj: return '/* ERROR */' try: content = obj.GET() except AttributeError, err: return str(obj)
def __call__(self): context = aq_inner(self.context) manager = IDynamicViewManager(context) layout = manager.getLayout() if not layout: layout, title = manager.getDefaultLayout() if ICollageAlias.providedBy(context): context = context.get_target() # if not set, revert to self.context if not context: context = self.context # transmute request interfaces ifaces = directlyProvidedBy(self.request) directlyProvides(self.request, ICollageBrowserLayer) view = getMultiAdapter((context, self.request), name=layout) # restore interfaces directlyProvides(self.request, ifaces) return view.index
def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] self.mtool = getToolByName(self.portal, 'portal_membership') self.acl = getToolByName(self.portal, 'acl_users') setRoles(self.portal, TEST_USER_ID, ['Manager']) # Layer for request ifaces = [IFtwUserManagement] + list(directlyProvidedBy(self.request)) directlyProvides(self.request, *ifaces) # Set authenticator flag to get a valid request value = self.portal.restrictedTraverse( '@@authenticator').authenticator() auth = re.search('value="(.*)"', value).group(1) self.request.form = dict(_authenticator=auth) self.request.other['method'] = 'POST' # Setup 10 Users registration = getToolByName(self.portal, 'portal_registration') for i in range(10): registration.addMember( '*****@*****.**' % i, '12345', properties={ 'username': '******' % i, 'email': '*****@*****.**' % i, }, REQUEST=self.layer['request']) # Setup 5 Groups groups_tool = getToolByName(self.portal, 'portal_groups') for i in range(5): groups_tool.addGroup('group_%s' % i)
def enabled(self, value): context = removeAllProxies(self.context) if value: interface.alsoProvides(context, self.marker) else: if self.marker in interface.directlyProvidedBy(context): interface.noLongerProvides(context, self.marker)
def _createBook(self): id = self.portal.invokeFactory( 'Folder', 'Maths', title=u"Maths Grade 10") book = self.portal._getOb(id) directlyProvides(book, directlyProvidedBy(book), INavigationRoot) structure = (('folder001', 'Folder', u'Folder 001'), ('folder002', 'Folder', u'Folder 002'), ('folder003', 'Folder', u'Folder 003'), ) for number, details in enumerate(structure): itemId, itemType, itemTitle = details id = book.invokeFactory(itemType, itemId, title=itemTitle) chapter = book[id] chapter.setNextPreviousEnabled(True) chapter.setExcludeFromNav(False) id = chapter.invokeFactory( 'File', 'file%s' %number, title=u'File %s' %number) item = chapter._getOb(id) item.setNextPreviousEnabled(True) item.setExcludeFromNav(False) chapter.setDefaultPage(id) return book
def getInterfaces(self, obj): if not obj: return None doc = self.doc root = doc.createElement('interfaces') ifaces = [i.__identifier__ for i in directlyProvidedBy(obj)] if self.include: ifaces = filter(lambda i: i in self.include, ifaces) elif self.exclude: ifaces = filter(lambda i: not i in self.include, ifaces) if ifaces == []: return None for iface in ifaces: # create record record = doc.createElement('record') # add object interface text = doc.createTextNode(iface) record.appendChild(text) root.appendChild(record) doc.appendChild(root) try: data = doc.toprettyxml(indent=' ', encoding='utf-8') except UnicodeDecodeError, e: # all comments are strings encoded in 'utf-8' and they will properly # saved in xml file, but if we explicitly give 'utf-8' encoding # UnicodeDecodeError will be raised when they have non-ascii chars data = doc.toprettyxml(indent=' ')
def configureXMLWidgets(root): """Configure XMLWidgets registries, editor, etc' """ # create the core widgets from the filesystem add_fss_directory_view(root, 'service_widgets', __file__, 'widgets') # create the editor service root.manage_addProduct['XMLWidgets'].manage_addEditorService( 'service_editor') # create the services for XMLWidgets for name in ['service_doc_editor', 'service_doc_previewer', 'service_doc_viewer', 'service_field_editor', 'service_field_viewer', 'service_nlist_editor', 'service_nlist_previewer', 'service_nlist_viewer', 'service_sub_editor', 'service_sub_previewer', 'service_sub_viewer', 'service_table_editor', 'service_table_viewer']: root.manage_addProduct['XMLWidgets'].manage_addWidgetRegistry(name) if IInvisibleService is not None: interface.directlyProvides( root[name], IInvisibleService, *interface.directlyProvidedBy(root[name])) # now register all widgets # XXX not really necessary; the "install" should take case of this registerCoreWidgets(root)
def publishTraverse(self, request, name): request.survey = self.context utils.setLanguage(request, self.context, self.context.language) if name not in ["view", "index_html"] and \ not self.hasValidSession(request): request.response.redirect( aq_parent(aq_parent(self.context)).absolute_url(), lock=True) return self.context if name not in self.phases: return super(SurveyPublishTraverser, self)\ .publishTraverse(request, name) # Decorate the request with the right skin layer and add to the aq path directlyProvides(request, self.phases[name], *directlyProvidedBy(request)) self.context = PathGhost(name).__of__(self.context) session = SessionManager.session tree_id = find_sql_context(session.id, request['TraversalRequestNameStack']) if tree_id is not None: return build_tree_aq_chain(self.context, tree_id) # No SQL based traversal possible, return the existing context with the # new skin layer applied return self.context
def copyRelationsOnSourceCopy(obj, event): """Copies all source relaitonships marked with IRetainOnCopy when the source object is copied""" orig_obj = obj.__orig_object__.aq_inner source = IRelationshipSource(orig_obj) cur_ifaces = directlyProvidedBy(obj) directlyProvides(obj, *[i for i in cur_ifaces if i is not ICopyPendingAdd]) delattr(obj, '__orig_object__') copy_filter = IRetainOnCopy.providedBy # this is not efficient to source objects with a huge number of # relations rels = source.getRelationships(rel_filter=copy_filter) container = getUtility(IComplexRelationshipContainer, name='relations') unwrapped_obj = aq_base(obj) for rel in rels: # copy the relationship rel_copy = locationCopy(aq_base(rel)) # The references on the copy becames copies themselves we need # to make sure all such references point to the originals: rel_copy.__dict__ = rel.__dict__ # We should also remove existing ILocation pointers rel_copy.__parent__ = rel_copy.__name__ = None # Now we add the relationship (with wrong sources for now) to # give it a context. container.add(rel_copy) # replace the old sources with just the copy rel_copy.sources = (obj,)
def applySkin(request, skin): """Change the presentation skin for this request. >>> import pprint >>> from zope.interface import Interface, providedBy >>> class SkinA(Interface): pass >>> directlyProvides(SkinA, ISkin) >>> class SkinB(Interface): pass >>> directlyProvides(SkinB, ISkin) >>> class IRequest(Interface): pass >>> class Request(object): ... implements(IRequest) >>> req = Request() >>> applySkin(req, SkinA) >>> pprint.pprint(list(providedBy(req).interfaces())) [<InterfaceClass zope.app.publisher.browser.SkinA>, <InterfaceClass zope.app.publisher.browser.IRequest>] >>> applySkin(req, SkinB) >>> pprint.pprint(list(providedBy(req).interfaces())) [<InterfaceClass zope.app.publisher.browser.SkinB>, <InterfaceClass zope.app.publisher.browser.IRequest>] """ # Remove all existing skin declarations (commonly the default skin). ifaces = [iface for iface in directlyProvidedBy(request) if not ISkin.providedBy(iface)] # Add the new skin. ifaces.append(skin) directlyProvides(request, *ifaces)
def get_specification(spec, force=False): """Get the specification of the given object. If the given object is already a specification acceptable to the component architecture, it is simply returned. This is true for classes and specification objects (which includes interfaces). In case of instances, an interface is generated on the fly and tagged onto the object. Then the interface is returned as the specification. """ # If the specification is an instance, then we do some magic. if (force or (spec is not None and not ISpecification.providedBy(spec) and not isinstance(spec, class_types))): # Step 1: Calculate an interface name iface_name = 'IGeneratedForObject_%i' % id(spec) # Step 2: Find out if we already have such an interface existing_interfaces = [ i for i in directlyProvidedBy(spec) if i.__name__ == iface_name ] # Step 3a: Return an existing interface if there is one if len(existing_interfaces) > 0: spec = existing_interfaces[0] # Step 3b: Create a new interface if not else: iface = InterfaceClass(iface_name) alsoProvides(spec, iface) spec = iface return spec
def getItems(self, contents=None): # needed to circumvent bug :-( self.request.debug = False # transmute request interfaces ifaces = directlyProvidedBy(self.request) directlyProvides(self.request, ICollageBrowserLayer) views = [] if not contents: contents = self.context.folderlistingFolderContents() for context in contents: target = context manager = IDynamicViewManager(context) layout = manager.getLayout() if not layout: layout, title = manager.getDefaultLayout() if ICollageAlias.providedBy(context): target = context.get_target() # if not set, revert to context if target is None: target = context # verify that target is accessible try: getSecurityManager().validate(self, self, target.getId(), target) except Unauthorized: continue # Filter out translation duplicates: # If a non-alias object is translatable, check if its language # is set to the currently selected language or to neutral, # or if it is the canonical version elif isTranslatable(target): language = self.request.get('LANGUAGE','') if target.Language() not in (language, ''): # Discard the object, if it is not the canonical version # or a translation is available in the requested language. if not target.isCanonical() or target.getTranslation(language) in contents: continue # assume that a layout is always available view = getMultiAdapter((target, self.request), name=layout) # store reference to alias if applicable if ICollageAlias.providedBy(context): view.__alias__ = context views.append(view) # restore interfaces directlyProvides(self.request, ifaces) return views
def test_hostname_switching_view(self): view = api.content.get_view(context=self.portal, request=self.request, name='sitemap') html = view() active = [x for x in directlyProvidedBy(self.request)] self.assertFalse(IThemeASpecific in active) self.assertFalse('testthemeA title' in html)
def get_directly_provided_interfaces(self): try: from zope.interface import directlyProvidedBy except: return self['_directly_provided'] = [ it.__identifier__ for it in directlyProvidedBy(self.context) ]
def test_hostname_layer_filtering(self): request = self.request request['HTTP_HOST'] = 'cms.localhost:8080' self.bust_request_caches() policy = theming_policy(request) policy.filter_request() active = [x for x in directlyProvidedBy(request)] self.assertFalse(IThemeASpecific in active)
def remove_request_interfaces(self): # Remove custom book interfaces from request to_remove = [IWithinBookLayer, IDefaultBookLayoutSelectionLayer] ifaces = [ iface for iface in directlyProvidedBy(self.request) if iface not in to_remove ] directlyProvides(self.request, *ifaces)
def switch_skin(content, event): print "IA AM CALLED FORM", content site = getSite() request = event.request if '__ac' not in request.get('HTTP_COOKIE', ''): ifaces = [IAnonymousLayer] + list(directlyProvidedBy(request)) directlyProvides(request, *ifaces) else: print "ANON REQ"
def schoolToolTraverseSubscriber(event): """A subscriber to BeforeTraverseEvent. Adds DevMode layer to the request. """ if (ISchoolToolApplication.providedBy(event.object) and IBrowserRequest.providedBy(event.request)): directlyProvides(event.request, directlyProvidedBy(event.request) + IDevModeLayer)
def mark_layer(site, event): base.mark_layer(site, event) request = event.request registry = component.getUtility(IRegistry) settings = registry.forInterface(interfaces.IThemeSettings) if request.get('BASE1') == settings.domain: ifaces = [interfaces.IBrowserLayer] + list( interface.directlyProvidedBy(request)) interface.directlyProvides(request, *ifaces)
def get_iresource(context) -> IInterface: """Get the :class:`adhocracy_core.interfaces.IResource` of `context`. :return: :class:`IInterface` or None to ease testing """ ifaces = list(directlyProvidedBy(context)) iresources = [i for i in ifaces if i.isOrExtends(IResource)] return iresources[0] if iresources else None
def unpigeonholize(self, portal_type): """Remove pigeonhole awareness from content_type""" site = getSite() catalog = getToolByName(site, 'portal_catalog') for brain in catalog(portal_type=portal_type): obj = brain.getObject() if IPigeonholeAware.providedBy(obj): directlyProvides(obj, directlyProvidedBy(obj)-IPigeonholeAware) self.ph_aware_types = list(set(self.ph_aware_types) - set([portal_type]))
def registerObject(self, ob, adapter=NO_ADAPTER_NEEDED, depth=1): if adapter is NO_ADAPTER_NEEDED: zi.directlyProvides(ob, self.subject) elif adapter is DOES_NOT_SUPPORT: zi.directlyProvides(ob, zi.directlyProvidedBy(ob) - self.subject) return supermeta(ZopeInterfaceAsProtocol, self).registerObject(ob, adapter, depth)
def _apply(request, skin): """Apply skin to request""" ifaces = [ iface for iface in directlyProvidedBy(request) if not issubclass(iface, IBaseLayer) ] # Add the new skin. ifaces.append(skin.layer) directlyProvides(request, *ifaces) LOGGER.debug("Applied skin {0!r} to request {1!r}".format( skin.label, request))
def bootstrapSchoolTool(self, db): """Bootstrap SchoolTool database.""" connection = db.open() root = connection.root() app_obj = root.get(ZopePublication.root_name) if app_obj is None: app = SchoolToolApplication() # Run school specific initialization code initializationUtility = getUtility( ISchoolToolInitializationUtility) initializationUtility.initializeApplication(app) directlyProvides(app, directlyProvidedBy(app) + IContainmentRoot) root[ZopePublication.root_name] = app # savepoint to make sure that the app object has # a _p_jar. This is needed to make things like # KeyReference work, which in turn is needed to # make the catalog work. We make this savepoint # optimistic because it will then work with any registered # data managers that do not support this feature. transaction.savepoint(optimistic=True) # set up the site so that local utility setups and catalog # indexing would work properly if not ISite.providedBy(app): app.setSiteManager(LocalSiteManager(app)) setSite(app) # We must set up the int ids utility before setting up any # of the plugin specific catalogs, as catalogs rely on # IntIds being present setUpUtilities(app, [UtilitySpecification(IntIds, IIntIds)]) # tell plugins to initialize their catalogs, must be done # before initializing plugins themselves or else all the # initial groups, persons, resources will not get indexed notify(CatalogSetUpEvent(app)) notify(CatalogStartUpEvent(app)) # initialize plugins themselves notify(ApplicationInitializationEvent(app)) notify(ObjectAddedEvent(app)) # unset the site so we would not confuse other # bootstraping code setSite(None) self.restoreManagerUser(app, MANAGER_PASSWORD) self.initializePreferences(app) transaction.commit() connection.close()
def _get_request_interfaces(self): request = self.layer['request'] setDefaultSkin(request) orig_iro = list(directlyProvidedBy(request).__iro__) directlyProvides(request, [self.additive_layer] + orig_iro) # Reset markers so that we can still register new skins and browserlayers del request._plonebrowserlayer_ del request._plonetheme_ notify(BeforeTraverseEvent(self.portal, request)) iro = list(request.__provides__.__iro__) return iro
def applySkin(request, skin, skin_type): """Change the presentation skin for this request. """ # Remove all existing skin declarations (commonly the default skin). ifaces = [ iface for iface in interface.directlyProvidedBy(request) if not skin_type.providedBy(iface) ] # Add the new skin. ifaces.append(skin) interface.directlyProvides(request, *ifaces)