Esempio n. 1
0
def tile(_context, name,
            title=None, description=None, add_permission=None, schema=None,
            for_=None, layer=None, class_=None, template=None, permission=None):
    """Implements the <plone:tile /> directive
    """
    
    if title is not None or description is not None or add_permission is not None or schema is not None:
        if title is None or add_permission is None:
            raise ConfigurationError(u"When configuring a new type of tile, 'title' and 'add_permission' are required")
    
        type_ = TileType(name, title, add_permission, description, schema)
        
        utility(_context, provides=ITileType, component=type_, name=name)
    
    if for_ is not None or layer is not None or class_ is not None or template is not None or permission is not None:
        if class_ is None and template is None:
            raise ConfigurationError(u"When configuring a tile, 'class' or 'template' must be given.")
        if permission is None:
            raise ConfigurationError(u"When configuring a tile, 'permission' is required")
        
        if for_ is None:
            for_ = Interface
        if layer is None:
            layer = IDefaultBrowserLayer
        
        if class_ is None:
            class_ = Tile
            
        page(_context, name=name, permission=permission, for_=for_, layer=layer,
                template=template, class_=class_)
Esempio n. 2
0
def eventIdentifierPlugin(_context, plugin, name=None):
    if name is None:
        name = '.'.join((plugin.__module__, plugin.__name__))
    utility(_context,
            name=name,
            factory=plugin,
            provides=IEventIdentifierPlugin)
Esempio n. 3
0
def solrConnectionConfigDirective(_context, host, port, base):

    utility(
        _context,
        provides=IZCMLSolrConnectionConfig,
        component=ZCMLSolrConnectionConfig(host, port, base),
    )
    def customPreferenceGroup(_context, id=None, schema=None,
                              title=u'', description=u'', category=False):

        dotted_id = '%s.%s' % (group_id, id)
        id = dotted_id if id else id
        group = PreferenceGroup(id, annotation_factory, schema, title, description, category)
        utility(_context, IPreferenceGroup, group, name=id)
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)
Esempio n. 6
0
def anonymousObjectFactoryDirective(_context,
                                    factory,
                                    for_,
                                    field,
                                    pass_external_object_to_factory=False,
                                    trusted=False,
                                    title=u'',
                                    description=u''):
    _validate_factory(factory, trusted)

    field_name = str(field)
    field = for_[field]
    if field.interface is not for_:
        raise TypeError(
            "Field %r is not directly part of the interface %r (it is %r)" %
            (field_name, for_, field.interface))

    factory = AnonymousObjectFactory(factory, title, description)
    factory.__external_factory_wants_arg__ = pass_external_object_to_factory

    name = '%s.%s:%s' % (for_.__module__, for_.__name__, field_name)
    assert isinstance(name, str)
    component_zcml.utility(_context,
                           provides=IAnonymousObjectFactory,
                           component=factory,
                           name=name)

    _context.action(discriminator=('anonymousObjectFactory', for_, field_name),
                    callable=field.setTaggedValue,
                    args=('__external_factory__', name))
Esempio n. 7
0
def registerMimeFactories(_context, module):
    for object_name, value in find_factories_in_module(module,
                                                       case_sensitive=True):
        __traceback_info__ = object_name, value

        try:
            mime_type = value.mimeType
        except AttributeError:
            try:
                mime_type = value.mime_type
            except AttributeError:
                continue

        if mime_type:
            logger.log(loglevels.TRACE,
                       "Registered mime factory utility %s = %s (%s)",
                       object_name, value, mime_type)
            factory = MimeObjectFactory(value,
                                        title=object_name,
                                        interfaces=list(
                                            interface.implementedBy(value)))
            component_zcml.utility(_context,
                                   provides=IMimeObjectFactory,
                                   component=factory,
                                   name=mime_type)
Esempio n. 8
0
def ruleConditionDirective(_context,
                           name,
                           title,
                           addview,
                           editview=None,
                           description="",
                           for_=Interface,
                           event=Interface,
                           schema=None,
                           factory=None):
    """Register a utility for IRuleCondition based on the parameters in the
    zcml directive
    """

    condition = RuleCondition()
    condition.title = title
    condition.addview = addview
    condition.editview = editview
    condition.description = description
    condition.for_ = for_
    condition.event = event
    condition.schema = schema
    condition.factory = factory

    utility(_context, provides=IRuleCondition, component=condition, name=name)
