Пример #1
0
 def getViewTypeTitles(self):
     return {
         "browser": _("Browser"),
         "xmlrpc": _("XML-RPC"),
         "http": _("HTTP"),
         "ftp": _("FTP"),
         "other": _("Other"),
         }
Пример #2
0
def getInterfaceInfoDictionary(iface):
    """Return a PT-friendly info dictionary for an interface."""
    if isinstance(iface, zope.interface.declarations.Implements):
        iface = iface.inherit
    if iface is None:
        return None
    return {'module': getattr(iface, '__module__', _('<unknown>')),
            'name': getattr(iface, '__name__', _('<unknown>'))}
Пример #3
0
 def unlock(self):
     lock = self.storage.getLock(self.context)
     if lock is None:
         raise interfaces.LockingError(_("Object is not locked"))
     principal = self._findPrincipal()
     if lock.principal_id != principal.id:
         raise interfaces.LockingError(_("Principal is not lock owner"))
     self.storage.delLock(self.context)
     event.notify(interfaces.UnlockedEvent(self.context))
Пример #4
0
class IAllIndex(zope.interface.Interface):
    """Index all objects of a specified interface.
    Collects all instances, not any property value.
    """

    interface = zope.schema.Choice(
        title=_(u"Interface"),
        description=_(u"Collect objects of this interface"),
        vocabulary="Interfaces",
        required=False,
        )
Пример #5
0
    def invalidate(self):
        "Invalidate the current cached value."

        cache = getCacheForObject(self.context)
        location = getLocationForCache(self.context)
        if cache and location:
            cache.invalidate(location)
            return self.form(message=_("cache-invalidated", u"Invalidated."))
        else:
            return self.form(message=_("no-cache-associated",
                                       u"No cache associated with object."))
Пример #6
0
class IAllIndex(zope.interface.Interface):
    """I index objects by first adapting them to an interface, then
       retrieving a field on the adapted object.
    """

    interface = zope.schema.Choice(
        title=_(u"Interface"),
        description=_(u"Objects will be adapted to this interface"),
        vocabulary="Interfaces",
        required=False,
    )
Пример #7
0
class IWidgetDirective(Interface):
    """
    Register a widget
    """
    factory = GlobalObject(
        title=_("Factory"),
        description=_("Python name of a factory which can create the"
                      " implementation object.  This must identify an"
                      " object in a module using the full dotted name."),
        required=True,
    )
Пример #8
0
 def _findPrincipal(self):
     # Find the current principal. Note that it is possible for there
     # to be more than one principal - in this case we throw an error.
     interaction = zope.security.management.getInteraction()
     principal = None
     for p in interaction.participations:
         if principal is None:
             principal = p.principal
         else:
             raise interfaces.LockingError(_("Multiple principals found"))
     if principal is None:
         raise interfaces.LockingError(_("No principal found"))
     return principal
Пример #9
0
class IRSSListing(Interface):
    """A content type, which displays an RSS feed in the same way as
    RSS Portlet does.
    """

    # Cloned from: plone.app.portlets.portlets.rss.IRSSPortlet
    count = schema.Int(title=_(u'Number of items to display', domain="plone"),
                       description=_(u'How many items to list.',
                                     domain="plone"),
                       required=True,
                       default=5)
    url = schema.Text(
        title=_(u'List of RSS feed URLs', domain="jyu.rsslisting"),
        description=
        _(u'List of links to the RSS feeds to display. Please, enter only one link per line.',
          domain="jyu.rsslisting"),
        required=True,
        default=u'')
    timeout = schema.Int(
        title=_(u'Feed reload timeout', domain="plone"),
        description=_(
            u'Time in minutes after which the feed should be reloaded.',
            domain="plone"),
        required=True,
        default=100)

    showMoreEnabled = schema.Bool(
        title=_(u'Show link to show more', domain="jyu.rsslisting"),
        description=
        _(u'When set there will be link at the end to show all the results. If there is more than one RSS feed defined, only the first RSS feed will be linked.',
          domain="jyu.rsslisting"),
        required=False,
    )
Пример #10
0
class IBrowserSubMenuItem(IBrowserMenuItem):
    """A menu item that points to a sub-menu."""

    submenuId = TextLine(title=_("Sub-Menu Id"),
                         description=_(
                             "The menu id of the menu that describes the "
                             "sub-menu below this item."),
                         required=True)

    action = TextLine(title=_("The URL to display if the item is selected"),
                      description=_(
                          "When a user selects a browser menu item, the URL "
                          "given in the action is displayed. The action is "
                          "usually given as a relative URL, relative to the "
                          "object the menu item is for."),
                      required=False)
