def unregisterService(service, interface): """Unregister the service using the given interface. """ site = service.aq_parent if not ISite.providedBy(site): raise ValueError("Service parent is not a site.") sm = ISite(site).getSiteManager() sm.unregisterUtility(service, interface)
def getNearestSite(self): """See ILocationInfo """ if ISite.providedBy(self.context): return self.context for parent in self.getParents(): if ISite.providedBy(parent): return parent return self.getRoot()
def delete_site(self): if not self.is_site(): raise ValueError(_(u'Not a local site.')) if interfaces.IRoot.providedBy(self.context): raise ValueError(_(u"Can't disable local site on Silva Root.")) sm = ISite(self.context).getSiteManager() if list(sm.registeredAdapters()): raise ValueError(_(u'Still have registered customizations.')) if list(sm.registeredUtilities()): raise ValueError(_(u'Still have registered services.')) disableSite(self.context)
def delete_site(self): if not self.is_site(): raise ValueError(_('Not a local site.')) if interfaces.IRoot.providedBy(self.context): raise ValueError(_("Can't disable local site on Silva Root.")) sm = ISite(self.context).getSiteManager() if list(sm.registeredAdapters()): raise ValueError(_('Still have registered customizations.')) if list(sm.registeredUtilities()): raise ValueError(_('Still have registered services.')) disableSite(self.context)
def ensure_site(context): """Ensure the given context implements ISite. The importance of this method is that it will ensure the given context is an ISite regardless of the Zope version (Zope 2.9 had a really hacked up SiteManager mechanism we have to account for). >>> from zope.location.interfaces import ISite, IPossibleSite >>> from OFS.Folder import Folder >>> if not IPossibleSite.implementedBy(Folder): ... from zope import interface ... from Products.Five.site.metaconfigure import (FiveSite, ... classSiteHook) ... classSiteHook(Folder, FiveSite) ... interface.classImplements(Folder, IPossibleSite) >>> om = Folder('foo') >>> ISite.providedBy(om) False >>> try: ... ensure_site(om) ... except TypeError: ... # not supposed to do anything unless enableLocalSiteHook was found ... if enableLocalSiteHook is None: ... True True """ if not IPossibleSite.providedBy(context): if hasattr(context, 'getPhysicalPath'): p = '/'.join(context.getPhysicalPath()) elif hasattr(context, 'getId'): p = context.getId() elif hasattr(context, 'id'): p = id else: p = str(context) raise TypeError('The object, "%s", is not an IPossibleSite' % p) if not ISite.providedBy(context): if enableLocalSiteHook is not None: enableLocalSiteHook(context) setSite(context) else: raise TypeError('"%s" is not configured as an ISite' % '/'.join(context.getPhysicalPath())) if not ISite.providedBy(context): raise TypeError('Somehow trying to configure "%s" as an ISite ' 'has failed' % '/'.join(context.getPhysicalPath()))
def registerService(context, id, service, interface): """Set and register the service id, using interface. """ if not ISite.providedBy(context.aq_base): site = context.Destination() if not ISite.providedBy(site): raise BadRequest("A service can only be created in a local site") else: site = context site._setObject(id, service) service = site._getOb(id) sm = site.getSiteManager() sm.registerUtility(service, interface) return service
def enableZope3Site(context): portal = getToolByName(context, 'portal_url').getPortalObject() if not ISite.providedBy(portal): make_objectmanager_site(portal) logger.info('Made the portal a Zope3 site.') try: components = portal.getSiteManager() except ComponentLookupError: next = find_next_sitemanager(portal) if next is None: next = base name = '/'.join(portal.getPhysicalPath()) components = PersistentComponents(name, (next,)) components.__parent__ = portal portal.setSiteManager(components) logger.info("Site manager '%s' added." % name) else: if components.utilities.LookupClass != FiveVerifyingAdapterLookup: # for CMF 2.1 beta instances components.__parent__ = portal components.utilities.LookupClass = FiveVerifyingAdapterLookup components.utilities._createLookup() components.utilities.__parent__ = components logger.info('LookupClass replaced.') # Make sure to set the new site as the new active one setSite(portal)
def _maybePlacefullyAuthenticate(self, request, ob): if not IUnauthenticatedPrincipal.providedBy(request.principal): # We've already got an authenticated user. There's nothing to do. # Note that beforeTraversal guarentees that user is not None. return if not ISite.providedBy(ob): # We won't find an authentication utility here, so give up. return sm = removeSecurityProxy(ob).getSiteManager() auth = sm.queryUtility(IAuthentication) if auth is None: # No auth utility here return # Try to authenticate against the auth utility principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # nothing to do here return request.setPrincipal(principal)
def SilvaZMIFilter(container, filter_addable=False): if filter_addable and not zmi_addable: return False try: inside_silva = interfaces.IRoot.providedBy(container.get_root()) except AttributeError: inside_silva = False if not inside_silva: # Outsite of Silva, you can only add a Silva Root. return interfaces.IRoot.implementedBy(content) if interfaces.IZMIObject.implementedBy(content): if interfaces.ISilvaLocalService.implementedBy(content): # Add local service in a site. return ISite.providedBy(container) # ZMIObject are addable, but not the non-local services # (they must be installed). return not interfaces.ISilvaService.implementedBy(content) if interfaces.IRoot.implementedBy(content): # Silva Root are not addable inside Silva. return False if interfaces.IContainer.providedBy(container): # In a Container, you can add content. return interfaces.ISilvaObject.implementedBy(content) if interfaces.IVersionedObject.providedBy(container): # In a Versioned object, you can add version. return interfaces.IVersion.implementedBy(content) return False
def findSite(container): """Return the nearest site. """ if ISite.providedBy(container): return container return findNextSite(container)
def silva_session_arg_generator(parent): root, options = parent.next() if not hasattr(options, 'paths') or not len(options.paths): fail(u"specifiy at least one Silva root path") for path in options.paths: try: silva = root.unrestrictedTraverse(path) except KeyError: fail("%s is not a valid Zope path" % path) if not IRoot.providedBy(silva): fail("%s is not a valid Silva root" % path) if ISite.providedBy(silva): setSite(silva) else: setSite(None) setHooks() if hasattr(options, 'username') and options.username: user = zope_find_user(silva, options.username) newSecurityManager(None, user) yield silva, options try: parent.next() except StopIteration: pass else: fail(u"internal error")
def test_enable_site(self): """Event handler should have configured local sitemanager.""" mnet = self.portal['maastricht'] self.assertTrue(ISite.providedBy(mnet)) self.assertTrue(IObjectManagerSite.providedBy(mnet)) self.assertNotEquals(self.portal.getSiteManager(), mnet.getSiteManager())
def validate(self, context): if context is self.startpoint: return False if ISite.providedBy(context): for obj in context.objectValues(): if IFilesService.providedBy(obj): raise StopIteration() return False
def activate(context): """Change the context to a local site. """ if not ISite.providedBy(context): create_new_sm(context) sm = context.getSiteManager() if IFiveSiteManager is not None and IFiveSiteManager.providedBy(sm): clean_old_five_sm(context, create=True) setup_intid(context)
def closest_short_url_service(location): # XXX Why not use getUtility ? while location: if ISite.providedBy(location): service = location._getOb(SERVICE_NAME, None) if service is not None and \ IShortURLService.providedBy(service): return service location = aq_parent(location) return None
def test_utility_only_in_local_site(self): # A service_customization can be added only in a local site. self.assertTrue(ISite.providedBy(self.root)) factory = self.root.manage_addProduct['Silva'] factory.manage_addPublication('publication', 'Publication') self.publication = self.root.publication self.assertFalse(ISite.providedBy(self.publication)) factory = self.publication.manage_addProduct['silva.core.layout'] self.assertRaises(BadRequest, factory.manage_addCustomizationService, 'service_customization') # Now our publication become a local site. make_objectmanager_site(self.publication) self.assertTrue(ISite.providedBy(self.publication)) factory = self.publication.manage_addProduct['silva.core.layout'] factory.manage_addCustomizationService('service_customization') self.assertTrue(hasattr(self.publication, 'service_customization'))
def find_next_sitemanager(site): """Find the closest sitemanager that is not the specified site's sitemanager. """ while True: site = get_parent(site, default=None) if site is None: return None if ISite.providedBy(site): return site.getSiteManager()
def upgrade(self, root): # If it's a Five site manager disable it first. The annoying # part might be that the code might already have been removed # from Zope ... setattr(root, '__initialization__', True) if ISite.providedBy(root): sm = root.getSiteManager() if ((IFiveSiteManager is not None and IFiveSiteManager.providedBy(sm)) or isinstance(sm, ZODB.broken.Broken)): setSite(None) setHooks() unregisterBeforeTraverse(aq_base(root), '__local_site_hook__') if hasattr(aq_base(root), '__local_site_hook__'): delattr(aq_base(root), '__local_site_hook__') zope.interface.noLongerProvides(root, ISite) root.setSiteManager(None) else: # Cleanup broken utilities for registration in list(sm.registeredUtilities()): if isinstance(registration.component, ZODB.broken.Broken): sm.unregisterUtility( registration.component, registration.provided) # Activate local site, add an intid service. ism = interfaces.ISiteManager(root) if not ism.is_site(): ism.make_site() setSite(root) setHooks() # Delete unused Silva Document service for s in ['service_doc_previewer', 'service_nlist_previewer', 'service_sub_previewer',]: if hasattr(root, s): root.manage_delObjects([s,]) # Update service_files settings service_files = root.service_files if hasattr(aq_base(service_files), '_filesystem_storage_enabled'): service_files.storage = BlobFile delattr(service_files , '_filesystem_storage_enabled') elif service_files.storage is not BlobFile: # For the upgrade service_files.storage = BlobFile # Disable quota verification (but not accounting if this # enabled) during the migration, so the file migration can # safely happens. root.service_extensions._quota_verify = False return root
def recursiveEventCrossbarSubscriber(obj): """distibution of eventcrossbar event """ if ISite.providedBy(obj): sitem = obj.getSiteManager() smList = list( sitem.getAllUtilitiesRegisteredFor(IAdmUtilEventCrossbar)) for utilObj in smList: if IAdmUtilEventCrossbar.providedBy(utilObj): globalEventCrossbarUtility.subscribeToEventCrossbar(utilObj) if IContainer.providedBy(obj): for (dummy_name, subObject) in obj.items(): recursiveEventCrossbarSubscriber(subObject)
def findNextSite(container): """Return the next site. """ while container: if IContainmentRoot.providedBy(container): return None try: container = get_parent(container) if container is None: return None except TypeError: return None if ISite.providedBy(container): return container
def recursiveCronSubscriber(obj): """distibution of cron event """ if ISite.providedBy(obj): sitem = obj.getSiteManager() #sitem = getSiteManager(obj) smList = list(sitem.getAllUtilitiesRegisteredFor(IAdmUtilCron)) for utilObj in smList: if IAdmUtilCron.providedBy(utilObj): globalCronUtility.subscribeToCron(utilObj) if IContainer.providedBy(obj): for (dummy_name, subObject) in obj.items(): recursiveCronSubscriber(subObject)
def publishTraverse(self, request, name): try: content = getUtility(IIntIds).queryObject(int(name)) except: raise NotFound(self.context, name, request) if not ISite.providedBy(self.context): request.response.redirect( '%s/%s/%s' % ( absoluteURL(getSite(), request), self.__name__, name)) return LocationProxy(content, self, name) if IAttachment.providedBy(content): return LocationProxy(content, self, name) raise NotFound(self.context, name, request)
def make_site(obj, iface=ISite): """Give the specified object required qualities to identify it as a proper ISite. """ if ISite.providedBy(obj): raise ValueError('This is already a site') next = find_next_sitemanager(obj) if next is None: next = base enableSite(obj, iface=iface) components = PersistentComponents('++etc++site', bases=(next,)) obj.setSiteManager(components) components.__parent__ = aq_base(obj)
def make_site(obj, iface=ISite): """Give the specified object required qualities to identify it as a proper ISite. """ if ISite.providedBy(obj): raise ValueError('This is already a site') next = find_next_sitemanager(obj) if next is None: next = base enableSite(obj, iface=iface) components = PersistentComponents('++etc++site', bases=(next, )) obj.setSiteManager(components) components.__parent__ = aq_base(obj)
def testSiteManagerSetup(self): clearSite() # The portal should be an ISite self.assertTrue(ISite.providedBy(self.portal)) # There should be a IComponentRegistry comp = IComponentLookup(self.portal) IComponentRegistry.providedBy(comp) # Test if we get the right site managers gsm = getGlobalSiteManager() sm = getSiteManager() # Without setting the site we should get the global site manager self.assertTrue(sm is gsm) # Now we set the site, as it is done in url traversal normally setSite(self.portal) # And should get the local site manager sm = getSiteManager() self.assertTrue(aq_base(sm) is aq_base(comp))
def addUtility(site, interface, klass, name='', ofs_name='', findroot=True): """ add local utility in zope2 """ app = site if findroot: app = get_root(site) # If we have the zope Application and the utility is not yet # registered, then register it. assert app is not None, TypeError("app is None") if not ISite.providedBy(app): initializeSite(app, sethook=False) sm = app.getSiteManager() obj = None # Try to get the utility from OFS directly in case it is # stored, but not registered ofs_name = ofs_name or name obj = getattr(aq_base(sm), ofs_name, None) if sm.queryUtility(interface, name=name, default=None) is None: # Register the utility if it is not yet registered if obj is None: if name: obj = klass(name) else: obj = klass() sm.registerUtility(provided=interface, component=obj, name=name) elif obj is None: # Get the utility if registered, but not yet stored in the LSM obj = sm.queryUtility(interface, name=name) # Make sure we store the utility permanently in the OFS so we don't loose # intids on uninstall if ofs_name and ofs_name not in sm.objectIds(): sm._setObject(ofs_name, aq_base(obj), set_owner=False, suppress_events=True)
def testEnableZope3Site(self): # First we remove the site and site manager self.disableSite(self.portal) clearSite(self.portal) self.portal.setSiteManager(None) gsm = getGlobalSiteManager() # Test it twice for i in range(2): enableZope3Site(self.portal) # And see if we have an ISite with a local site manager self.assertTrue(ISite.providedBy(self.portal)) sm = getSiteManager(self.portal) self.assertFalse(gsm is sm) lc = sm.utilities.LookupClass self.assertEqual(lc, FiveVerifyingAdapterLookup) # Test the lookupclass migration sm.utilities.LookupClass = None # Test it twice for i in range(2): enableZope3Site(self.portal) self.assertEqual(sm.utilities.LookupClass, FiveVerifyingAdapterLookup) self.assertEqual(sm.utilities.__parent__, sm) self.assertEqual(sm.__parent__, self.portal)
def _wrap(comp, registry): """Return an aq wrapped component with the site as the parent but only if the comp has an aq wrapper to begin with. """ # If component is stored as a ComponentPathWrapper, we traverse to # the component using the stored path: if isinstance(comp, ComponentPathWrapper): comp = getSite().unrestrictedTraverse(comp.path) if IAcquirer.providedBy(comp): return _rewrap(comp) else: return comp # BBB: The primary reason for doing this sort of wrapping of # returned utilities is to support CMF tool-like functionality where # a tool expects its aq_parent to be the portal object. New code # (ie new utilities) should not rely on this predictability to # get the portal object and should search out an alternate means # (possibly retrieve the ISiteRoot utility). Although in most # cases getting at the portal object shouldn't be the required pattern # but instead looking up required functionality via other (possibly # local) components. if registry.__bases__ and IAcquirer.providedBy(comp): current_site = getSite() registry_site = Acquisition.aq_base(registry.__parent__) if not ISite.providedBy(registry_site): registry_site = registry_site.__parent__ if current_site is None: # If no current site can be found, return utilities wrapped in # the site they where registered in. We loose the whole aq chain # here though current_site = Acquisition.aq_base(registry_site) parent = None if current_site == registry_site: parent = current_site else: parent = _recurse_to_site(current_site, registry_site) if parent is None: raise ValueError('Not enough context to acquire parent') base = Acquisition.aq_base(comp) # clean up aq_chain, removing REQUEST objects parent = _rewrap(parent) if base is not Acquisition.aq_base(parent): # If the component is not the component registry container, # wrap it in the parent comp = base.__of__(parent) else: # If the component happens to be the component registry # container we are looking up a ISiteRoot. # We are not wrapping it in itself but in its own parent site_parent = Acquisition.aq_parent(parent) if site_parent is None: raise ValueError('The ISiteRoot %s has no parent or the ' 'current site is not set correctly.' % repr(parent)) comp = base.__of__(site_parent) return comp
def is_site(self): return ISite.providedBy(self.context)
def closest_site(location): while location: if ISite.providedBy(location): return location location = aq_parent(location) return None
def install(context): portal = getToolByName(context, 'portal_url').getPortalObject() sm = ISite(portal).getSiteManager() add_local_mail_host_utility(portal, sm)
def testSiteManagerInstall(self): self.failUnless(ISite.providedBy(self.portal))
def test_portal_is_a_site(self): self.assert_(ISite.providedBy(self.portal))