Esempio n. 9
0
def contenttype_directive(_context,
                          portal_type,
                          class_,
                          schema,
                          behaviors=None,
                          add_permission=None,
                          allowed_types=None):
    """
    Generate factory for the passed schema
    """
    logger.warn('plone:contenttype directive will be removed in 1.0.0 final')

    # prevent circular import
    from plone.server.content import ResourceFactory

    factory = ResourceFactory(class_,
                              title='',
                              description='',
                              portal_type=portal_type,
                              schema=schema,
                              behaviors=behaviors or (),
                              add_permission=add_permission
                              or DEFAULT_ADD_PERMISSION,
                              allowed_types=allowed_types)
    utility(
        _context,
        provides=IResourceFactory,
        component=factory,
        name=portal_type,
    )
Esempio n. 10
0
def contenttype_directive(_context, portal_type, class_, schema, behaviors=None,
                          add_permission=None, allowed_types=None):
    """
    Generate factory for the passed schema
    """
    logger.warn('plone:contenttype directive will be removed in 1.0.0 final')

    # prevent circular import
    from plone.server.content import ResourceFactory

    factory = ResourceFactory(
        class_,
        title='',
        description='',
        portal_type=portal_type,
        schema=schema,
        behaviors=behaviors or (),
        add_permission=add_permission or DEFAULT_ADD_PERMISSION,
        allowed_types=allowed_types
    )
    utility(
        _context,
        provides=IResourceFactory,
        component=factory,
        name=portal_type,
    )
Esempio n. 11
0
def definePermission(_context,
                     id,
                     title,
                     access_level="write",
                     description=''):
    permission = LaunchpadPermission(id, title, access_level, description)
    utility(_context, ILaunchpadPermission, permission, name=id)
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)
Esempio n. 13
0
def handlerDirective(_context, name, transform, generator,
                     scope, class_=None, attribute=None, order=-1):
    if attribute and class_:
        msg = u"Either ``class`` or ``attribute`` must be set."
        raise ConfigurationError(msg)
    name = '%s.%s.%s' % (transform, generator, name)
    handler = class_(name, scope, order)
    utility(_context, provides=IHandler, component=handler, name=name)
Esempio n. 14
0
def registerSiteMapping(_context, source_site_name, target_site_name):
    """
    Create and register a site mapping, as a utility under the `source_site_name`.
    """
    site_mapping = SiteMapping(source_site_name=source_site_name,
                               target_site_name=target_site_name)
    utility(_context, provides=ISiteMapping,
            component=site_mapping, name=source_site_name)
def hotspotDirective(_context, name, obj=None, interface=None,
                     resource=[], considerparams=[]):
    if not obj and not interface and not resource:
        raise ConfigurationError(u"Du solltest dich entscheiden, Jonny!")
    hotspot = Hotspot(obj, interface, resource, considerparams)
    utility(_context,
            provides=IHotspot,
            component=hotspot,
            name=name)
Esempio n. 16
0
 def after(self):
     permission = Permission(self.id, self.title, self.description)
     utility(self.context, IPermission, permission, name=self.id)
     
     zope2_permission = str(self.title)
     if self.roles:
         addPermission(zope2_permission, default_roles=tuple(self.roles))
     else:
         addPermission(zope2_permission)
def menuDirective(_context, id=None, class_=BrowserMenu, interface=None,
                  title=u'', description=u''):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError(
            "You must specify the 'id' or 'interface' attribute.")

    if interface is None:
        if id in dir(menus):
            # reuse existing interfaces for the id, without this we are not
            # able to override menus.
            interface = getattr(menus, id)
        else:
            interface = InterfaceClass(id, (),
                                       __doc__='Menu Item Type: %s' %id,
                                       __module__='zope.app.menus')
            # Add the menu item type to the `menus` module.
            # Note: We have to do this immediately, so that directives using the
            # MenuField can find the menu item type.
            setattr(menus, id, interface)
        path = 'zope.app.menus.' + id
    else:
        path = interface.__module__ + '.' + interface.getName()

        # If an id was specified, make this menu available under this id.
        # Note that the menu will be still available under its path, since it
        # is an adapter, and the `MenuField` can resolve paths as well.
        if id is None:
            id = path
        else:
            # Make the interface available in the `zope.app.menus` module, so
            # that other directives can find the interface under the name
            # before the CA is setup.
            _context.action(
                discriminator=('browser', 'MenuItemType', path),
                callable=provideInterface,
                args=(path, interface, IMenuItemType, _context.info)
            )
            setattr(menus, id, interface)

    # Register the layer interface as an interface
    _context.action(
        discriminator=('interface', path),
        callable=provideInterface,
        args=(path, interface),
        kw={'info': _context.info}
    )

    # Register the menu item type interface as an IMenuItemType
    _context.action(
        discriminator=('browser', 'MenuItemType', id),
        callable=provideInterface,
        args=(id, interface, IMenuItemType, _context.info)
    )

    # Register the menu as a utility
    utility(_context, IBrowserMenu, class_(id, title, description), name=id)