Пример #11
0
    def __call__(self):
        """Create breadcrumbs for an interface object.

        The breadcrumbs are rooted at the code browser.
        """
        docroot = findAPIDocumentationRoot(self.context)
        codeModule = traverse(docroot, "Code")
        crumbs = [{
            'name': _('[top]'),
            'url': absoluteURL(codeModule, self.request)
        }]
        # We need the __module__ of the interface, not of a location proxy,
        # so we have to remove all proxies.
        iface = removeAllProxies(self.context)
        mod_names = iface.__module__.split('.')
        obj = codeModule
        for name in mod_names:
            try:
                obj = traverse(obj, name)
            except KeyError: # pragma: no cover
                # An unknown (root) module, such as logging
                continue
            crumbs.append({
                'name': name,
                'url': absoluteURL(obj, self.request)
            })
        crumbs.append({
            'name': iface.__name__,
            'url': absoluteURL(self.context, self.request)
        })
        return crumbs
Пример #12
0
def getUtilityInfoDictionary(reg):
    """Return a PT-friendly info dictionary for a factory."""
    component = reg.component
    # Check whether we have an instance of some custom type or not
    # Unfortunately, a lot of utilities have a `__name__` attribute, so we
    # cannot simply check for its absence
    # TODO: Once we support passive display of instances, this insanity can go
    #       away.
    if not isinstance(component, (types.MethodType, types.FunctionType,
                                  six.class_types,
                                  InterfaceClass)):
        component = getattr(component, '__class__', component)

    path = getPythonPath(component)

    # provided interface id
    iface_id = '%s.%s' % (reg.provided.__module__, reg.provided.getName())

    # Determine the URL
    if isinstance(component, InterfaceClass):
        url = 'Interface/%s' % path
    else:
        url = None
        if isReferencable(path):
            url = 'Code/%s' % path.replace('.', '/')

    return {'name': six.text_type(reg.name) or _('<i>no name</i>'),
            'url_name': utilitymodule.encodeName(reg.name or '__noname__'),
            'iface_id': iface_id,
            'path': path,
            'url': url}
    def manage_delMessage(self, message, REQUEST, RESPONSE):
        """ """
        message_key = self.message_decode(message)
        self.get_message_catalog().del_message(message_key)

        url = get_url(REQUEST.URL1 + '/manage_messages',
                      REQUEST['batch_start'], REQUEST['batch_size'],
                      REQUEST['regex'], REQUEST.get('lang', ''),
                      REQUEST.get('empty', 0),
                      manage_tabs_message=_(u'Saved changes.'))
        RESPONSE.redirect(url)
Пример #14
0
 def lock(self, timeout=None, principal=None):
     if principal is None:
         principal = self._findPrincipal()
     principal_id = principal.id
     lock = self.storage.getLock(self.context)
     if lock is not None:
         raise interfaces.LockingError(_("Object is already locked"))
     lock = LockInfo(self.context, principal_id, timeout)
     self.storage.setLock(self.context, lock)
     event.notify(interfaces.LockedEvent(self.context, lock))
     return lock
Пример #15
0
class ILockInfo(IMapping):
    """
    An ILockInfo implementation is responsible for
    """

    target = interface.Attribute("""the actual locked object.""")

    principal_id = schema.TextLine(
        description=_("id of the principal owning the lock")
    )

    created = schema.Float(
        description=_("time value indicating the creation time"),
        required=False
    )

    timeout = schema.Float(
        description=_("time value indicating the lock timeout from creation"),
        required=False
    )
