def items(self):
        """Return items to be shown in the calendar overlay.

        Does not include "my calendar".

        Each item is a dict with the following keys:

            'title' - title of the calendar

            'calendar' - the calendar object

            'color1', 'color2' - colors assigned to this calendar

            'id' - identifier for form controls

            'checked' - was this item checked for display (either "checked" or
            None)?

        """
        person = IPerson(self.request.principal)
        items = [((item.calendar.title, getPath(item.calendar.__parent__)),
                  {'title': item.calendar.title,
                   'id': getPath(item.calendar.__parent__),
                   'calendar': item.calendar,
                   'checked': item.show and "checked" or '',
                   'color1': item.color1,
                   'color2': item.color2})
                 for item in person.overlaid_calendars
                 if canAccess(item.calendar, '__iter__')]
        items.sort()
        return [i[-1] for i in items]
def getReviewKey(instance, object, *args, **kw):
    request = object.request
    principal = object.context.principal

    if request is None or request.principal.id != principal.id:
        return {'principal': 'notself',
                'context': getPath(object.context)}

    else:
        return {'principal': principal.id,
                'context': getPath(object.context)}
Exemple #3
0
    def cutObjects(self):
        """move objects specified in a list of object ids"""
        request = self.request
        ids = request.get('ids')
        if not ids:
            IStatusMessage(request).add(
                _("You didn't specify any ids to cut."), 'error')
            return

        container = self.context
        container_path = getPath(container)

        items = []
        for id in ids:
            ob = container[id]
            mover = IObjectMover(ob)
            if not mover.moveable():
                IStatusMessage(request).add(
                    _("Object '${name}' cannot be moved", {"name": id}),
                    'error'
                )
                return
            items.append(joinPath(container_path, id))

        # store the requested operation in the principal annotations:
        clipboard = getPrincipalClipboard(request)
        clipboard.clearContents()
        clipboard.addItems('cut', items)

        IStatusMessage(request).add(_('Selected items has been cut.'))
Exemple #4
0
    def getId(self, item):
        """Returns the DOM id for a given object.

        Note: we encode the upper case letters because the Dom element id are 
        not case sensitive in HTML. We prefix each upper case letter with ':'.
        """
        path = api.getPath(item)
        newPath = u''
        for letter in path:
            if letter in string.uppercase:
                newPath += ':' + letter
            else:
                newPath += letter

        # we use a dot as a root representation, this avoids to get the same id
        # for the ul and the first li tag
        if newPath == '/':
            newPath = '.'
        # add additinal dot which separates the tree id and the path, is used
        # for get the tree id out of the string in the javascript using
        # ids = id.split("."); treeId = ids[0];
        id = self.z3cJSONTreeId +'.'+ newPath
        # convert '/' path separator to marker '::', because the path '/'' is  
        # not allowed as DOM id. See also:
        # http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name
        return id.replace('/', '::')
Exemple #5
0
    def handleCut(self, action):
        if not len(self.selectedItems):
            self.status = self.cutNoItemsMessage
            return

        items = []
        append = items.append
        for obj in self.selectedItems:
            mover = IObjectMover(obj)
            __name__ = api.getName(obj)
            if not mover.moveable():
                m = {"name": __name__}
                if name:
                    m["name"] = __name__
                    self.status = _(
                        "Object '${name}' (${name}) cannot be moved",
                        mapping=m)
                else:
                    self.status = _("Object '${name}' cannot be moved",
                                   mapping=m)
                transaction.doom()
                return
            append(api.joinPath(api.getPath(self.context), __name__))

        self.status = self.cutItemsSelected
        # store the requested operation in the principal annotations:
        self.clipboard.clearContents()
        self.clipboard.addItems('cut', items)
def Workspace(object, instance, *args, **kw):
    if not instance.available:
        raise DoNotCache()
    if instance.workspace is not None:
        return {'context': getPath(instance.workspace)}
    else:
        return ()