Esempio n. 18
0
    def after(self):
        permission = Permission(self.id, self.title, self.description)
        utility(self.context, IPermission, permission, name=self.id)

        zope2_permission = str(self.title)
        if self.roles:
            addPermission(zope2_permission, default_roles=tuple(self.roles))
        else:
            addPermission(zope2_permission)
Esempio n. 19
0
def menuDirective(_context, id=None, class_=BrowserMenu, interface=None,
                  title=u'', description=u''):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError(
            "You must specify the 'id' or 'interface' attribute.")

    if interface is None:
        if id in dir(menus):
            # reuse existing interfaces for the id, without this we are not
            # able to override menus.
            interface = getattr(menus, id)
        else:
            interface = InterfaceClass(id, (),
                                       __doc__='Menu Item Type: %s' %id,
                                       __module__='zope.app.menus')
            # Add the menu item type to the `menus` module.
            # Note: We have to do this immediately, so that directives using the
            # MenuField can find the menu item type.
            setattr(menus, id, interface)
        path = 'zope.app.menus.' + id
    else:
        path = interface.__module__ + '.' + interface.getName()

        # If an id was specified, make this menu available under this id.
        # Note that the menu will be still available under its path, since it
        # is an adapter, and the `MenuField` can resolve paths as well.
        if id is None:
            id = path
        else:
            # Make the interface available in the `zope.app.menus` module, so
            # that other directives can find the interface under the name
            # before the CA is setup.
            _context.action(
                discriminator = ('browser', 'MenuItemType', path),
                callable = provideInterface,
                args = (path, interface, IMenuItemType, _context.info)
                )
            setattr(menus, id, interface)

    # Register the layer interface as an interface
    _context.action(
        discriminator = ('interface', path),
        callable = provideInterface,
        args = (path, interface),
        kw = {'info': _context.info}
        )

    # Register the menu item type interface as an IMenuItemType
    _context.action(
        discriminator = ('browser', 'MenuItemType', id),
        callable = provideInterface,
        args = (id, interface, IMenuItemType, _context.info)
        )

    # Register the menu as a utility
    utility(_context, IBrowserMenu, class_(id, title, description), name=id)
Esempio n. 20
0
def tile(_context,
         name,
         title=None,
         description=None,
         icon=None,
         add_permission=None,
         edit_permission=None,
         delete_permission=None,
         schema=None,
         for_=None,
         layer=None,
         class_=None,
         template=None,
         permission=None):
    """Implements the <plone:tile /> directive
    """
    if (title is not None or description is not None or icon is not None
            or add_permission is not None or schema is not None):
        if title is None or add_permission is None:
            raise ConfigurationError(
                u"When configuring a new type of tile, 'title' and "
                u"'add_permission' are required")
        type_ = TileType(name,
                         title,
                         add_permission,
                         permission,
                         edit_permission=edit_permission,
                         delete_permission=delete_permission,
                         description=description,
                         icon=icon,
                         schema=schema)

        utility(_context, provides=ITileType, component=type_, name=name)

    if (for_ is not None or layer is not None or class_ is not None
            or template is not None):
        if class_ is None and template is None:
            raise ConfigurationError(
                u"'class' or 'template' must be given when configuring a tile."
            )

        if for_ is None:
            for_ = Interface
        if layer is None:
            layer = IDefaultBrowserLayer

        if class_ is None:
            class_ = Tile

        page(_context,
             name=name,
             permission=permission,
             for_=for_,
             layer=layer,
             template=template,
             class_=class_)
