def getMenuLink(self, node): """Return the HTML link of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, Directive): ns = getParent(obj) apidoc_url = findAPIDocumentationRootURL(self.context, self.request) return '%s/ZCML/%s/%s/index.html' % ( apidoc_url, getName(ns), getName(obj)) return None
def getMenuLink(self, node): """Return the HTML link of the node that is displayed in the menu.""" obj = node.context apidoc_url = findAPIDocumentationRootURL(self.context, self.request) if isinstance(obj, Utility): iface = getParent(obj) return '%s/Utility/%s/%s/index.html' % (apidoc_url, getName(iface), getName(obj)) if isinstance(obj, UtilityInterface): return '%s/Interface/%s/index.html' % (apidoc_url, getName(obj))
def update(self): if 'DONE' in self.request: url = absoluteURL(self.context, self.request) self.request.response.redirect(url) elif 'form-submitted' in self.request: for demo in self.context.values(): name = 'delete.%s' % demo.__name__ if name in self.request: del self.context[demo.__name__] return old_pos, new_pos = 0, 0, False for demo in self.context.values(): old_pos += 1 name = getName(demo) if 'pos.'+name not in self.request: continue new_pos = int(self.request['pos.'+name]) if new_pos != old_pos: break old_pos, new_pos = old_pos-1, new_pos-1 keys = list(self.context.keys()) moving = keys[old_pos] keys.remove(moving) keys.insert(new_pos,moving) self.context.updateOrder(keys)
def edit(self, email=None, lastName=None, firstName=None, userId=None, password=None, groups=[]): """ """ obj = self.context if email: obj.email = email if firstName: obj.firstName = firstName if lastName: obj.lastName = lastName if userId: obj.userId = userId if password: obj.password = password if groups is not None: name = getName(obj) gs = self.context.getYeepa().getGroupSource() oldGroups = self.context.getGroupNames() for g in oldGroups: if g not in groups: gs.getGroup(g).removeMember(name) for g in groups: if g not in oldGroups: gs.getGroup(g).addMember(name) return 'OK'
def getMembers(self): """ """ userSource = self.context.getYeepa().getUserSource() name = getName(self.context) users = [u for u in userSource.getUsers(name)] return sorted((userAsDict(user) for user in users), key=lambda x: x['nickName'])
def pasteObjectLinks(self): """Paste oject links in the user clipboard to the container """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'copy': linker = IObjectLinker(removeAllProxies(obj)) try: linker.linkTo(target) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(getName(obj)) if moved: clipboard.clearContents() if not_pasteable_ids: abort() IStatusMessage(self.request).add( _("The given name(s) %s is / are already being used" % ( str(not_pasteable_ids))), 'error')
def setBody(self, body): """ """ name = getName(self.context) if name and identPattern in body: body = body.replace(identPattern, name) self.context.body = body return 'OK'
def getContextHelpTopic(self): """Retrieve a help topic based on the context of the help namespace. If the context is a view, try to find a matching help topic for the view and its context. If no help topic is found, try to get a help topic for the context only. If the context is not a view, try to retrieve a help topic based on the context. If nothing is found, return the onlinehelp root topic """ if self.topic is not None: return self.topic onlinehelp = self.context help_context = onlinehelp.context self.topic = None if IBrowserView.providedBy(help_context): # called from a view self.topic = getTopicFor(getParent(help_context), getName(help_context)) if self.topic is None: # nothing found for view try context only self.topic = getTopicFor(getParent(help_context)) else: # called without view self.topic = getTopicFor(help_context) if self.topic is None: self.topic = onlinehelp return self.topic
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 update(self): if 'DONE' in self.request: url = absoluteURL(self.context, self.request) self.request.response.redirect(url) elif 'form-submitted' in self.request: for demo in self.context.values(): name = 'delete.%s' % demo.__name__ if name in self.request: del self.context[demo.__name__] return old_pos, new_pos = 0, 0, False for demo in self.context.values(): old_pos += 1 name = getName(demo) if 'pos.' + name not in self.request: continue new_pos = int(self.request['pos.' + name]) if new_pos != old_pos: break old_pos, new_pos = old_pos - 1, new_pos - 1 keys = list(self.context.keys()) moving = keys[old_pos] keys.remove(moving) keys.insert(new_pos, moving) self.context.updateOrder(keys)
def getEvaluationsOfEvaluator(self, evaluator): """See interfaces.IEvaluations""" result = [(name, ev) for name, ev in self.items() if ev.evaluator == evaluator] result = Evaluations(result) location.locate(result, getParent(self), getName(self)) return result
def asDictionary(session): return {'ident': str(getName(session)), 'title': session.title, 'type': 'assessment', 'sessionFormat': session.sessionFormat, 'state': session.state, 'duration': [session.duration, session.durationUnit]}
def update_object(obj, data, includeOnly=None): logUpdate = data.get('_log_update', True) ident = (data.get('_identifier') or getattr(obj, 'identifier', getName(baseObject(obj)))) changedValues = {} for attr, nv in data.items(): if attr.startswith('_'): continue if includeOnly is not None and attr not in includeOnly: continue if isinstance(nv, Error): logger.warn('update_object error: %s: %s %s' % (ident, attr, nv)) return 'error' if nv is _invalid: continue ov = getattr(obj, attr) if nv != ov: changedValues[attr] = (ov, nv) setattr(obj, attr, nv) if changedValues: if logUpdate: logger.info('update_object %s: %s' % (ident, changedValues)) # TODO: notify(ObjectModifiedEvent()) return 'updated' return None
def subItems(self): """Collect all tree items for the given context.""" items = [] keys = [] append = items.append if IReadContainer.providedBy(self.context): try: keys = list(self.context.keys()) except(Unauthorized, Forbidden): return items else: return items counter = 1 for name in keys: # Only include items we can traverse to subItem = api.traverse(self.context, name, None) if subItem is not None: append((api.getName(subItem), subItem, self._hasSubItems(subItem))) counter += 1 if counter == self.maxItems: # add context which should support a item listing view with # batch lenght = len(keys) - self.maxItems default = '[%s more items...]' % lenght name = zope.i18n.translate( _('[${lenght} more items...]', mapping={'lenght':lenght}), context=self.request, default=default) append((name, self.context, False)) break return items
def userAsDict(user): #return dict(ident=getName(user), nickName=user.nickName, return dict(ident=getName(user), nickName=user.nickName, title=user.title, email=user.email, userId=user.userId, firstName=user.firstName, lastName=user.lastName, groups=sorted(user.getGroupNames()), )
def getMenuTitle(self, node): """Return the title of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, UtilityInterface): return getName(obj).split('.')[-1] if obj.name == NONAME: return 'no name' return obj.name
def getEvaluationsForRequirement(self, req, recurse=True): """See interfaces.IEvaluations""" requirements = getRequirementList(req, recurse) result = [(name, ev) for name, ev in self.items() if ev.requirement in requirements] result = Evaluations(result) location.locate(result, getParent(self), getName(self)) return result
def __call__(self): filename = getName(self.context) + '.pdf' response = self.request.response response.setHeader('Content-Disposition', 'attachment; filename=%s' % filename) response.setHeader('Content-Type', 'application/pdf') return getMultiAdapter((self.context, self.request), IPDFPresentation)
def getItems(self, topic=None): """ Return a sequence of dictionaries for all items. """ return sorted([{'ident': getName(item), 'title': self.getItemTitle(item), 'dimensions': item.getImageSize(), 'size': item.getSize()} for item in self.context.values()], lambda a, b: cmp(a['title'], b['title']))
def getMenuTitle(self, node): """Return the title of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, Namespace): name = obj.getShortName() if name == 'ALL': return 'All Namespaces' return name return getName(obj)
def getScripts(self): """ Return a list of dictionaries with the scripts in this script container. """ scripts = self.context.getItems() return [dict(name=getName(s), title=s.title or u'', parameters=s.parameters or u'') for s in scripts]
def asDictionary(session): return { 'ident': str(getName(session)), 'title': session.title, 'type': 'assessment', 'sessionFormat': session.sessionFormat, 'state': session.state, 'duration': [session.duration, session.durationUnit] }
def getItems(self, topic=None): """ Return a sequence of dictionaries for all items. """ return sorted([{ 'ident': getName(item), 'title': self.getItemTitle(item), 'dimensions': item.getImageSize(), 'size': item.getSize() } for item in self.context.values()], lambda a, b: cmp(a['title'], b['title']))
def getScripts(self): """ Return a list of dictionaries with the scripts in this script container. """ scripts = self.context.getItems() return [ dict(name=getName(s), title=s.title or u'', parameters=s.parameters or u'') for s in scripts ]
def userAsDict(user): #return dict(ident=getName(user), nickName=user.nickName, return dict( ident=getName(user), nickName=user.nickName, title=user.title, email=user.email, userId=user.userId, firstName=user.firstName, lastName=user.lastName, groups=sorted(user.getGroupNames()), )
def getId(self): """Return the id of the field as it is defined for the interface utility. Example:: >>> from tests import getInterfaceDetails >>> details = getInterfaceDetails() >>> details.getId() 'IFoo' """ return getName(self.context)
def findByIds(self, ids): """Do a find for the `ids` listed in `ids`, which is a string.""" finder = IFind(self.context) ids = ids.split() # if we don't have any ids listed, don't search at all if not ids: return [] request = self.request result = [] for object in finder.find([SimpleIdFindFilter(ids)]): url = absoluteURL(object, request) result.append({'id': getName(object), 'url': url}) return result
def findByIds(self, ids): """Do a find for the `ids` listed in `ids`, which is a string.""" finder = IFind(self.context) ids = ids.split() # if we don't have any ids listed, don't search at all if not ids: return [] request = self.request result = [] for object in finder.find([SimpleIdFindFilter(ids)]): url = absoluteURL(object, request) result.append({ 'id': getName(object), 'url': url}) return result
def __call__(self): ids = getUtility(IIntIds) data = [] for name, link in IAttachmentsExtension(self.context).items(): if ILink.providedBy(link) and link: title = link.title or getName(link) data.append((title, link.url)) data.sort() js_encoded = encoder.encode(data) return """tinyMCELinkList = new Array(%s);""" % js_encoded[1:-1]
def __call__(self): ids = getUtility(IIntIds) data = [] for name, image in IAttachmentsExtension(self.context).items(): if IImage.providedBy(image) and image: id = ids.queryId(removeAllProxies(image)) title = image.title or getName(image) data.append((title, '@@content.attachment/%s' % id)) data.sort() js_encoded = encoder.encode(data) return """tinyMCEImageList = new Array(%s);""" % js_encoded[1:-1]
def __call__(self): ids = getUtility(IIntIds) data = [] for name, file in IAttachmentsExtension(self.context).items(): if IFile.providedBy(file) and file: id = ids.queryId(removeAllProxies(file)) title = file.title or getName(file) data.append((title, '++attachment++%s' % id)) data.sort() js_encoded = encoder.encode(data) return """tinyMCEMediaList = new Array(%s);""" % js_encoded[1:-1]
def activities(self): pos = 0 for activity in list(self.context.values()): pos += 1 url = absoluteURL(activity, self.request) if interfaces.ILinkedColumnActivity.providedBy(activity): url += '/editLinkedColumn.html' yield { 'name': getName(activity), 'title': activity.title, 'url': url, 'pos': pos, 'deployed': self.context.deployed }
def handlePaste(self, action): items = self.clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = api.traverse(self.context, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) try: mover.moveTo(self.context) moved = True except DuplicateIDError: duplicated_id = True elif item['action'] == 'copy': copier = IObjectCopier(obj) try: copier.copyTo(self.context) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(api.getName(obj)) if moved: # Clear the clipboard if we do a move, but not if we only do a copy self.clipboard.clearContents() if not_pasteable_ids != []: # Show the ids of objects that can't be pasted because # their ids are already taken. # TODO Can't we add a 'copy_of' or something as a prefix # instead of raising an exception ? transaction.doom() raise UserError( _("The given name(s) %s is / are already being used" % ( str(not_pasteable_ids)))) else: # we need to update the table rows again, otherwise we don't # see the new item in the table self.updateAfterActionExecution() self.status = self.pasteSucsessMessage
def getItems(self, topic=None, typeName='content'): """ Return a sequence of dictonaries for all selected items. """ topics = topic and [topic] or None result = [] for node in self.context.getNodes(topics, typeName): entry = dict(ident=getName(node), title=node.title, body=node.body, topics=sorted(node.topics), references=sorted(node.references)) if typeName == 'reference': entry['pages'] = node.pages entry['url'] = node.url result.append(entry) return sorted(result, lambda a, b: cmp(a['title'], b['title']))
def pasteObjects(self): """Paste ojects in the user clipboard to the container """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) try: mover.moveTo(target) moved = True except DuplicateIDError: duplicated_id = True elif item['action'] == 'copy': copier = IObjectCopier(obj) try: copier.copyTo(target) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(getName(obj)) if moved: # Clear the clipboard if we do a move, but not if we only do a copy clipboard.clearContents() if not_pasteable_ids != []: # Show the ids of objects that can't be pasted because # their ids are already taken. # TODO Can't we add a 'copy_of' or something as a prefix # instead of raising an exception ? raise UserError( _("The given name(s) %s is / are already being used" %( str(not_pasteable_ids))))
def pasteObjects(self): """Paste ojects in the user clipboard to the container """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) try: mover.moveTo(target) moved = True except DuplicateIDError: duplicated_id = True elif item['action'] == 'copy': copier = IObjectCopier(obj) try: copier.copyTo(target) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(getName(obj)) if moved: # Clear the clipboard if we do a move, but not if we only do a copy clipboard.clearContents() if not_pasteable_ids != []: # Show the ids of objects that can't be pasted because # their ids are already taken. # TODO Can't we add a 'copy_of' or something as a prefix # instead of raising an exception ? raise UserError( _("The given name(s) %s is / are already being used" % (str(not_pasteable_ids))))
def createUser(self, nickName, email=None, userId=None, password=None, lastName=None, firstName=None, groups=[]): """ """ obj = self.context.createUser(nickName) obj.email = email or u'' obj.userId = userId or u'' obj.password = password or u'' obj.firstName = firstName or u'' obj.lastName = lastName or u'' name = getName(obj) if groups: gs = self.context.getYeepa().getGroupSource() for g in groups: group = gs.getGroup(g) if group is not None: group.addMember(name) return name
class Index(mars.view.PageletView): grok.context(IRootFolder) grok.require(permissions.MANAGESITE) title = _("Tree Fern Web Site Demo") columns = ( table.CheckboxColumn(_('Sel')), column.GetterColumn(_('Id'), lambda item, f: api.getName(item), table.link('index', _('View'))), column.GetterColumn(_('Title'), lambda item, f: item.title, table.link('edit', _('Edit'))), column.GetterColumn(_('Created On'), table.getCreatedDate), column.GetterColumn(_('Modified On'), table.getModifiedDate), ) status = None def table(self): formatter = AlternatingRowFormatter(self.context, self.request, self.items, columns=self.columns) formatter.widths = [25, 50, 300, 100, 100] formatter.cssClasses['table'] = 'list' return formatter() def update(self): self.items = [ obj for obj in self.context.values() if interfaces.IWebSite.providedBy(obj) ] if 'ADD' in self.request: self.request.response.redirect('add') if 'DELETE' in self.request: if self.request.get('confirm_delete') != 'yes': self.status = _('You did not confirm the deletion correctly.') return if 'selected' in self.request: for id in self.request['selected']: self.items.remove(self.context[id]) del self.context[id] self.status = _('Sites were successfully deleted.') else: self.status = _('No sites were selected.')
def update(self): if 'DELETE' in self.request: for name in self.request.get('delete', []): del self.context[name] elif 'form-submitted' in self.request: old_pos, new_pos = 0, 0, False for activity in self.context.values(): old_pos += 1 name = getName(activity) if 'pos.' + name not in self.request: continue new_pos = int(self.request['pos.' + name]) if new_pos != old_pos: break old_pos, new_pos = old_pos - 1, new_pos - 1 keys = list(self.context.keys()) moving = keys[old_pos] keys.remove(moving) keys.insert(new_pos, moving) self.context.updateOrder(keys)
def update(self): if 'DELETE' in self.request: for name in self.request.get('delete', []): del self.context[name] elif 'form-submitted' in self.request: old_pos, new_pos = 0, 0, False for activity in self.context.values(): old_pos += 1 name = getName(activity) if 'pos.'+name not in self.request: continue new_pos = int(self.request['pos.'+name]) if new_pos != old_pos: break old_pos, new_pos = old_pos-1, new_pos-1 keys = list(self.context.keys()) moving = keys[old_pos] keys.remove(moving) keys.insert(new_pos,moving) self.context.updateOrder(keys)
def update(self): self.person = IPerson(self.request.principal, None) if self.person is None: # XXX ignas: i had to do this to make the tests pass, # someone who knows what this code should do if the user # is unauthenticated should add the relevant code raise Unauthorized("You don't have the permission to do this.") if 'DELETE' in self.request: for name in self.request.get('delete', []): del self.context[name] elif 'form-submitted' in self.request: old_pos = 0 for activity in self.context.values(): old_pos += 1 name = getName(activity) if 'pos.' + name not in self.request: continue new_pos = int(self.request['pos.' + name]) if new_pos != old_pos: self.context.changePosition(name, new_pos - 1)
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
def name(self): return getName(self.context)
def title_or_name(self): try: return getattr(self, 'title', '') or getName(self.context) except Unauthorized: return getName(self.context)
def createItem(self, title=u'', format=''): """ """ obj = self.context.createItem() obj.contentType = format obj.title = title return getName(obj)
def createAssessment(self, title=u'', topics=[]): """ """ obj = self.context.createItem(title=title, topics=topics) return getName(obj)
def getName(item): # probably not IPhysicallyLocatable but still could have a __name__ try: return api.getName(item) except TypeError as e: return item.__name__
def testGetName(self): from zope.traversing.api import getName self.assertEqual(getName(self.item), 'item')
def testGetNameOfRoot(self): from zope.traversing.api import getName self.assertEqual( getName(self.root), u'', )
def __call__(self, *args, **kwargs): """See interfaces.IEvaluationsQuery""" result = Evaluations(self._query(*args, **kwargs)) location.locate(result, getParent(self.context), getName(self.context)) return result
def anchor(value, item, formatter): site = hooks.getSite() url = '%s/members/%s/%s' % (absoluteURL( site, formatter.request), api.getName(item), view) return u'<a href="%s" title="%s">%s</a>' % (url, title, value)
def getGroups(self): """ """ return sorted( dict(ident=getName(group), title=group.title) for group in self.context.getGroups())