Exemple #7
0
def ContextModified(object, instance, *args, **kw):
    key = {'context': getPath(instance.context)}

    times = IDCTimes(instance.context, None)
    if times is not None:
        key['modified'] = times.modified

    return key
def BreadcrumbsContext(object, instance, *args, **kw):
    contexts = []
    for object in instance.objects:
        times = IDCTimes(object, None)
        if times is not None:
            contexts.append(times.modified)
    return {'context': getPath(instance.context),
            'contexts': tuple(contexts)}
    def __call__(self, context):
        if not IDraftContent.providedBy(context):
            return Vocabulary(())

        ct = IContentType(context)
        types = []
        for tp in ct.destination:
            types.append(tp.name)

        kwargs = {}
        if types:
            kwargs['type'] = {'any_of': types}

        request = getRequest()
        catalog = getUtility(ICatalog)

        perms = {}
        permissions = []
        for id in listAllowedRoles(request.principal, context):
            perms[ct.submit] = 1
            perms[ct.publish] = 1
            permissions.append((ct.submit, id))
            permissions.append((ct.publish, id))

        results = catalog.searchResults(
            draftSubmitTo={'any_of': permissions}, **kwargs)

        if not results:
            return Vocabulary(())

        perms = perms.keys()
        ids = getUtility(IIntIds)

        contents = []
        for content in results:
            allow = False
            for perm in perms:
                if checkPermission(perm, content):
                    allow = True
                    break

            if allow:
                contents.append(
                    (getPath(content),
                     IItem(content).title, ids.getId(content), content))

        contents.sort()

        terms = []
        for path, title, id, content in contents:
            term = SimpleTerm(
                id, str(id), getMultiAdapter((content, request), IBreadcrumb))
            term.content = content
            terms.append(term)

        return Vocabulary(terms)
Exemple #10
0
    def __call__(self, id, instance, *args, **kw):
        global tagging

        name = u'portlet:%s'%instance.__name__
        val = tagging.query(name, instance.context)
        context = getPath(instance.context)

        if val:
            return (('tag:%s'%name, val), ('context', context))
        return (('context', context),)
Exemple #11
0
 def update(self):
     """Process form submission."""
     if 'OVERLAY_MORE' in self.request:
         person = IPerson(self.request.principal)
         url = absoluteURL(person, self.request)
         url += '/calendar_selection.html'
         url += '?nexturl=%s' % urllib.quote(str(self.request.URL))
         self.request.response.redirect(url)
     if 'OVERLAY_APPLY' in self.request:
         person = IPerson(self.request.principal)
         selected = set(self.request.get('overlay', []))
         for item in person.overlaid_calendars:
             item.show = getPath(item.calendar.__parent__) in selected
         url = str(self.request.URL)
         self.request.response.redirect(url)
Exemple #12
0
    def test_ensureUtilityForSubSite(self):
        self.createRFAndSM()

        db, connection, root, root_folder = getInformationFromEvent(
            EventStub(self.db))

        sub_folder = root_folder['sub_folder']
        ensureUtility(sub_folder, IErrorReportingUtility,
                     'ErrorReporting', ErrorReportingUtility,
                     'ErrorReporting')

        # Make sure it was created on the sub folder, not the root folder
        got_utility = zope.component.getUtility(IErrorReportingUtility,
                                                name='ErrorReporting',
                                                context=sub_folder)
        got_path = getPath(got_utility)
        self.assertEquals("/sub_folder/++etc++site/default/ErrorReporting", got_path)