Esempio n. 21
0
def componentFieldSpecDirective(_context, class_, fields=()):
    meta_type = class_.meta_type
    klass = type('ComponentFieldSpec',
                 (ComponentFieldSpec,),
                 {
                     'fields':fields,
                     'meta_type':meta_type,
                 }
            )
    utility(_context, name=meta_type, factory=klass, provides=IComponentFieldSpec)
Esempio n. 22
0
def engine(_context, url, name='', echo=False, pool_recycle=-1, **kwargs):

    engine_component = sqlalchemy.create_engine(
        url, echo=echo,
        pool_recycle=pool_recycle, **kwargs)

    zcml.utility(_context,
                 provides = interfaces.IDatabaseEngine,
                 component = engine_component,
                 name = name)
Esempio n. 23
0
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_,)
        )
Esempio n. 24
0
    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,))
Esempio n. 25
0
    def factory(self, _context, id=None, title="", description=''):
        """Register a zmi factory for this class"""

        id = id or self.__id
        factoryObj = Factory(self.__class, title, description)

        # note factories are all in one pile, utilities and content,
        # so addable names must also act as if they were all in the
        # same namespace, despite the utilities/content division
        utility(_context, IFactory, factoryObj,
                permission=PublicPermission, name=id)
def transformDirective(_context, provides=None, component=None, factory=None,
                       permission=None, name=None):

    if factory:
        if component:
            raise TypeError("Can't specify factory and component.")
        component = factory()
        factory = None

    if name is None:
        name = component.name
        if [True for n in KNOWN_BASE_NAMES if name.startswith(n)]:
            # If no name was specified or we are subclassing one of the
            # base classes, automatically generate the name based on the full
            # dotted class name.
            module = component.__module__
            classname = component.__class__.__name__
            name = component.name = module + '.' + classname

    if permission is None:
        # Default to all public permission
        permission = PublicPermission

    if provides is None:
        provides = list(providedBy(component))
        if len(provides) == 1:
            provides = provides[0]
        else:
            # Try to be a bit smarter about the interface guessing.
            for iface in provides:
                if (not iface.isOrExtends(ITransform) or
                    iface in INVALID_INTERFACES):
                    provides.remove(iface)
            # See if we still have more than one interface
            if len(provides) == 1:
                provides = provides[0]
            else:
                # See if we have both ITransform and something else in here
                if ITransform in provides:
                    provides.remove(ITransform)
                if len(provides) == 1:
                    provides = provides[0]
                else:
                    # Look again for ICommandTransform and something else
                    if ICommandTransform in provides:
                        provides.remove(ICommandTransform)
                    if len(provides) == 1:
                        provides = provides[0]
                    else:
                        raise TypeError("Missing 'provides' attribute")

    utility(_context, provides=provides, component=component, factory=factory,
                    permission=permission, name=name)
Esempio n. 27
0
 def __call__(self):
     # Set up the utility with an appropriate proxy.
     # Note that this does not take into account other security
     # directives on this content made later on during the execution
     # of the zcml.
     checker = Checker(
         self.permission_collector.get_permissions,
         self.permission_collector.set_permissions)
     component = ProxyFactory(self.component, checker=checker)
     utility(
         self._context, self.provides, component=component, name=self.name)
     return ()
def flavorDirective(_context, title, behavior, description=None, for_=None, icon=None):
    info = FlavorInfo(behavior)
    info.title = title
    info.description = description
    info.icon = icon
    if for_:
        info.interfaces = for_
    else:
        info.interfaces = (IFlavorAware,)

    # register a utility, used in vocabularies of flavors:
    utility(_context, provides=IFlavor, name=info.identifier, component=info)
Esempio n. 29
0
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_, ))
Esempio n. 30
0
def unauthenticatedPrincipal(_context, id, title, description=''):
    principal = principalregistry.UnauthenticatedPrincipal(
        id, title, description)
    _context.action(
        discriminator = 'unauthenticatedPrincipal',
        callable = principalregistry.principalRegistry.defineDefaultPrincipal,
        args = (id, title, description, principal) )
    utility(_context, interfaces.IUnauthenticatedPrincipal, principal)
    _context.action(
        discriminator = None,
        callable = _unauthenticatedPrincipal,
        args = (),
        )