Пример #16
0
class IBrowserMenu(Interface):
    """Menu

    Menus are objects that can return a list of menu items they contain. How
    they generate this list is up to them. Commonly, however, they will look
    up adapters that provide the ``IBrowserMenuItem`` interface.
    """

    id = TextLine(title=_("Menu Id"),
                  description=_("The id uniquely identifies this menu."),
                  required=True)

    title = TextLine(
        title=_("Menu title"),
        description=_("The title provides the basic label for the menu."),
        required=False)

    description = Text(title=_("Menu description"),
                       description=_(
                           "A description of the menu. This might be shown "
                           "on menu pages or in pop-up help for menus."),
                       required=False)

    def getMenuItems(object, request):
        """Return a TAL-friendly list of menu items.
    def manage_delMessage(self, message, REQUEST, RESPONSE):
        """ """
        message_key = self.message_decode(message)
        self.get_message_catalog().del_message(message_key)

        url = get_url(REQUEST.URL1 + '/manage_messages',
                      REQUEST['batch_start'],
                      REQUEST['batch_size'],
                      REQUEST['regex'],
                      REQUEST.get('lang', ''),
                      REQUEST.get('empty', 0),
                      manage_tabs_message=_(u'Saved changes.'))
        RESPONSE.redirect(url)
    def manage_editMessage(self, message, language, translation,
                           REQUEST, RESPONSE):
        """Modifies a message.
        """
        message_encoded = message
        message_key = self.message_decode(message_encoded)
        self.get_message_catalog()\
            .edit_message(message_key, language, translation)

        url = get_url(REQUEST.URL1 + '/manage_messages',
                      REQUEST['batch_start'], REQUEST['batch_size'],
                      REQUEST['regex'], REQUEST.get('lang', ''),
                      REQUEST.get('empty', 0),
                      msg=message_encoded,
                      manage_tabs_message=_(u'Saved changes.'))
        RESPONSE.redirect(url)
    def manage_editMessage(self, message, language, translation, REQUEST,
                           RESPONSE):
        """Modifies a message.
        """
        message_encoded = message
        message_key = self.message_decode(message_encoded)
        self.get_message_catalog()\
            .edit_message(message_key, language, translation)

        url = get_url(REQUEST.URL1 + '/manage_messages',
                      REQUEST['batch_start'],
                      REQUEST['batch_size'],
                      REQUEST['regex'],
                      REQUEST.get('lang', ''),
                      REQUEST.get('empty', 0),
                      msg=message_encoded,
                      manage_tabs_message=_(u'Saved changes.'))
        RESPONSE.redirect(url)
Пример #20
0
def getFactoryInfoDictionary(reg):
    """Return a PT-friendly info dictionary for a factory."""
    factory = reg.component
    callable = factory

    # Usually only zope.component.factory.Factory instances have this attribute
    if IFactory.providedBy(factory) and hasattr(factory, '_callable'):
        callable = factory._callable
    elif hasattr(callable, '__class__'):
        callable = callable.__class__

    path = getPythonPath(callable)

    return {'name': six.text_type(reg.name) or _('<i>no name</i>'),
            'title': getattr(factory, 'title', u''),
            'description': renderText(getattr(factory, 'description', u''),
                                      module=callable.__module__),
            'url': isReferencable(path) and path.replace('.', '/') or None}
Пример #21
0
    def __call__(self):
        """Create breadcrumbs for a module or an object in a module or package.

        We cannot reuse the system's bread crumbs, since they go all the
        way up to the root, but we just want to go to the root module.
        """
        obj = self.context
        crumbs = []
        while not IDocumentationModule.providedBy(obj):
            crumbs.append(
                {'name': getName(obj),
                 'url': absoluteURL(obj, self.request)}
                )
            obj = getParent(obj)

        crumbs.append(
            {'name': _('[top]'),
             'url': absoluteURL(obj, self.request)}
            )
        crumbs.reverse()
        return crumbs
Пример #22
0
def getViewInfoDictionary(reg):
    """Build up an information dictionary for a view registration."""
    # get configuration info
    if isinstance(reg.info, (str, unicode)):
        doc = reg.info
        zcml = None
    else:
        doc = None
        zcml = getParserInfoInfoDictionary(reg.info)

    info = {'name' : unicode(reg.name) or _('<i>no name</i>'),
            'type' : getPythonPath(getPresentationType(reg.required[-1])),
            'factory' : getViewFactoryData(reg.factory),
            'required': [getInterfaceInfoDictionary(iface)
                         for iface in reg.required],
            'provided' : getInterfaceInfoDictionary(reg.provided),
            'doc': doc,
            'zcml': zcml
            }

    # Educated guess of the attribute name
    info.update(getPermissionIds('publishTraverse', klass=reg.factory))

    return info
Пример #23
0
from Products.ATContentTypes.content import base
from Products.ATContentTypes.content import schemata
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from jyu.rsslisting.interfaces.rsslisting import IRSSListing
from jyu.rsslisting.config import PROJECTNAME

from zope.i18nmessageid import Message as _ # requires explicit domain

RSSListingSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((

    atapi.IntegerField('count',
        required=True,
        searchable=True,
        storage=atapi.AnnotationStorage(),
        widget=atapi.IntegerWidget(label=_(u'Number of items to display', domain="plone"),
                                   description=_(u'How many items to list.', domain="plone")),
        default=5,
        ),

    atapi.TextField('url',
        required=True,
        searchable=True,
#        validators=(('isURL'),),
        storage=atapi.AnnotationStorage(),
        widget=atapi.TextAreaWidget(label=_(u'List of RSS feed URLs', domain="jyu.rsslisting"),
                                    description=_(u'List of links to the RSS feeds to display. Please, enter only one link per line.',
                                                  domain="jyu.rsslisting")),
        ),

    atapi.IntegerField('timeout',
Пример #24
0
 def breaklock(self):
     lock = self.storage.getLock(self.context)
     if lock is None:
         raise interfaces.LockingError(_("Object is not locked"))
     self.storage.delLock(self.context)
     event.notify(interfaces.BreakLockEvent(self.context))
Пример #25
0
                                       name='absolute_url')
        try:
            return absolute_url()
        except TypeError:
            # In case the cache object is a global one and does not have a
            # location, then we just return None. 
            return None

    def invalidate(self):
        "Invalidate the current cached value."

        cache = getCacheForObject(self.context)
        location = getLocationForCache(self.context)
        if cache and location:
            cache.invalidate(location)
            return self.form(message=_("cache-invalidated", u"Invalidated."))
        else:
            return self.form(message=_("no-cache-associated",
                                       u"No cache associated with object."))

    def action(self):
        "Change the cacheId"
        try:
            cacheId = self.cacheId_widget.getInputValue()
        except WidgetInputError, e:
            #return self.form(errors=e.errors)
            return repr(e.errors)
        else:
            self.cacheable.setCacheId(cacheId)
            return self.form(message=_(u"Saved changes."))
Пример #26
0
 def getViewClassTitles(self):
     return {
         "specific": _("Specific views"),
         "extended": _("Extended views"),
         "generic": _("Generic views"),
         }
Пример #27
0
 def check_content_type(self):
     if self.request.get_header("Content-Type") != "application/x-snarf":
         raise ValueError(_("Content-Type is not application/x-snarf"))
Пример #28
0
class ITingIndexSchema(IAttributeIndex):
    default_fields = BytesLine(
        title=_(u"Default fields"),
        description=_(
            "Look in these fields by default (consider dedicated_storage=True)"
        ),
        required=True,
        default='')
    storage = Choice(
        title=_(u"Storage"),
        description=_(u"Component for storing wordID-to-documentID-mappings"),
        required=True,
        default=config.DEFAULT_STORAGE,
        vocabulary="TextIndexNG3 Storages")
    dedicated_storage = Bool(
        title=_(u"Dedicated storage"),
        description=_(
            u"Use seperate index for each field (allows per field search)"),
        required=True,
        default=config.defaults['dedicated_storage'])
    languages = BytesLine(
        title=_(u"Languages"),
        description=_(
            u"Languages supported by this index (space seperated list)"),
        default=config.DEFAULT_LANGUAGE,
        constraint=re.compile('[a-z]+(\s+[a-z]+)*').match)
    use_stemmer = Bool(
        title=_(u"Stemming"),
        description=
        _(u"Compare words according to their word stems (a kind of similarity search)"
          ),
        default=False,
        required=config.defaults['use_stemmer'])
    use_stopwords = Bool(
        title=_(u"Stopwords"),
        description=
        _(u"Enable to prvent looking for words like 'and' or 'a' which are unlike to be useful in search queries"
          ),
        required=True,
        default=config.defaults['use_stopwords'])
    use_normalizer = Bool(
        title=_(u"Normalize"),
        description=
        _(u"Enable to normalize words language specific (e.g. ä -> ae , è -> e)"
          ),
        required=True,
        default=config.defaults['use_normalizer'])
    ranking = Bool(
        title=_(u"Ranking"),
        description=
        _(u"Enable ranking according to word frequency of documents (selects different storage)"
          ),
        required=True,
        default=config.defaults['ranking'])
    autoexpand_limit = Int(
        title=_(u"Autoexpand limit"),
        description=_(u"Lower limit for automatic right-*-wildcard-search"),
        required=True,
        default=config.defaults['autoexpand_limit'])
    splitter = Choice(
        title=_(u"Splitter"),
        description=_(u"Splitter to be used to turn text into words"),
        required=True,
        default=config.DEFAULT_SPLITTER,
        vocabulary="TextIndexNG3 Splitters")
    lexicon = Choice(
        title=_(u"Lexicon"),
        description=_(u"Component to be used for storing word-to-id-mappings"),
        required=True,
        default=config.DEFAULT_LEXICON,
        vocabulary="TextIndexNG3 Lexicons")
    index_unknown_languages = Bool(
        title=_(u"Index unknown languages"),
        description=
        _(u"Assigns unknown languages the first language of the languages selected for this index"
          ),
        required=True,
        default=config.defaults['index_unknown_languages'],
    )
    splitter_additional_chars = BytesLine(
        title=_(u"Non-seperators"),
        description=_(
            u"Characters that should *not* be threaded as separators"),
        required=True,
        default=config.defaults['splitter_additional_chars'])
    splitter_casefolding = Bool(
        title=_(u"Case-insensitive"),
        description=_(u"Make this index case insensitive"),
        required=True,
        default=config.defaults['splitter_casefolding'])
    query_parser = Choice(title=_(u"Query Parser"),
                          description=_(u"Parser to be used for this index"),
                          required=True,
                          default=config.DEFAULT_PARSER,
                          vocabulary="TextIndexNG3 Query Parsers")
    def get_namespace(self, REQUEST):
        """For the management interface, allows to filter the messages to
        show.
        """
        # Check whether there are languages or not
        languages = self.get_languages_mapping()
        if not languages:
            return {}

        # Input
        batch_start = REQUEST.get('batch_start', 0)
        batch_size = REQUEST.get('batch_size', 15)
        empty = REQUEST.get('empty', 0)
        regex = REQUEST.get('regex', '')
        message = REQUEST.get('msg', None)

        # Build the namespace
        namespace = {}
        namespace['batch_size'] = batch_size
        namespace['empty'] = empty
        namespace['regex'] = regex

        # The language
        lang = REQUEST.get('lang', None) or languages[0]['code']
        namespace['language'] = lang

        # Filter the messages
        query = regex.strip()
        try:
            query = re.compile(query)
        except:
            query = re.compile('')

        messages = []
        for m, t in self.get_message_catalog().messages():
            if query.search(m) and (not empty or not t.get(lang, '').strip()):
                messages.append(m)
        messages.sort(filter_sort)
        # How many messages
        n = len(messages)
        namespace['n_messages'] = n

        # Calculate the start
        while batch_start >= n:
            batch_start = batch_start - batch_size
        if batch_start < 0:
            batch_start = 0
        namespace['batch_start'] = batch_start
        # Select the batch to show
        batch_end = batch_start + batch_size
        messages = messages[batch_start:batch_end]
        # Batch links
        namespace['previous'] = get_url(REQUEST.URL, batch_start - batch_size,
                                        batch_size, regex, lang, empty)
        namespace['next'] = get_url(REQUEST.URL, batch_start + batch_size,
                                    batch_size, regex, lang, empty)

        # Get the message
        message_encoded = None
        #translations = {}
        translation = None
        if message is None:
            if messages:
                message = messages[0]
                translation = self.get_message_catalog()\
                                  .gettext(message, lang, '')
                message = to_unicode(message)
                message_encoded = self.message_encode(message)
        else:
            message_encoded = message
            message = self.message_decode(message_encoded)
            #translations = self.get_translations(message)
            translation = self.get_message_catalog().gettext(message, lang, '')
            message = to_unicode(message)
        namespace['message'] = message
        namespace['message_encoded'] = message_encoded
        #namespace['translations'] = translations
        namespace['translation'] = translation

        # Calculate the current message
        namespace['messages'] = []
        for x in messages:
            x = to_unicode(x)
            x_encoded = self.message_encode(x)
            url = get_url(REQUEST.URL,
                          batch_start,
                          batch_size,
                          regex,
                          lang,
                          empty,
                          msg=x_encoded)
            namespace['messages'].append({
                'message': x,
                'message_encoded': x_encoded,
                'current': x == message,
                'url': url
            })

        # The languages
        for language in languages:
            code = language['code']
            language['name'] = _(language['name'])
            language['url'] = get_url(REQUEST.URL,
                                      batch_start,
                                      batch_size,
                                      regex,
                                      code,
                                      empty,
                                      msg=message_encoded)
        namespace['languages'] = languages

        return namespace
    def get_namespace(self, REQUEST):
        """For the management interface, allows to filter the messages to
        show.
        """
        # Check whether there are languages or not
        languages = self.get_languages_mapping()
        if not languages:
            return {}

        # Input
        batch_start = REQUEST.get('batch_start', 0)
        batch_size = REQUEST.get('batch_size', 15)
        empty = REQUEST.get('empty', 0)
        regex = REQUEST.get('regex', '')
        message = REQUEST.get('msg', None)

        # Build the namespace
        namespace = {}
        namespace['batch_size'] = batch_size
        namespace['empty'] = empty
        namespace['regex'] = regex

        # The language
        lang = REQUEST.get('lang', None) or languages[0]['code']
        namespace['language'] = lang

        # Filter the messages
        query = regex.strip()
        try:
            query = re.compile(query)
        except:
            query = re.compile('')

        messages = []
        for m, t in self.get_message_catalog().messages():
            if query.search(m) and (not empty or not t.get(lang, '').strip()):
                messages.append(m)
        messages.sort(filter_sort)
        # How many messages
        n = len(messages)
        namespace['n_messages'] = n

        # Calculate the start
        while batch_start >= n:
            batch_start = batch_start - batch_size
        if batch_start < 0:
            batch_start = 0
        namespace['batch_start'] = batch_start
        # Select the batch to show
        batch_end = batch_start + batch_size
        messages = messages[batch_start:batch_end]
        # Batch links
        namespace['previous'] = get_url(REQUEST.URL, batch_start - batch_size,
            batch_size, regex, lang, empty)
        namespace['next'] = get_url(REQUEST.URL, batch_start + batch_size,
            batch_size, regex, lang, empty)

        # Get the message
        message_encoded = None
        #translations = {}
        translation = None
        if message is None:
            if messages:
                message = messages[0]
                translation = self.get_message_catalog()\
                                  .gettext(message, lang, '')
                message = to_unicode(message)
                message_encoded = self.message_encode(message)
        else:
            message_encoded = message
            message = self.message_decode(message_encoded)
            #translations = self.get_translations(message)
            translation = self.get_message_catalog().gettext(message, lang, '')
            message = to_unicode(message)
        namespace['message'] = message
        namespace['message_encoded'] = message_encoded
        #namespace['translations'] = translations
        namespace['translation'] = translation

        # Calculate the current message
        namespace['messages'] = []
        for x in messages:
            x = to_unicode(x)
            x_encoded = self.message_encode(x)
            url = get_url(
                REQUEST.URL, batch_start, batch_size, regex, lang, empty,
                msg=x_encoded)
            namespace['messages'].append({
                'message': x,
                'message_encoded': x_encoded,
                'current': x == message,
                'url': url})

        # The languages
        for language in languages:
            code = language['code']
            language['name'] = _(language['name'])
            language['url'] = get_url(REQUEST.URL, batch_start, batch_size,
                regex, code, empty, msg=message_encoded)
        namespace['languages'] = languages

        return namespace
Пример #31
0
    def status(self):
        setUpWidget(self, 'principal', self.principal_field, IInputWidget)
        if not self.principal_widget.hasInput():
            return u''
        try:
            principal = self.principal_widget.getInputValue()
        except MissingInputError:
            return u''

        self.principal = principal

        # Make sure we can use the principal id in a form by base64ing it
        principal_token = unicode(principal).encode('base64').strip().replace(
            '=', '_')

        roles = [role for name, role in getUtilitiesFor(IRole)]
        roles.sort(lambda x, y: cmp(x.title, y.title))
        principal_roles = IPrincipalRoleManager(self.context)

        self.roles = []
        for role in roles:
            name = principal_token + '.role.'+role.id
            field = zope.schema.Choice(__name__= name,
                                       title=role.title,
                                       vocabulary=settings_vocabulary)
            setUpWidget(self, name, field, IInputWidget,
                        principal_roles.getSetting(role.id, principal))
            self.roles.append(getattr(self, name+'_widget'))

        perms = [perm for name, perm in getUtilitiesFor(IPermission)]
        perms.sort(lambda x, y: cmp(x.title, y.title))
        principal_perms = IPrincipalPermissionManager(self.context)

        self.permissions = []
        for perm in perms:
            if perm.id == 'zope.Public':
                continue
            name = principal_token + '.permission.'+perm.id
            field = zope.schema.Choice(__name__=name,
                                       title=perm.title,
                                       vocabulary=settings_vocabulary)
            setUpWidget(self, name, field, IInputWidget,
                        principal_perms.getSetting(perm.id, principal))
            self.permissions.append(
                getattr(self, name+'_widget'))

        if 'GRANT_SUBMIT' not in self.request:
            return u''

        for role in roles:
            name = principal_token + '.role.'+role.id
            role_widget = getattr(self, name+'_widget')
            if role_widget.hasInput():
                try:
                    setting = role_widget.getInputValue()
                except MissingInputError:
                    pass
                else:
                    # Arrgh!
                    if setting is Allow:
                        principal_roles.assignRoleToPrincipal(
                            role.id, principal)
                    elif setting is Deny:
                        principal_roles.removeRoleFromPrincipal(
                            role.id, principal)
                    else:
                        principal_roles.unsetRoleForPrincipal(
                            role.id, principal)

        for perm in perms:
            if perm.id == 'zope.Public':
                continue
            name = principal_token + '.permission.'+perm.id
            perm_widget = getattr(self, name+'_widget')
            if perm_widget.hasInput():
                try:
                    setting = perm_widget.getInputValue()
                except MissingInputError:
                    pass
                else:
                    # Arrgh!
                    if setting is Allow:
                        principal_perms.grantPermissionToPrincipal(
                            perm.id, principal)
                    elif setting is Deny:
                        principal_perms.denyPermissionToPrincipal(
                            perm.id, principal)
                    else:
                        principal_perms.unsetPermissionForPrincipal(
                            perm.id, principal)

        return _('Grants updated.')
Пример #32
0
class IBrowserMenuItem(Interface):
    """Menu type

    An interface that defines a menu.
    """

    title = TextLine(
        title=_("Menu item title"),
        description=_("The title provides the basic label for the menu item."),
        required=True)

    description = Text(
        title=_("Menu item description"),
        description=_("A description of the menu item. This might be shown "
                      "on menu pages or in pop-up help for menu items."),
        required=False)

    action = TextLine(title=_("The URL to display if the item is selected"),
                      description=_(
                          "When a user selects a browser menu item, the URL"
                          "given in the action is displayed. The action is "
                          "usually given as a relative URL, relative to the "
                          "object the menu item is for."),
                      required=True)

    order = Int(title=_("Menu item ordering hint"),
                description=_(
                    "This attribute provides a hint for menu item ordering."
                    "Menu items will generally be sorted by the `for_`"
                    "attribute and then by the order."))

    filter_string = TextLine(
        title=_("A condition for displaying the menu item"),
        description=_("The condition is given as a TALES expression. The "
                      "expression has access to the variables:\n"
                      "\n"
                      "context -- The object the menu is being displayed "
                      "for\n"
                      "\n"
                      "request -- The browser request\n"
                      "\n"
                      "nothing -- None\n"
                      "\n"
                      "The menu item will not be displayed if there is a \n"
                      "filter and the filter evaluates to a false value."),
        required=False)

    icon = URI(title=_("Icon URI"),
               description=_("URI of the icon representing this menu item"))

    def available():
        """Test whether the menu item should be displayed