Exemple #13
0
 def __init__(self, context):
     self.context = context
     try:
         parent = getParent(self.context)
     except TypeError:
         parent = None
     if parent is not None:
         try:
             pp = getPath(parent)
         except TypeError:
             pp = ""
         if not pp.endswith("/"):
             pp += "/"
         self.pp = pp # parentpath
     else:
         self.pp = ""
     self.pplen = len(self.pp)
    def getLanguages(self):
        tool = getUtility(IPortalLanguagesConfiglet)
        if not tool.isVisible:
            return []
        patern = re.compile(r"(.*)_(.*)$")
        site_name = patern.split(getSite().__name__)

        def normalise_site_name(site_name):
            return len(site_name)>1 and site_name[1:] or site_name + ['gb']
        site_name = normalise_site_name(site_name)
        root = getRoot(self.context)
        sites = []
        current_site = getSite()
        for site in [(i,normalise_site_name(patern.split(i[0]))) for i in root.items() if ISite.providedBy(i[1])]:
            setSite(site[0][1])
            if getUtility(IPortalLanguagesConfiglet).isVisible:
                sites.append(site)
        setSite(current_site)

        def link_by_path(path,site):
            if len(path)==0:
                return site
            parent = site
            item = path[0]
            for item in path:
                if item in [i for i in parent.keys()]:
                    parent = parent[item]
                else:
                    break
            return parent

        langs = []
        for site in sites:
            if site[1][0]==site_name[0]:
                setSite(site[0][1])
                langs.append({
                            'code':site[1][1],
                            'link':absoluteURL(link_by_path(getPath(self.context).split('/')[2:],site[0][1]),self.request),
                            'title':re.sub(r'(\/.*)? ?\[.*?\]$','',[i[1].title for i in zojax.language.vocabulary.terms if i[1].value == getUtility(ISiteLanguage).language][0])
                            })
                setSite(current_site)

        return langs
    def __call__(self, context):
        terms = []
        ids = getUtility(IIntIds)
        site = getSite()
        try:
            for i in [site] + getParents(site):
                if not ISite.providedBy(i):
                    continue
                setSite(i)
                fields = getUtility(IProfileFields)
                for name, field in fields.items():
                    id  = ids.getId(field)
                    path = getPath(i)[1:]
                    if path:
                        path += '/'
                    terms.append((path+IItem(field).title, id))

            terms.sort()
            return Vocabulary(
                [SimpleTerm(name, name, title) for title, name in terms])
        finally:
            setSite(site)
Exemple #16
0
    def __init__(self, sequence, start=0, size=20,
                 batches=None, context=None, request=None,
                 prefix='', queryparams={}):
        self.context = context
        self.request = request
        self.prefix = prefix

        if request is not None:
            rkey = self.prefix + 'bstart'

            if context is None:
                key = rkey
            else:
                key = '%s:%s'%(getPath(context), rkey)

            if rkey in request:
                try:
                    rstart = int(request.get(rkey, start))

                    data = ISession(request)[SESSIONKEY]
                    data[key] = rstart

                    start = rstart
                except:
                    pass
            else:
                data = ISession(request)[SESSIONKEY]
                start = data.get(key, start)

        if start >= len(sequence):
            start = 0

        super(SessionBatch, self).__init__(sequence, start, size, batches)

        if batches is None:
            self.batches = Batches(self)

        self.queryparams = queryparams
    def copyObjects(self):
        """Copy objects specified in a list of object ids"""
        request = self.request
        ids = request.get('ids')

        if not ids:
            self.error = _("You didn't specify any ids to copy.")
            return

        container_path = getPath(self.context)

        # For each item, check that it can be copied; if so, save the
        # path of the object for later copying when a destination has
        # been selected; if not copyable, provide an error message
        # explaining that the object can't be copied.
        items = []
        for id in ids:
            ob = self.context[id]
            copier = IObjectCopier(ob)
            if not copier.copyable():
                m = {"name": id}
                title = getDCTitle(ob)
                if title:
                    m["title"] = title
                    self.error = _(
                        "Object '${name}' (${title}) cannot be copied",
                        mapping=m)
                else:
                    self.error = _("Object '${name}' cannot be copied",
                                   mapping=m)
                return
            items.append(joinPath(container_path, id))

        # store the requested operation in the principal annotations:
        clipboard = getPrincipalClipboard(self.request)
        clipboard.clearContents()
        clipboard.addItems('copy', items)