Esempio n. 31
0
 def __call__(self):
     # Set up the utility with an appropriate proxy.
     # Note that this does not take into account other security
     # directives on this content made later on during the execution
     # of the zcml.
     checker = Checker(self.permission_collector.get_permissions,
                       self.permission_collector.set_permissions)
     component = ProxyFactory(self.component, checker=checker)
     utility(self._context,
             self.provides,
             component=component,
             name=self.name)
     return ()
Esempio n. 32
0
    def __init__(
        self,
        _context,
        name,
        schema,
        title,
        description="",
        class_=None,
        provides=(),
        permission="zojax.ManageProducts",
        tests=(),
        configurable=False,
        require=(),
    ):

        product_class = Product
        if class_ is None:
            class_ = product_class
        else:
            class_ = (class_, product_class)

        if configurable:
            test = ProductTest()
            tests = (test,) + tuple(tests)
        else:
            tests = (NotConfigurable,)

        # create component registry
        registry = ProductRegistry(name, title)
        zojax.product.registries[name] = registry
        setattr(zojax.product, name, registry)
        utility(_context, IComponents, registry, name=name)

        # register configlet
        productName = name
        name = "product." + name

        super(ProductDirective, self).__init__(
            _context, name, schema, title, description, class_, provides, permission, tests
        )

        self._class.__require__ = require
        self._class.__product_name__ = productName

        if configurable:
            test.product = self._configlet

        utility(_context, IProduct, self._configlet, name=productName)

        self.require(_context, permission, interface=(IProduct,))
        self.require(_context, CheckerPublic, attributes=("isInstalled", "__installed__"))
Esempio n. 33
0
def authenticatedGroup(_context, id, title, description=''):
    principal = principalregistry.AuthenticatedGroup(
        id, title, description)
    utility(_context, interfaces.IAuthenticatedGroup, principal)
    _context.action(
        discriminator = None,
        callable = _authenticatedGroup,
        args = (principal.id, ),
        )
    _context.action(
        discriminator = None,
        callable = principalregistry.principalRegistry.registerGroup,
        args = (principal, ),
        )
Esempio n. 34
0
def everybodyGroup(_context, id, title, description=''):
    principal = principalregistry.EverybodyGroup(
        id, title, description)
    utility(_context, interfaces.IEveryoneGroup, principal)
    _context.action(
        discriminator = None,
        callable = _everybodyGroup,
        args = (principal.id, ),
        )
    _context.action(
        discriminator = None,
        callable = principalregistry.principalRegistry.registerGroup,
        args = (principal, ),
        )
Esempio n. 35
0
def tikaConfigDirective(_context, **arguments):
    """The <tika:config /> directive.
    Usage:

    <configure xmlns:tika="http://namespaces.plone.org/tika">
        <tika:config path="/path/to/tika-app.jar"
                     host="tika.host"
                     port="9998"
                     timeout="10" />
    </configure>
    """

    utility(_context,
            provides=IZCMLTikaConfig,
            component=ZCMLTikaConfig(**arguments))
Esempio n. 36
0
def load_utility(_context, _utility):
    conf = _utility['config']
    if 'factory' in conf:
        conf['factory'] = resolve_or_get(conf['factory'])
    elif 'component' in conf:
        conf['component'] = resolve_or_get(conf['component'])
    else:
        # use provided klass
        klass = _utility['klass']
        if isinstance(klass, type):
            # is a class type, use factory setting
            conf['factory'] = klass
        else:
            # not a factory
            conf['component'] = klass
    zcml.utility(_context, **conf)
def unauthenticatedPrincipal(_context, id, title, description=''):
    """
    Implementation of :class:`zope.principalregistry.metadirectives.IDefineUnauthenticatedPrincipalDirective`.
    """
    principal = principalregistry.UnauthenticatedPrincipal(
        id, title, description)
    _context.action(
        discriminator='unauthenticatedPrincipal',
        callable=principalregistry.principalRegistry.defineDefaultPrincipal,
        args=(id, title, description, principal))
    utility(_context, interfaces.IUnauthenticatedPrincipal, principal)
    _context.action(
        discriminator=None,
        callable=_unauthenticatedPrincipal,
        args=(),
    )