Пример #33
0
 def sizeForDisplay(self):
     num_items = self._get_size()
     if num_items == 1:
         return _('1 item')
     return _('${items} items', mapping={'items': str(num_items)})
Пример #34
0
 def getDocString(self):
     """See Module class."""
     return _('Zope 3 root.')
Пример #35
0
        elif interfaces.IPreferenceGroup.providedBy(obj):
            parent = getParent(obj)
            matches = interfaces.IPreferenceCategory.providedBy(parent)

        return matches


class PreferencesTree(CookieTreeView):
    """Preferences Tree using the stateful cookie tree."""
    def tree(self):
        root = getRoot(self.context)
        filter = PreferenceGroupFilter()
        return self.cookieTree(root, filter)


pref_msg = _("${name} Preferences")


class EditPreferenceGroup(EditView):
    def __init__(self, context, request):
        self.__used_for__ = removeSecurityProxy(context.__schema__)
        self.schema = removeSecurityProxy(context.__schema__)

        if self.schema is None:
            self.schema = NoneInterface
            zope.interface.alsoProvides(removeSecurityProxy(context),
                                        NoneInterface)

        name = translate(context.__title__,
                         context=request,
                         default=context.__title__)
Пример #36
0
class BookModule(OnlineHelp):
    """Represent a book compiled from various `README.txt` and other `*.txt`
    documentation files.
    """

    implements(IBookModule)

    # See zope.app.apidoc.interfaces.IDocumentationModule
    title = _('Book')

    # See zope.app.apidoc.interfaces.IDocumentationModule
    description = _("""
    This is a developer's book compiled from all existing documentation
    files. It is not meant to be a complete or cohesive work, but each chapter
    in itself is a little story. Think about it like a collection of fairy
    tales.
    """)