Exemple #18
0
 def __init__(self, obj, stype='oid'):
     self.stype = stype
     if self.stype == 'oid':
         self.value = obj.getObjectId()
     elif self.stype == 'path':
         self.value = getPath(obj)
    def update(self):
        context = self.context
        request = self.request
        maincontext = self.maincontext
        mainview = self.mainview
        ws = mainview
        view = mainview
        viewclass = mainview.__class__.__bases__[0]
        ct = IContentType(maincontext, None)

        self.portal_url = '%s/' % absoluteURL(context, request)

        self.context_title = getMultiAdapter(
            (maincontext, request), IBreadcrumb).name

        if not ISite.providedBy(maincontext):
            self.notRoot = True
            self.portal_title = getMultiAdapter(
                (getSite(), request), IBreadcrumb).name

        self.url = '%s/' % request.URL
        self.base_url = '%s/' % request.URL[-1]

        # body id

        while not IWorkspace.providedBy(ws):
            ws = ws.__parent__
            if ws is None:
                break

        self.contentClass = 'aero'

        if ws is not None:
            self.contentClass += ' section-workspace-%s' % ws.__name__.replace(
                '.', '-')

        if IConfiglet.providedBy(maincontext):
            self.contentClass += ' section-controlpanel-%s' % maincontext.__name__.replace(
                '.', '-')

        # body class

        if ct is None:
            ctname = maincontext.__name__
        else:
            ctname = ct.name

        if IConfiglet.providedBy(maincontext):
            ctname = maincontext.__name__

        self.contentId = '-'.join(
            ('section', ctname, mainview.__name__)).replace('.', '-').replace('@', '')

        if IForm.providedBy(mainview):
            self.contentClass += ' ' + mainview.mode

        if not viewclass is BrowserPagelet:
            self.contentClass += ' %s.%s' % (
                viewclass.__module__, viewclass.__name__)

        if mainview.template:
            self.contentClass += ' %s' % (
                os.path.split(mainview.template.filename)[1])

        self.contentClass = self.contentClass.replace('.', '-').lower()
        self.sitePath = getPath(getSite())[1:].replace('/', '-')
        self.contentPath = getPath(maincontext)[1:].replace('/', '-')

        while not IContentWizard.providedBy(view):
            view = view.__parent__
            if view is None:
                break

        self.wizard = view is not None

        self.wizard = self.wizard or isinstance(maincontext, Feeds)
        if self.wizard:
            self.contentClass += ' wizard'
def NewsListingBatchTag(oid, instance, *args, **kw):
    return {'bstart': (instance.news.start, len(instance.news)),
            'bpages': len(instance.news.batches),
            'context': getPath(instance.context)}
Exemple #21
0
 def testGetPathOfRoot(self):
     from zope.traversing.api import getPath
     self.assertEqual(
         getPath(self.root),
         u'/',
     )
Exemple #22
0
 def testGetPath(self):
     from zope.traversing.api import getPath
     self.assertEqual(getPath(self.item), u'/folder/item')
Exemple #23
0
 def _items(self):
     """return all items and their path (for testing only!)"""
     return [(uid, getPath(ref())) for uid, ref in self.context.items()]
Exemple #24
0
def PrincipalAndContext(object, instance, *args, **kw):
    return {'principal': instance.request.principal.id,
            'context': getPath(instance.context)}
 def testGetPathOfRoot(self):
     from zope.traversing.api import getPath
     self.assertEqual(
         getPath(self.root),
         u'/',
         )
Exemple #26
0
def VisibleContext(object, instance, *args, **kw):
    if IVisibleContext.providedBy(instance.context):
        return {'context': getPath(instance.context)}
    else:
        return {'principal': instance.request.principal.id,
                'context': getPath(instance.context)}
 def testGetPath(self):
     from zope.traversing.api import getPath
     self.assertEqual(
         getPath(self.item),
         u'/folder/item'
         )