Esempio n. 38
0
def classObjectFactoryDirective(_context,
                                factory,
                                name='',
                                trusted=False,
                                title='',
                                description=''):
    _validate_factory(factory, trusted)

    name = name or getattr(factory, '__external_class_name__',
                           factory.__name__)

    factory = ClassObjectFactory(factory, title, description)
    component_zcml.utility(_context,
                           provides=IClassObjectFactory,
                           component=factory,
                           name=name)
def registerPreferenceGroupDirective(_context, annotation_factory, directive_name, group_id):

    utility(_context, IPreferenceAnnotationFactory, annotation_factory, name=group_id)

    def customPreferenceGroup(_context, id=None, schema=None,
                              title=u'', description=u'', category=False):

        dotted_id = '%s.%s' % (group_id, id)
        id = dotted_id if id else id
        group = PreferenceGroup(id, annotation_factory, schema, title, description, category)
        utility(_context, IPreferenceGroup, group, name=id)

    defineSimpleDirective(_context,
                          name=directive_name,
                          schema=IPreferenceGroup,
                          handler=customPreferenceGroup)
Esempio n. 40
0
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 unauthenticatedGroup(_context, id, title, description=''):
    """
    Implementation of :class:`zope.principalregistry.metadirectives.IDefineUnauthenticatedGroupDirective`.
    """
    principal = principalregistry.UnauthenticatedGroup(
        id, title, description)
    utility(_context, interfaces.IUnauthenticatedGroup, principal)
    _context.action(
        discriminator=None,
        callable=_unauthenticatedGroup,
        args=(principal.id, ),
    )
    _context.action(
        discriminator=None,
        callable=principalregistry.principalRegistry.registerGroup,
        args=(principal, ),
    )
Esempio n. 42
0
def ruleConditionDirective(_context, name, title, addview, editview=None,
        description="", for_=Interface, event=Interface, schema=None, factory=None):
    """Register a utility for IRuleCondition based on the parameters in the
    zcml directive
    """

    condition = RuleCondition()
    condition.title = title
    condition.addview = addview
    condition.editview = editview
    condition.description = description
    condition.for_ = for_
    condition.event = event
    condition.schema = schema
    condition.factory = factory

    utility(_context, provides=IRuleCondition, component=condition, name=name)
Esempio n. 43
0
def load_utility(_context, _utility):
    conf = _utility['config']
    if 'factory' in conf:
        conf['factory'] = resolve_or_get(conf['factory'])
    elif 'component' in conf:
        conf['component'] = resolve_or_get(conf['component'])
    else:
        # use provided klass
        klass = _utility['klass']
        if isinstance(klass, type):
            # is a class type, use factory setting
            conf['factory'] = klass
        else:
            # not a factory
            conf['component'] = klass
    zcml.utility(
        _context,
        **conf
    )
Esempio n. 44
0
def load_contenttype(_context, contenttype):
    conf = contenttype['config']
    klass = contenttype['klass']
    if 'schema' in conf:
        classImplements(klass, conf['schema'])

    from plone.server.content import ResourceFactory

    factory = ResourceFactory(
        klass,
        title='',
        description='',
        portal_type=conf['portal_type'],
        schema=resolve_or_get(conf.get('schema', Interface)),
        behaviors=[resolve_or_get(b) for b in conf.get('behaviors', []) or ()],
        add_permission=conf.get('add_permission') or DEFAULT_ADD_PERMISSION,
        allowed_types=conf.get('allowed_types', None))
    zcml.utility(
        _context,
        provides=IResourceFactory,
        component=factory,
        name=conf['portal_type'],
    )
Esempio n. 45
0
    def __init__(self, _context, name, schema, title,
                 description='', class_=None, provides=(),
                 permission='zojax.Configure', tests=(), install_schema_utility=True):

        ConfigletClass = ConfigletType(
            str(name), schema, class_, title, description)

        for test in tests:
            if not callable(test):
                raise ConfigurationError("Test should be callable.")

        if permission == 'zope.Public':
            configlet = ConfigletClass(tuple(tests))
        else:
            configlet = ConfigletClass((
                PermissionChecker(permission),) + tuple(tests))

        utility(_context, IConfiglet, configlet, name=name)

        if install_schema_utility:
            utility(_context, schema, configlet)

        interface.classImplements(ConfigletClass, schema, *provides)

        self._class = ConfigletClass
        self._context = _context
        self._configlet = configlet
        self._permission = permission

        self.require(_context, permission,
                     interface=(IConfiglet, schema), set_schema=(schema,))
        self.require(_context, CheckerPublic, interface=(IEnumerableMapping,))
        self.require(_context, CheckerPublic, attributes=('isAvailable',))

        _context.action(
            discriminator=('zojax:controlpanel', configlet),
            callable=addSubgroup, args=(configlet,))
