def paragraphDirective(_context, targets, renderer=None, template=None, name="default", filtering = None, description=None, folderish=False, macro=None): cname = "Paragraph renderer %s" % name attrs = {} if template is not None: if macro is not None: attrs['index'] = ViewPageTemplateAndMacroFile(template) attrs['__renderer_macro__'] = macro else: attrs['index'] = ViewPageTemplateFile(template) attrs['__renderer_macro__'] = None if renderer is None: attrs['__doc__'] = description or u"default renderer" baseclasses = (ParagraphStructuredRenderer,) else: attrs['__doc__'] = description or renderer.__doc__ baseclasses = (renderer, ParagraphStructuredRenderer,) if folderish == True: baseclasses = baseclasses + (FolderishRenderer,) attrs['__name__'] = name klass = makeClass(cname, baseclasses, attrs) if filtering: klass._filtering = filtering for target in targets: adapter(_context, (klass,), provides = IParagraphRenderer, for_ = (target,IBrowserRequest), name = name, trusted=True)
def subMenuItem(self, _context, submenu, title, description=u'', action=u'', icon=None, filter=None, permission=None, extra=None, order=0, item_class=None): filter = Engine.compile(filter) if filter is not None else None if permission is None: permission = self.permission if order == 0: order = _order_counter.get(self.for_, 1) _order_counter[self.for_] = order + 1 if item_class is None: item_class = self.subMenuItemClass if not IBrowserSubMenuItem.implementedBy(item_class): raise ValueError("Item class (%s) must implement IBrowserSubMenuItem" % item_class) factory = MenuItemFactory( item_class, title=title, description=description, icon=icon, action=action, filter=filter, permission=permission, extra=extra, order=order, _for=self.for_, submenuId=submenu) adapter(_context, (factory,), self.menuItemType, (self.for_, self.layer), name=title)
def ttwResourceDirective( _context, name, title, for_ = interface.Interface, layer = IDefaultBrowserLayer, type = '', file = None, description=u'', **kwargs): rname = u'simplettw.%s'%name # register resource resourceDirective( _context, rname, file, layer, permission='zope.Public', type='') # Build a new class that we can use different permission settings if we # use the class more then once. cdict = {} cdict['name'] = name cdict['title'] = title cdict['description'] = description cdict['file'] = os.path.abspath(str(_context.path(file))) cdict['contentType'] = type newclass = Type( str('<TTWResourceFactory %s>'%name), (TTWResourceFactory,), cdict) # Set up permission mapping for various accessible attributes required = dict([(iname, CheckerPublic) for iname in ITTWResourceFactory]) defineChecker(newclass, Checker(required)) # register the resource element adapter(_context, (newclass,), ITTWItemFactory, (ISimpleTTW, layer), name=name) # register IStaticResource adapter adapter(_context, (StaticResource(rname),), IStaticResource, (layer,), name=name)
def ttwElementDirective( _context, name, title, for_ = interface.Interface, description=u'', layer = IDefaultBrowserLayer, template=u''): # register pageelement pageelementDirective( _context, name, for_=for_, title=title, description=description, layer=layer, template=template) # Make sure that the template exists template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) # Build a new class that we can use different permission settings if we # use the class more then once. cdict = {} cdict['name'] = name cdict['title'] = title cdict['description'] = description cdict['template'] = template newclass = type( str('<TTWResourceFactory %s>'%name), (TTWPageElementFactory,), cdict) # Set up permission mapping for various accessible attributes required = {} for iname in ITTWPageElementFactory: required[iname] = CheckerPublic # security checker defineChecker(newclass, Checker(required)) # register the page element adapter(_context, (newclass,), ITTWItemFactory, (for_, layer), name=name)
def pipeline(_context, for_, names): """Register a pipeline application list""" obj = PipelineApplicationList(names) adapter(_context, factory=(obj.adapt, ), provides=IPipelineApplicationList, for_=for_)
def _register_datasource(_context, name, json_source, site, title, description, select_label, select_description, setting_iface, adapter_factory, label_getter=lambda x,y:y['settingsdata']): json_data = simplejson.loads(open(json_source).read()) utility(_context, name=name, factory=lambda : json_data, provides=IGroupSource) utility_factory = type(str(name), (LookupRecipientSourceRegistration,), { 'name': name, 'title': title, 'description': description, 'site': site, 'settings_schema': setting_iface, 'get_label': label_getter }) utility(_context, name=name, factory=utility_factory) adapter(_context, factory=(adapter_factory,), for_=(IMegaphone, IBrowserRequest), provides=IRecipientSource, name=name)
def serviceDirective(_context, method, factory, for_, layer=None, cors_enabled=False, cors_origin=None): if method.upper() == "GET": marker = interfaces.IGET elif method.upper() == "POST": marker = interfaces.IPOST elif method.upper() == "OPTIONS": marker = interfaces.IOPTIONS elif method.upper() == "PUT": marker = interfaces.IPUT elif method.upper() == "DELETE": marker = interfaces.IDELETE elif method.upper() == "PATCH": marker = interfaces.IPATCH else: raise ConfigurationError(u"No implementation for %s method" % method) # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. # if factory is not None and ISchemaAwareFactory.providedBy(factory): # factory = factory(provides) # registration = ServiceRegistration( # title=title, # description=description, # interface=provides, # marker=marker, # factory=factory) # adapter_factory = ServiceAdapterFactory(registration) adapter(_context, factory=(factory,), provides=IBrowserPublisher, for_=(for_, marker))
def portletManagerDirective( _context, name, title, for_=None, description=u'', class_=None, schema=None, layer=IDefaultBrowserLayer, provides=(), portlettype=IPortlet, **kw): # Build a new class ManagerClass = PortletManager( name, class_, provides, title, description, schema, portlettype, **kw) # Set up permission mapping for various accessible attributes required = {'__call__': CheckerPublic, 'browserDefault': CheckerPublic, 'publishTraverse': CheckerPublic} for iname in IPortletManager: required[iname] = CheckerPublic # security checker defineChecker(ManagerClass, Checker(required)) # security for schema fields for iface in (IPortletManagerConfiguration, schema): if iface is None: continue for f_id in iface: field = iface[f_id] if IField.providedBy(field) and not field.readonly: protectSetAttribute(ManagerClass, f_id, 'zojax.ManagePortlets') protectName(ManagerClass, f_id, 'zope.Public') # register the portlet manager adapter(_context, (ManagerClass,), IPortletManager, (for_, layer, None), name=name)
def portletRendererDirective(_context, portlet, class_=None, template=None, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, manager=IPortletManager): """Register a custom/override portlet renderer """ if class_ is None and template is None: raise TypeError("Either 'template' or 'class' must be given") if class_ is not None and template is not None: raise TypeError( "'template' and 'class' cannot be specified at the same time") if template is not None: # Look up the default renderer for this portlet base_class = _default_renderers.get(portlet, None) if base_class is None: raise TypeError( "Can't find default renderer for %s. " "Perhaps the portlet has not been registered yet?" % portlet.__identifier__) # Generate a subclass with 'renderer' using this template class_ = type("PortletRenderer from %s" % template.encode('UTF-8'), (base_class, ), {'render': ViewPageTemplateFile(template)}) adapter(_context, (class_, ), provides=IPortletRenderer, for_=(for_, layer, view, manager, portlet))
def menus(_context, module, classes): """Handler for the `IMenusDirective`.""" if not inspect.ismodule(module): raise TypeError("module attribute must be a module: %s, %s" % module, type(module)) menutypes = [IFacetMenu, IApplicationMenu, IContextMenu, INavigationMenu] applicationmenutypes = [IApplicationMenu, INavigationMenu] for menuname in classes: menuclass = getattr(module, menuname) implemented = None for menutype in menutypes: if menutype.implementedBy(menuclass): assert implemented is None, ( 'The menu class %r implements more than one of %s' % (menuclass, menutypes)) provides = menutype name = '' if menutype in applicationmenutypes: name = getattr(menuclass, 'facet', None) if name is None: raise AssertionError( 'The menu %r needs a "facet" attribute' ' saying what facet it is to be used for.' % menuclass) break else: raise TypeError('class %r is not one of %s' % (menuclass, menutypes)) for_ = [menuclass.usedfor] factory = [menuclass] adapter(_context, factory, provides, for_, name=name, permission=PublicPermission)
def _register_datasource(_context, name, json_source, site, title, description, select_label, select_description, setting_iface, adapter_factory, label_getter=lambda x, y: y['settingsdata']): json_data = simplejson.loads(open(json_source).read()) utility(_context, name=name, factory=lambda: json_data, provides=IGroupSource) utility_factory = type( str(name), (LookupRecipientSourceRegistration, ), { 'name': name, 'title': title, 'description': description, 'site': site, 'settings_schema': setting_iface, 'get_label': label_getter }) utility(_context, name=name, factory=utility_factory) adapter(_context, factory=(adapter_factory, ), for_=(IMegaphone, IBrowserRequest), provides=IRecipientSource, name=name)
def subMenuItem(self, _context, submenu, title, description=u'', action=u'', icon=None, filter=None, permission=None, extra=None, order=0, item_class=None): if filter is not None: filter = Engine.compile(filter) if permission is None: permission = self.permission if order == 0: order = _order_counter.get(self.for_, 1) _order_counter[self.for_] = order + 1 if item_class is None: item_class = self.subMenuItemClass if not IBrowserSubMenuItem.implementedBy(item_class): raise ValueError("Item class (%s) must implement IBrowserSubMenuItem" % item_class) factory = MenuItemFactory( item_class, title=title, description=description, icon=icon, action=action, filter=filter, permission=permission, extra=extra, order=order, _for=self.for_, submenuId=submenu) adapter(_context, (factory,), self.menuItemType, (self.for_, self.layer), name=title)
def registerCommandSet(_context, for_, class_, name, provides): 'Directive that registers a command set' adapter(_context, [class_], provides, [for_]) _context.action( discriminator = ('registerKssCommandSet', name), callable = registerAndAllowCommandSet, args = (class_, name, provides), )
def registerMacroFactory(_context, path, name, macro, for_, view, layer, contentType): """Register a named macro factory adapter.""" factory = MacroFactory(path, macro, contentType) # register the macro zcml.adapter(_context, (factory,), interfaces.IMacroTemplate, (for_, view, layer), name=name)
def serviceDirective( _context, method, factory, for_, name=u'', cors_enabled=False, cors_origin=None, permission=CheckerPublic ): if method.upper() == 'GET': marker = interfaces.IGET elif method.upper() == 'POST': marker = interfaces.IPOST elif method.upper() == 'OPTIONS': marker = interfaces.IOPTIONS elif method.upper() == 'PUT': marker = interfaces.IPUT elif method.upper() == 'DELETE': marker = interfaces.IDELETE elif method.upper() == 'PATCH': marker = interfaces.IPATCH else: raise ConfigurationError( u"No implementation for %s method" % method ) required = {} if permission == 'zope.Public': permission = CheckerPublic for n in ('browserDefault', '__call__', 'publishTraverse'): required[n] = permission # defineChecker(factory, Checker(required)) if cors_enabled: # Check if there is already an adapter for options # Register adapter( _context, factory=(get_cors_preflight_view), provides=IBrowserPublisher, for_=(for_, interfaces.IOPTIONS), name=name, ) adapter( _context, factory=(factory,), provides=IBrowserPublisher, for_=(for_, marker), name=name, )
def application(_context, factory, name, for_=()): """Register a WSGI application""" if not for_: for_ = (IRequest, ) factory_factory = WSGIApplicationFactory(factory) adapter(_context, factory=(factory_factory.adapt, ), provides=IWSGIApplicationFactory, for_=for_, name=name)
def __init__(self, _context, id, schema, title, for_=None, description=u'', class_=None, provides=[], permission='zojax.ModifyPreference', accesspermission='', tests=(), order = 9999): if not accesspermission: accesspermission = permission if permission == 'zope.Public': permission = CheckerPublic if accesspermission == 'zope.Public': accesspermission = CheckerPublic Class = PreferenceType(str(id), schema, class_, title, description) Class.order = order Class.__permission__ = permission Class.__accesspermission__ = accesspermission tests = tuple(tests) if permission != CheckerPublic: tests = tests + (PermissionChecker,) if interface.interfaces.IInterface.providedBy(for_): tests = tests + (PrincipalChecker(for_),) group = Class(tests) utility(_context, IPreferenceGroup, group, name=id) adapter(_context, (PreferenceGroupAdapter(id),), schema, (for_ or IPrincipal,)) adapter(_context, (PreferenceGroupAdapter(id),), schema, (for_ or IPrincipal, interface.Interface)) interface.classImplements(Class, *provides) self._class = Class self._context = _context self._permission = permission self.require(_context, permission, set_schema=(schema,)) self.require(_context, accesspermission, interface=(IPreferenceGroup, schema)) self.require(_context, CheckerPublic, interface=(IEnumerableMapping, ILocation), attributes=('isAvailable', '__id__', '__schema__', '__title__', '__description__', '__permission__')) schema.setTaggedValue('preferenceID', id) _context.action( discriminator=('zojax:preferences', schema), callable=addSubgroup, args=(group,))
def behaviorDirective(_context, title, provides, description=None, marker=None, factory=None, for_=None): if marker is None and factory is None: marker = provides if factory is None and marker is not None and marker is not provides: raise ConfigurationError( u"You cannot specify a different 'marker' and 'provides' if " u"there is no adapter factory for the provided interface." ) # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. if factory is not None and ISchemaAwareFactory.providedBy(factory): factory = factory(provides) # Attempt to guess the factory's adapted interface and use it as the for_ if for_ is None and factory is not None: adapts = getattr(factory, '__component_adapts__', None) if adapts: if len(adapts) != 1: raise ConfigurationError( u"The factory cannot be declared a multi-adapter." ) for_ = adapts[0] else: for_ = Interface elif for_ is None: for_ = Interface registration = BehaviorRegistration( title=title, description=description, interface=provides, marker=marker, factory=factory ) adapter_factory = BehaviorAdapterFactory(registration) utility( _context, provides=IBehavior, name=provides.__identifier__, component=registration ) if factory is not None: adapter( _context, factory=(adapter_factory,), provides=provides, for_=(for_,) )
def __init__(self, _context, name, schema, title, for_ = interface.Interface, description = u'', class_=None, layer = None, permission = 'zojax.ManageExtension', tests=(), type=IDefaultExtensionType): for test in tests: if not callable(test): raise ConfigurationError('Test should be callable.') # permission checker if permission == 'zope.Public': tests = tuple(tests) else: tests = (PermissionChecker(permission),) + tuple(tests) # generate class ExtensionClass = ExtensionType( name, schema, class_, title, description, tests=tests, layer=layer) interface.classImplements(ExtensionClass, schema) # register adater if layer: factory = ExtensionClass adapter(_context, (factory,), IExtension, (for_, layer), name=name) adapter(_context, (factory,), schema, (for_, layer), name='extension') adapter(_context, (Wrapper(factory),), schema, (for_, layer, ExtensionMarker)) else: factory = ExtensionClass adapter(_context, (factory,), schema, (for_,)) adapter(_context, (factory,), IExtension, (for_,), name=name) # extension type if type is not None: interface.classImplements(ExtensionClass, type) # save data for subdirectives self._class = ExtensionClass self._context = _context self._permission = permission # set default security rules self.require(_context, permission, interface=(schema,), set_schema=(schema,)) # allow access to IExtension interface if layer: self.require(_context, CheckerPublic, interface=(IBrowserExtension,)) else: self.require(_context, CheckerPublic, interface=(IExtension,))
def menuSelectorDirective( _context, factory=checker.TrueSelectedChecker, for_=zope.interface.Interface, layer=IBrowserRequest, view=IBrowserView, manager=interfaces.IMenuManager, menu=interfaces.IMenuItem): # Security map dictionary objs = (for_, layer, view, manager ,menu) factory = (factory,) zcml.adapter(_context, factory, provides=interfaces.ISelectedChecker, for_=objs, permission=None, name='', trusted=False, locate=False)
def load_adapter(_context, adapter): conf = adapter['config'] klass = resolve_or_get(adapter['klass']) factory = conf.pop('factory', None) or klass _component_conf(conf) if 'provides' in conf and isinstance(klass, type): # not sure if this is what we want or not for sure but # we are automatically applying the provides interface to # registered class objects classImplements(klass, conf['provides']) zcml.adapter(_context, factory=(factory, ), **conf)
def behaviorDirective(_context, title, provides, description=None, marker=None, factory=None, for_=None): if marker is None and factory is None: marker = provides if factory is None and marker is not None and marker is not provides: raise ConfigurationError( u"You cannot specify a different 'marker' and 'provides' if " u"there is no adapter factory for the provided interface.") # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. if factory is not None and ISchemaAwareFactory.providedBy(factory): factory = factory(provides) # Attempt to guess the factory's adapted interface and use it as the for_ if for_ is None and factory is not None: adapts = getattr(factory, '__component_adapts__', None) if adapts: if len(adapts) != 1: raise ConfigurationError( u"The factory cannot be declared a multi-adapter.") for_ = adapts[0] else: for_ = Interface elif for_ is None: for_ = Interface registration = BehaviorRegistration(title=title, description=description, interface=provides, marker=marker, factory=factory) adapter_factory = BehaviorAdapterFactory(registration) utility(_context, provides=IBehavior, name=provides.__identifier__, component=registration) if factory is not None: adapter(_context, factory=(adapter_factory, ), provides=provides, for_=(for_, ))
def authorizations(_context, module): if not inspect.ismodule(module): raise TypeError("module attribute must be a module: %s, %s" % module, type(module)) provides = IAuthorization for nameinmodule, authorization in inspect.getmembers( module, _isAuthorization): if (authorization.permission is not None and authorization.usedfor is not None): name = authorization.permission for_ = [authorization.usedfor] factory = [authorization] adapter(_context, factory, provides, for_, name=name)
def authorizations(_context, module): if not inspect.ismodule(module): raise TypeError("module attribute must be a module: %s, %s" % module, type(module)) provides = IAuthorization for nameinmodule, authorization in inspect.getmembers(module, _isAuthorization): if (authorization.permission is not None and authorization.usedfor is not None): name = authorization.permission for_ = [authorization.usedfor] factory = [authorization] adapter(_context, factory, provides, for_, name=name)
def url(_context, for_, path_expression=None, urldata=None, attribute_to_parent=None, parent_utility=None, rootsite=None): """browser:url directive handler.""" if (not attribute_to_parent and not parent_utility and not urldata): raise TypeError( 'Must provide attribute_to_parent, urldata or parent_utility.') if attribute_to_parent: if attribute_to_parent not in for_: raise AttributeError( 'The name "%s" is not in %s.%s' % (attribute_to_parent, for_.__module__, for_.__name__)) if path_expression is not None: compiled_path_expression = TrustedEngine.compile(path_expression) # Dead chicken for the namespace gods. rootsite_ = rootsite if urldata: CanonicalUrlData = urldata elif attribute_to_parent: class CanonicalUrlData(CanonicalUrlDataBase): _for = for_ _compiled_path_expression = compiled_path_expression rootsite = rootsite_ @property def inside(self): return getattr(self.context, attribute_to_parent) else: class CanonicalUrlData(CanonicalUrlDataBase): _for = for_ _compiled_path_expression = compiled_path_expression rootsite = rootsite_ @property def inside(self): return getUtility(parent_utility) factory = [CanonicalUrlData] provides = ICanonicalUrlData adapter(_context, factory, provides, [for_])
def templateDirective(_context, template, macro=None, for_=interface.Interface, layer=IDefaultBrowserLayer, contentType='text/html', ): # Make sure that the template exists template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) factory = TemplateFactory(template, macro, contentType) # register the template zcml.adapter(_context, (factory,), IPageTemplate, (for_, layer))
def load_adapter(_context, adapter): conf = adapter['config'] klass = resolve_or_get(adapter['klass']) factory = conf.pop('factory', None) or klass _component_conf(conf) if 'provides' in conf and isinstance(klass, type): # not sure if this is what we want or not for sure but # we are automatically applying the provides interface to # registered class objects classImplements(klass, conf['provides']) zcml.adapter( _context, factory=(factory,), **conf )
def registerComponent(_context, name, component, viewlet, manager, selection=None, image=None, permission="zope.Public"): """ Register a component to be used by articles """ adapter(_context, [component], interfaces.IComponent, name=name, for_=[interfaces.IArticle]) if selection: adapter(_context, [component], interfaces.IComponentSelection, name=name, for_=[selection]) viewletDirective(_context, component.viewlet, permission, for_=component.interface, manager=manager, class_=viewlet, view=interfaces.IArticleView) if not image: path = os.path.abspath(str(_context.path(component.image.replace('++resource++', '')))) if os.path.isfile(path): image = path if image: resource(_context, component.image.replace('++resource++', ''), image=image)
def behaviorDirective(_context, title, provides, name=None, description=None, marker=None, factory=None, for_=None): if marker is None and factory is None: marker = provides if marker is not None and factory is None and marker is not provides: raise ConfigurationError( u"You cannot specify a different 'marker' and 'provides' if " u"there is no adapter factory for the provided interface." ) # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. if factory is not None and ISchemaAwareFactory.providedBy(factory): factory = factory(provides) registration = BehaviorRegistration( title=title, description=description, interface=provides, marker=marker, factory=factory, name=name ) # behavior registration by provides interface identifier utility(_context, provides=IBehavior, name=provides.__identifier__, component=registration) if name is not None: # for convinience we register with a given name utility(_context, provides=IBehavior, name=name, component=registration) if factory is None: if for_ is not None: logger.warn( u"Specifying 'for' in behavior '{0}' if no 'factory' is given " u"has no effect and is superfluous.".format(title) ) # w/o factory we're done here return if for_ is None: # Attempt to guess the factory's adapted interface and use it as # the 'for_'. # Fallback to '*' (=Interface). adapts = getattr(factory, "__component_adapts__", None) or [Interface] if len(adapts) != 1: raise ConfigurationError(u"The factory can not be declared as multi-adapter.") for_ = adapts[0] adapter_factory = BehaviorAdapterFactory(registration) adapter(_context, factory=(adapter_factory,), provides=provides, for_=(for_,))
def contentPermissionHandler( _context, permission, category, managepermission, for_=None, class_=None, provides=(), **kwargs): if permission == 'zope.Public': raise ConfigurationError('zope.Public permission is not allowed.') provides = list(provides) provides.append(category) PermissionClass = PermissionType( permission, category, managepermission, class_, provides) # set default values for iface in provides: verifyClass(iface, PermissionClass) for fname, field in schema.getFields(iface).items(): if fname in kwargs: if not IFromUnicode.providedBy(field): raise ConfigurationError("Can't convert value", fname) setattr(PermissionClass, fname, field.fromUnicode(kwargs[fname])) else: if field.required and not hasattr(PermissionClass, fname): raise ConfigurationError("Required field is missing", fname) if not hasattr(PermissionClass, fname): setattr(PermissionClass, fname, field.default) # set up permissions required = {} for iface in provides + [IContentPermission]: for iname in iface: required[iname] = managepermission defineChecker(PermissionClass, Checker(required)) # register adapters adapter(_context, (PermissionClass,), category, (for_,), name=permission) adapter(_context, (PermissionClass,), IContentPermission, (for_,), name=permission)
def url(_context, for_, path_expression=None, urldata=None, attribute_to_parent=None, parent_utility=None, rootsite=None): """browser:url directive handler.""" if (not attribute_to_parent and not parent_utility and not urldata): raise TypeError( 'Must provide attribute_to_parent, urldata or parent_utility.') if attribute_to_parent: if attribute_to_parent not in for_: raise AttributeError('The name "%s" is not in %s.%s' % (attribute_to_parent, for_.__module__, for_.__name__)) if path_expression is not None: compiled_path_expression = TrustedEngine.compile(path_expression) # Dead chicken for the namespace gods. rootsite_ = rootsite if urldata: CanonicalUrlData = urldata elif attribute_to_parent: class CanonicalUrlData(CanonicalUrlDataBase): _for = for_ _compiled_path_expression = compiled_path_expression rootsite = rootsite_ @property def inside(self): return getattr(self.context, attribute_to_parent) else: class CanonicalUrlData(CanonicalUrlDataBase): _for = for_ _compiled_path_expression = compiled_path_expression rootsite = rootsite_ @property def inside(self): return getUtility(parent_utility) factory = [CanonicalUrlData] provides = ICanonicalUrlData adapter(_context, factory, provides, [for_])
def portletDirective( _context, name, title, for_=None, template=u'', description=u'', class_=None, provides=IPortlet, schema=None, type=IPortlet, manager=None, **kw): # Make sure that the template exists if template: template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) # Build a new class. PortletClass = Portlet( name, class_, title, description, template, schema, **kw) if provides is not IPortlet: interface.classImplements(PortletClass, provides) # Set up permission mapping for various accessible attributes required = {'__call__': CheckerPublic, 'browserDefault': CheckerPublic, 'publishTraverse': CheckerPublic} for iface in (IPortlet, provides): for iname in iface: required[iname] = CheckerPublic # security checker defineChecker(PortletClass, Checker(required)) # portlet schema if schema is not None: # security for configuration for f_id in schema: field = schema[f_id] if IField.providedBy(field) and not field.readonly: protectSetAttribute(PortletClass, f_id, 'zojax.ManagePortlets') protectName(PortletClass, f_id, CheckerPublic) # register the portlet adapter(_context, (PortletClass,), type, (for_, None, manager, None), name=name)
def register_service(_context, configuration, content, method, layer, default_permission, name=''): logger.debug(configuration) factory = configuration['factory'] if isinstance(factory, str): factory = import_class(factory) if factory is None: raise TypeError('Factory not defined {0:s} '.format( configuration['factory'])) if getCheckerForInstancesOf(factory): # in case already exist remove old checker undefineChecker(factory) if 'permission' in configuration: permission = configuration['permission'] else: permission = default_permission required = {} for n in ('__call__', 'publishTraverse'): required[n] = permission # prevent circular import from plone.server.security import ViewPermissionChecker from plone.server import app_settings defineChecker(factory, ViewPermissionChecker(required)) logger.debug('Defining adapter for ' # noqa '{0:s} {1:s} {2:s} to {3:s} name {4:s}'.format( content.__identifier__, app_settings['http_methods'][method].__identifier__, layer.__identifier__, str(factory), name)) adapter(_context, factory=(factory, ), provides=app_settings['http_methods'][method], for_=(content, layer), name=name)
def mirror(_context, content, serializer=None, transformer=None): if not interfaces.IMirrored.implementedBy(content): interface.classImplements(content, interfaces.IMirrored) if serializer: zcml.adapter(_context, (serializer,), interfaces.ISerializer, (content,)) if transformer: zcml.adapter(_context, (transformer,), interfaces.ISchemaTransformer, (content, interfaces.IMetaData)) _context.action( discriminator = (content, interfaces.IMirrored), callable = loader.load, args = (content,))
def register_service(_context, configuration, content, method, layer, default_permission, name=''): logger.debug(configuration) factory = configuration['factory'] if isinstance(factory, str): factory = import_class(factory) if factory is None: raise TypeError( 'Factory not defined {0:s} '.format(configuration['factory'])) if getCheckerForInstancesOf(factory): # in case already exist remove old checker undefineChecker(factory) if 'permission' in configuration: permission = configuration['permission'] else: permission = default_permission required = {} for n in ('__call__', 'publishTraverse'): required[n] = permission # prevent circular import from plone.server.auth.checker import ViewPermissionChecker from plone.server import app_settings defineChecker(factory, ViewPermissionChecker(required)) logger.debug('Defining adapter for ' # noqa '{0:s} {1:s} {2:s} to {3:s} name {4:s}'.format( content.__identifier__, app_settings['http_methods'][method].__identifier__, layer.__identifier__, str(factory), name)) adapter( _context, factory=(factory,), provides=app_settings['http_methods'][method], for_=(content, layer), name=name )
def GenerateCollectionTraversal( ctx ): collection_names = [] for k,v in ctx.domain_model.__dict__.items(): if IManagedContainer.providedBy( v ): collection_names.append( k ) if not collection_names: return traverser = CollectionTraverser( *collection_names ) # register collection traversal subscription adapter subscriber( ctx.zcml, for_=(ctx.domain_interface, IPublisherRequest ), factory=traverser, provides=ITraverserPlugin ) adapter( ctx.zcml, for_ = ( ctx.domain_interface, IPublisherRequest ), factory = (PluggableTraverser,), provides = IPublishTraverse )
def portletRendererDirective(_context, portlet, class_=None, template=None, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, manager=IPortletManager): """Register a custom/override portlet renderer """ if class_ is None and template is None: raise TypeError("Either 'template' or 'class' must be given") if class_ is not None and template is not None: raise TypeError("'template' and 'class' cannot be specified at the same time") if template is not None: # Look up the default renderer for this portlet base_class = _default_renderers.get(portlet, None) if base_class is None: raise TypeError("Can't find default renderer for %s. " "Perhaps the portlet has not been registered yet?" % portlet.__identifier__) # Generate a subclass with 'renderer' using this template class_ = type("PortletRenderer from %s" % template.encode('UTF-8'), (base_class, ), {'render': ViewPageTemplateFile(template)}) adapter(_context, (class_, ), provides=IPortletRenderer, for_=(for_, layer, view, manager, portlet))
def WidgetDirective(_context, factory=None, schema=None, accessor=WidgetData, criterion=ICriterion, **kwargs): """ Register faceted widgets """ if not factory: raise TypeError("No factory provided") name = getattr(factory, 'widget_type', None) if not name: raise TypeError( "Invalid factory: widget_type property is empty or not defined") WidgetsInfo._widgets[name] = factory if schema is None: raise TypeError("No schema provided for faceted widget type '%s'" % name) WidgetsInfo._schemas[name] = schema adapter(_context=_context, provides=schema, factory=(accessor, ), for_=(criterion, )) # # Ensure custom Faceted Navigation widgets were upgraded # edit_schema = getattr(factory, 'edit_schema', None) if edit_schema is not None: warnings.warn( "'edit_schema' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s" % name, DeprecationWarning) view_schema = getattr(factory, 'view_schema', None) if view_schema is not None: warnings.warn( "'view_schema' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s" % name, DeprecationWarning) view_css = getattr(factory, 'view_css', None) if view_css is not None: warnings.warn( "'view_css' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/cssregistry,xml" % name, DeprecationWarning) edit_css = getattr(factory, 'edit_css', None) if edit_css is not None: warnings.warn( "'edit_css' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/cssregistry,xml" % name, DeprecationWarning) view_js = getattr(factory, 'view_js', None) if view_js is not None: warnings.warn( "'view_js' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/jsregistry,xml" % name, DeprecationWarning) edit_js = getattr(factory, 'edit_js', None) if edit_js is not None: warnings.warn( "'edit_js' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/jsregistry,xml" % name, DeprecationWarning)
def _callFUT(self, *args, **kw): from zope.component.zcml import adapter return adapter(*args, **kw)
def portletDirective(_context, name, interface, assignment, renderer, addview, view_permission=u"zope2.View", edit_permission="plone.app.portlets.ManageOwnPortlets", editview=None): """Register a portlet assignment type using typical options. Portlets that consist of a simple assignment class deriving form base.Assignment, a renderer deriving from base.Renderer, an addview using formlib and deriving from base.AddForm and an editview (optional) using formlib and deriving from base.EditForm, can use this directive to avoid having to regiter each of those components individually. In addition, we register the portlet interface using IPortletTypeInterface and an IFactory utility, in order to help the GenericSetup handler and other generic code instantiate portlets. """ name = str(name) # De-unicode # Register the portlet interface as named utility so that we can find it # again (in the GS handler) alsoProvides(interface, IPortletTypeInterface) utility(_context, provides=IPortletTypeInterface, name=name, component=interface) # Register a factory utility(_context, provides=IFactory, name=name, component=Factory(assignment)) # Set permissions on the assignment class # <class class="[assignment]"> # <require # permission="[view_permission]" # interface="[interface]" # /> # </class> # XXX: Is this necessary? The renderer doesn't need it, so it may # just be superfluous. # Register the renderer: # <adapter # factory="[renderer]" # for="zope.interface.Interface # zope.publisher.interfaces.browser.IDefaultBrowserLayer # zope.publisher.interfaces.browser.IBrowserView # plone.portlets.interfaces.IPortletManager # [interface] # provides="plone.portlets.interfaces.IPortletRenderer" # /> adapter(_context, (renderer, ), provides=IPortletRenderer, for_=(Interface, IDefaultBrowserLayer, IBrowserView, IPortletManager, interface)) _default_renderers[interface] = renderer # Register the adding view # <browser:page # for="plone.app.portlets.browser.interfaces.IPortletAdding" # name="[name]" # class="[addview]" # permission="[edit_permission]" # /> page(_context, for_=IPortletAdding, name=name, class_=addview, permission=edit_permission) # Register the edit view, if applicable # <browser:page # for="[interface]" # name="edit" # class="[editview]" # permission="[edit_permission]" # /> if editview is not None: page(_context, for_=interface, name="edit", class_=editview, permission=edit_permission)
def autoPackageExternalization(_context, root_interfaces, modules, factory_modules=None, iobase=None, register_legacy_search_module=False): # TODO: Simplify this method; refactor inta parts # pylint:disable=too-many-locals ext_module_name = root_interfaces[0].__module__ package_name = ext_module_name.rsplit('.', 1)[0] root_interfaces = frozenset(root_interfaces) @classmethod def _ap_enumerate_externalizable_root_interfaces(_cls, unused_ifaces): return root_interfaces module_names = frozenset([m.__name__.split('.')[-1] for m in modules]) @classmethod def _ap_enumerate_module_names(_cls): return module_names @classmethod def _ap_find_package_name(_cls): return package_name # Items in a class dict and its name need to be native strings # under both py2 and py3 cls_dict = { '_ap_find_package_name': _ap_find_package_name, '_ap_enumerate_module_names': _ap_enumerate_module_names, '_ap_enumerate_externalizable_root_interfaces': _ap_enumerate_externalizable_root_interfaces } bases = (AutoPackageSearchingScopedInterfaceObjectIO, ) if iobase: bases = (iobase, ) + bases cls_iio = type('AutoPackageSearchingScopedInterfaceObjectIO', bases, cls_dict) # If we don't set the __module__, it defaults to this module, # which would be very confusing. cls_iio.__module__ = _context.package.__name__ if _context.package else '__dynamic__' for iface in root_interfaces: logger.log(loglevels.TRACE, "Registering ObjectIO for %s as %s", iface, cls_iio) component_zcml.adapter(_context, factory=(cls_iio, ), for_=(iface, )) # Now init the class so that it can add the things that internalization # needs. # Unfortunately, we are doing this eagerly instead of when the # configuration executes its actions runs because it must be done # before ``registerMimeFactories`` is invoked in order to add the # mimeType fields if they are missing. If we deferred it, we would # have to defer registerMimeFactories---and one action cannot # invoke another action or add more actions to the list and still # have any conflicts detected. Using the `order` parameter doesn't help us # much with that, either. # The plus side is that now that we are using component_zcml.utility() # to register legacy class factories too, there's not much harm in # initing the class early. legacy_factories = cls_iio.__class_init__() # Now that it's initted, register the factories for module in (factory_modules or modules): logger.log(loglevels.TRACE, "Examining module %s for mime factories", module) registerMimeFactories(_context, module) if register_legacy_search_module: for name, factory in find_factories_in_module(legacy_factories): component_zcml.utility(_context, provides=_ILegacySearchModuleFactory, component=factory, name=name)
def WidgetDirective(_context, factory=None, schema=None, accessor=WidgetData, criterion=ICriterion, **kwargs): """ Register faceted widgets """ if not factory: raise TypeError("No factory provided") name = getattr(factory, 'widget_type', None) if not name: raise TypeError( "Invalid factory: widget_type property is empty or not defined") WidgetsInfo._widgets[name] = factory if schema is None: raise TypeError( "No schema provided for faceted widget type '%s'" % name) WidgetsInfo._schemas[name] = schema adapter( _context=_context, provides=schema, factory=(accessor,), for_=(criterion,) ) # # Ensure custom Faceted Navigation widgets were upgraded # edit_schema = getattr(factory, 'edit_schema', None) if edit_schema is not None: warnings.warn( "'edit_schema' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s" % name, DeprecationWarning) view_schema = getattr(factory, 'view_schema', None) if view_schema is not None: warnings.warn( "'view_schema' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s" % name, DeprecationWarning) view_css = getattr(factory, 'view_css', None) if view_css is not None: warnings.warn( "'view_css' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/cssregistry,xml" % name, DeprecationWarning) edit_css = getattr(factory, 'edit_css', None) if edit_css is not None: warnings.warn( "'edit_css' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/cssregistry,xml" % name, DeprecationWarning) view_js = getattr(factory, 'view_js', None) if view_js is not None: warnings.warn( "'view_js' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/jsregistry,xml" % name, DeprecationWarning) edit_js = getattr(factory, 'edit_js', None) if edit_js is not None: warnings.warn( "'edit_js' attribute is deprecated. " "Please remove it from your custom Faceted Widget: %s " "and register it within registry.xml/jsregistry,xml" % name, DeprecationWarning)
def behaviorDirective(_context, title, provides, name=None, description=None, marker=None, factory=None, for_=None, name_only=False): if marker is None and factory is None: # a schema only behavior means usually direct attribute settings on the # object itself, so the object itself provides the interface. # so we mark with the provides. marker = provides if marker is not None and factory is None and marker is not provides: raise ConfigurationError( u'You cannot specify a different \'marker\' and \'provides\' if ' u'there is no adapter factory for the provided interface.') if name_only and name is None: raise ConfigurationError( u'If you decide to only register by \'name\', a name must ' u'be given.') # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. if factory is not None and ISchemaAwareFactory.providedBy(factory): factory = factory(provides) # the behavior registration hold all information about the behavior. registration = BehaviorRegistration( title=title, description=description, interface=provides, marker=marker, factory=factory, name=name, ) # the behavior registration can be looked up as a named utility. # the name of the utility is either the full dotted path of the interface # it provides... if not name_only: # behavior registration by provides interface identifier utility(_context, provides=IBehavior, name=provides.__identifier__, component=registration) if name is not None: # .. or if given, we register with a given (short) name. # Advantage is, we can have more than one implementations of a # behavior on one object (if a factory is used). # This is handy for certain use cases. utility(_context, provides=IBehavior, name=name, component=registration) if factory is None: if for_ is not None: logger.warn( u'Specifying \'for\' in behavior \'{0}\' if no \'factory\' is ' u'given has no effect and is superfluous.'.format(title)) # w/o factory we're done here: schema only behavior return if for_ is None: for_ = _detect_for(factory, marker) adapter_factory = BehaviorAdapterFactory(registration) adapter(_context, factory=(adapter_factory, ), provides=provides, for_=(for_, ))
def portletDirective(_context, name, interface, assignment, renderer, addview, view_permission=u"zope2.View", edit_permission="plone.app.portlets.ManageOwnPortlets", editview=None): """Register a portlet assignment type using typical options. Portlets that consist of a simple assignment class deriving form base.Assignment, a renderer deriving from base.Renderer, an addview using z3c form and deriving from base.AddForm and an editview (optional) using z3c form and deriving from base.EditForm, can use this directive to avoid having to regiter each of those components individually. In addition, we register the portlet interface using IPortletTypeInterface and an IFactory utility, in order to help the GenericSetup handler and other generic code instantiate portlets. """ name = str(name) # De-unicode # Register the portlet interface as named utility so that we can find it # again (in the GS handler) alsoProvides(interface, IPortletTypeInterface) utility(_context, provides=IPortletTypeInterface, name=name, component=interface) # Register a factory utility(_context, provides=IFactory, name=name, component=Factory(assignment)) # Set permissions on the assignment class # <class class="[assignment]"> # <require # permission="[view_permission]" # interface="[interface]" # /> # </class> # XXX: Is this necessary? The renderer doesn't need it, so it may # just be superfluous. # Register the renderer: # <adapter # factory="[renderer]" # for="zope.interface.Interface # zope.publisher.interfaces.browser.IDefaultBrowserLayer # zope.publisher.interfaces.browser.IBrowserView # plone.portlets.interfaces.IPortletManager # [interface] # provides="plone.portlets.interfaces.IPortletRenderer" # /> adapter(_context, (renderer, ), provides=IPortletRenderer, for_=(Interface, IDefaultBrowserLayer, IBrowserView, IPortletManager, interface)) _default_renderers[interface] = renderer # Register the adding view # <browser:page # for="plone.app.portlets.browser.interfaces.IPortletAdding" # name="[name]" # class="[addview]" # permission="[edit_permission]" # /> page(_context, for_=IPortletAdding, name=name, class_=addview, permission=edit_permission) # Register the edit view, if applicable # <browser:page # for="[interface]" # name="edit" # class="[editview]" # permission="[edit_permission]" # /> if editview is not None: page(_context, for_=interface, name="edit", class_=editview, permission=edit_permission)
def contentHandler(_context, schema, name, title, class_=None, description='', permission='zope.View', contenttype=None, ctclass=None, type=[], contains=(), containers=(), addform=None): if class_ is None: type = type + [IInactiveType,] if IInactiveType in type and IActiveType in type: type.remove(IActiveType) # make content type Active if no type is set if not type: type.append(IActiveType) for tp in type: if tp.isOrExtends(IContentType): raise ValueError( 'Content type type can not extend IContentType interface.', tp) # check schema if class_ is not None and not schema.implementedBy(class_): raise ValueError( 'Content class should implement content schema.', class_, schema) # create content type if ctclass is not None: if not IContentType.implementedBy(ctclass): raise ValueError('Custom content type implementation '\ 'should implement IContentType interface.') ct_factory = ctclass else: ct_factory = ContentType ct = ct_factory( name, schema, class_, title, description, permission, addform) # set types interface.alsoProvides(ct, type) for tp in type: utility(_context, tp, ct, name=name) # create unique interface for content type if contenttype is None: iname = name for ch in ('.', '-'): iname = iname.replace(ch, '_') contenttype = InterfaceClass(iname, (IContentType,), __doc__='Content Type: %s' %name, __module__='zojax.content') # Add the content type to the `zojax.content` module. setattr(zojax.content, iname, contenttype) # register content type as utility utility(_context, contenttype, ct) # create named utility for content type utility(_context, IContentType, ct, name=name) # adapter that return IContentType object from class instances adapter(_context, (ClassToTypeAdapter(name),), IContentType, (schema,)) if class_ is not None: clsifaces = list(interface.implementedBy(class_)) if not IContent.implementedBy(class_): clsifaces.append(IContent) clsifaces.extend(type) interface.classImplements(class_, clsifaces) # process constraints _context.action( discriminator = ('zojax.content:contentTypeConstraints', name), callable = contentTypeConstraints, args = (name, contains, containers, _context), order = 999998) # added custom interface to contenttype object _context.action( discriminator = ('zojax.content:contenttypeInterface', contenttype), callable = contenttypeInterface, args = (ct, contenttype))
def behaviorDirective(_context, title, provides, name=None, description=None, marker=None, factory=None, for_=None): if marker is None and factory is None: marker = provides if marker is not None and factory is None and marker is not provides: raise ConfigurationError( u"You cannot specify a different 'marker' and 'provides' if " u"there is no adapter factory for the provided interface.") # Instantiate the real factory if it's the schema-aware type. We do # this here so that the for_ interface may take this into account. if factory is not None and ISchemaAwareFactory.providedBy(factory): factory = factory(provides) registration = BehaviorRegistration( title=title, description=description, interface=provides, marker=marker, factory=factory, name=name, ) # behavior registration by provides interface identifier utility(_context, provides=IBehavior, name=provides.__identifier__, component=registration) if name is not None: # for convinience we register with a given name utility(_context, provides=IBehavior, name=name, component=registration) if factory is None: if for_ is not None: logger.warn( u"Specifying 'for' in behavior '{0}' if no 'factory' is given " u"has no effect and is superfluous.".format(title)) # w/o factory we're done here return if for_ is None: # Attempt to guess the factory's adapted interface and use it as # the 'for_'. # Fallback to '*' (=Interface). adapts = getattr(factory, '__component_adapts__', None) or [Interface] if len(adapts) != 1: raise ConfigurationError( u"The factory can not be declared as multi-adapter.") for_ = adapts[0] adapter_factory = BehaviorAdapterFactory(registration) adapter(_context, factory=(adapter_factory, ), provides=provides, for_=(for_, ))