Exemple #28
0
    def update(self):
        name = self.name
        request = self.request
        context = self.form.context

        self.auth = getUtility(IAuthentication)

        key = u'%s:%s'%(getPath(context), name)
        self.sessionKey = key
        self.selectedName = u'%s-selectedItem'%name

        super(BasePrincipalWidget, self).update()

        tp = []
        if IUserField.providedBy(self.field):
            tp = ('user',)
        elif IGroupField.providedBy(self.field):
            tp = ('group',)
        else:
            tp = ('user', 'group')

        # search text
        data = ISession(request)[SESSIONKEY]
        if '%s-empty-marker'%name not in request and key in data:
            del data[key]

        if u'%s.searchButton'%name in request:
            searching = True
            searchtext = request.get(u'%s.searchText'%name, u'')
            data[key] = (searchtext, True)
            if searchtext:
                try:
                    principals = searchPrincipals(
                        tp, searchableText = searchtext)
                except:
                    principals = []
            else:
                principals = []
        elif u'%s.searchClear'%name in request:
            if key in data:
                del data[key]
            searchtext = u''
            searching = False
            principals = searchPrincipals(tp)
        else:
            searchtext, searching = data.get(key, (u'', False))
            if searchtext:
                try:
                    principals = searchPrincipals(
                        tp, searchableText = searchtext)
                except:
                    principals = []
            else:
                principals = searchPrincipals(tp)

        self.searching = searching
        self.searchtext = searchtext

        self.principals = SessionBatch(
            principals, size=self.pageSize,
            context=context, request=request, prefix=name,
            queryparams = {'%s-empty-marker'%self.name: '1'})
Exemple #29
0
def Context(object, instance, *args, **kw):
    return {'context': getPath(instance.context)}
Exemple #30
0
 def _items(self):
     """return all items and their path (for testing only!)"""
     return [(uid, getPath(ref())) for uid, ref in self.context.items()]
    def render(self, name):
        schema = self.context.schema
        sourcename = getName(self.context)
        sourcepath = getPath(self.context)
        setUpWidgets(self, schema, IInputWidget, prefix=name+'.field')
        html = []

        # add sub title for source search field
        html.append('<h4>%s</h4>' % sourcename)

        # start row for path display field
        html.append('<div class="row">')

        # for each source add path of source
        html.append('  <div class="label">')
        label = translate(source_label, context=self.request)
        title = translate(source_title, context=self.request)
        html.append('    <label for="%s" title="%s">' % (sourcename, title))
        html.append('      %s' % label)
        html.append('    </label>')
        html.append('  </div>')
        html.append('  <div class="field">')
        html.append('      %s' % sourcepath)
        html.append('  </div>')
        html.append('</div>')

        # start row for search fields
        html.append('<div class="row">')

        for field_name, field in getFieldsInOrder(schema):
            widget = getattr(self, field_name+'_widget')

            # for each field add label...
            html.append('  <div class="label">')
            html.append('    <label for="%s" title="%s">'
                        % (widget.name, widget.hint))
            html.append('      %s' % widget.label)
            html.append('    </label>')
            html.append('  </div>')

            # ...and field widget
            html.append('  <div class="field">')
            html.append('    %s' % widget())

            if widget.error():
                html.append('    <div class="error">')
                html.append('      %s' % widget.error())
                html.append('    </div>')
            html.append('  </div>')
        # end row
        html.append('</div>')

        # add search button for search fields
        html.append('<div class="row">')
        html.append('  <div class="field">')
        html.append('    <input type="submit" name="%s" value="%s" />'
                     % (name+'.search',
                        translate(search_label, context=self.request)))
        html.append('  </div>')
        html.append('</div>')

        return '\n'.join(html)
Exemple #32
0
def getLocationForCache(obj):
    """Returns the location to be used for caching the object or ``None``."""
    try:
        return getPath(obj)
    except (ComponentLookupError, TypeError):
        return None
Exemple #33
0
    def __call__(self, object, instance, *args, **kw):
        context = instance.context

        return {'context': getPath(context),
                'permissions': tuple(((p, checkPermission(p, context)) for p \
                                in self.permissions))}
Exemple #34
0
def milestoneSearchable(milestone):
    return api.traverse(getSite(), api.getPath(removeAllProxies(milestone)))
Exemple #35
0
 def getRelativePaths(self):
     return [getPath(self.context)]