Esempio n. 46
0
def load_contenttype(_context, contenttype):
    conf = contenttype['config']
    klass = contenttype['klass']
    if 'schema' in conf:
        classImplements(klass, conf['schema'])

    from plone.server.content import ResourceFactory

    factory = ResourceFactory(
        klass,
        title='',
        description='',
        portal_type=conf['portal_type'],
        schema=resolve_or_get(conf.get('schema', Interface)),
        behaviors=[resolve_or_get(b) for b in conf.get('behaviors', []) or ()],
        add_permission=conf.get('add_permission') or DEFAULT_ADD_PERMISSION,
        allowed_types=conf.get('allowed_types', None)
    )
    zcml.utility(
        _context,
        provides=IResourceFactory,
        component=factory,
        name=conf['portal_type'],
    )
Esempio n. 47
0
def generatorDirective(_context, name, transform, depends,
                       targethandler=NullTargetHandler,
                       dispatcher=Dispatcher, class_=Generator,
                       description=u''):
    name = '%s.%s' % (transform, name)
    description = normalizetext(description)
    generator = class_(name, depends, description)
    utility(_context, provides=IGenerator, component=generator, name=name)
    dispatcher = dispatcher(name)
    utility(_context, provides=IDispatcher, component=dispatcher, name=name)
    targethandler = targethandler(None)
    utility(_context, provides=ITargetHandler,
            component=targethandler, name=name)
Esempio n. 48
0
def mq_queue(context, name,
             routing_key=u"default", processor=None, allow_emission=True):

    if allow_emission is False and processor is None:
        raise ValueError(u'A queue must be able to either send or receive.')

    queue = kombu.Queue(name, context.exchange, routing_key)

    if processor is not None:
        receiver = processor(queue, name)
        utility(context, IProcessor, receiver, name=name)
        utility(context, IReceptionQueue, queue, name=name)

    if allow_emission is True:
        utility(context, IEmissionQueue, queue, name=name)
Esempio n. 49
0
def mq_queue(context,
             name,
             routing_key=u"default",
             processor=None,
             allow_emission=True):

    if allow_emission is False and processor is None:
        raise ValueError(u'A queue must be able to either send or receive.')

    queue = kombu.Queue(name, context.exchange, routing_key)

    if processor is not None:
        receiver = processor(queue, name)
        utility(context, IProcessor, receiver, name=name)
        utility(context, IReceptionQueue, queue, name=name)

    if allow_emission is True:
        utility(context, IEmissionQueue, queue, name=name)
Esempio n. 50
0
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_, ))
Esempio n. 51
0
def _eventPlugin(_context, plugin, pluginInterface, name=None):
    if name is None:
        name = '.'.join((plugin.__module__, plugin.__name__))
    utility(_context, name=name, factory=plugin, provides=pluginInterface)
Esempio n. 52
0
 def _callFUT(self, *args, **kw):
     from zope.component.zcml import utility
     return utility(*args, **kw)
Esempio n. 53
0
def permission(_context, id, title, description=u''):
    from zope.security.interfaces import IPermission
    from zope.security.permission import Permission
    from zope.component.zcml import utility
    permission = Permission(id, title, description)
    utility(_context, IPermission, permission, name=id)
Esempio n. 54
0
def defineHRole(_context, id, title, description='', includes=''):
    iroles = includes.split()
    role = HRole(id, title, description, iroles)
    utility(_context, IHRole, role, name=id)
def preferenceGroup(_context, id=None, schema=None,
                    title=u'', description=u'', category=False):
    if id is None:
        id = ''
    group = PreferenceGroup(id, schema, title, description, category)
    utility(_context, IPreferenceGroup, group, name=id)
Esempio n. 56
0
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)