# Global Book Instance
path = os.path.join(os.path.dirname(zope.app.apidoc.bookmodule.__file__),
                    'intro.txt')
book = BookModule(_('Book'), path)

def _clear():
    global book
    book.__init__(book.title, book.path)

from zope.testing import cleanup
cleanup.addCleanUp(_clear)
Пример #37
0
#
##############################################################################
"""Role implementation
"""
__docformat__ = 'restructuredtext'

from persistent import Persistent

from zope.interface import implementer
from zope.component import getUtilitiesFor
from zope.location import Location

from zope.securitypolicy.interfaces import IRole

from zope.i18nmessageid import ZopeMessageFactory as _
NULL_ID = _('<role not activated>')


@implementer(IRole)
class Role(object):

    def __init__(self, id, title, description=""):
        self.id = id
        self.title = title
        self.description = description


@implementer(IRole)
class LocalRole(Persistent, Location):

    def __init__(self, title, description=""):
Пример #38
0
 def test_translation_msgid(self):
     t = PageTemplate()
     t.write("""<p tal:replace="options/msgid">text</p>""")
     self.assertEqual(t(msgid=_("x")), "translated")
Пример #39
0
#
##############################################################################
"""Setting bases for local sites.

$Id$
"""
__docformat__ = "reStructuredText"
import zope.interface
import zope.component
import zope.schema
from zope.i18nmessageid import ZopeMessageFactory as _
from zope.formlib import form
from zope.security.proxy import removeSecurityProxy
from zope.site.interfaces import ILocalSiteManager

BASENAME = _('-- Global Base Registry --')
PARENTNAME = _('-- Parent Local Registry --')

class BaseComponentsVocabulary(zope.schema.vocabulary.SimpleVocabulary):
    """A vocabulary for ``IComponents`` utilities."""

    zope.interface.classProvides(zope.schema.interfaces.IVocabularyFactory)

    def __init__(self, context):
        terms = []
        utils = set()
        
        # add available registry utilities
        for name, util in \
            zope.component.getUtilitiesFor(
                zope.component.interfaces.IComponents, context):
Пример #40
0
 def getDocString(self):
     return _('Zope 3 root.')
Пример #41
0
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.securitypolicy.interfaces import IPrincipalRoleManager
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.vocabulary import GrantVocabulary

from zope.authentication.principal import PrincipalSource
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import MissingInputError
from zope.formlib.utility import setUpWidget
from zope.formlib.widget import renderElement
from zope.formlib.widgets import RadioWidget
from zope.security.interfaces import IPermission


settings_vocabulary = GrantVocabulary(
    [SimpleTerm(Allow, token="allow", title=_('Allow')),
     SimpleTerm(Unset, token="unset", title=_('Unset')),
     SimpleTerm(Deny,  token='deny',  title=_('Deny')),
     ])


class GrantWidget(RadioWidget):
    """Grant widget for building a colorized matrix.

    The matrix shows anytime the status if you edit the radio widgets.
    This special widget shows the radio input field without labels.
    The labels are added in the header of the table. The order of the radio
    input fields is 'Allowed', 'Unset', 'Deny'.

    """
    orientation = "horizontal"
Пример #42
0
from Products.ATContentTypes.content import schemata
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from jyu.rsslisting.interfaces.rsslisting import IRSSListing
from jyu.rsslisting.config import PROJECTNAME

from zope.i18nmessageid import Message as _  # requires explicit domain

RSSListingSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((
    atapi.IntegerField(
        'count',
        required=True,
        searchable=True,
        storage=atapi.AnnotationStorage(),
        widget=atapi.IntegerWidget(
            label=_(u'Number of items to display', domain="plone"),
            description=_(u'How many items to list.', domain="plone")),
        default=5,
    ),
    atapi.TextField(
        'url',
        required=True,
        searchable=True,
        #        validators=(('isURL'),),
        storage=atapi.AnnotationStorage(),
        widget=atapi.TextAreaWidget(
            label=_(u'List of RSS feed URLs', domain="jyu.rsslisting"),
            description=
            _(u'List of links to the RSS feeds to display. Please, enter only one link per line.',
              domain="jyu.rsslisting")),
    ),