def getMemberInfo(self, id): member = self.context[id] try: principal = self.auth.getPrincipal(member.__name__) except PrincipalLookupError: return profile = IPersonalProfile(principal, None) if profile is None: return space = profile.space if space is None: return info = { 'id': principal.id, 'spaceid': space.__name__, 'title': profile.title, 'avatar': profile.avatarUrl(self.request), 'joined': self.formatter.format(member.joined), 'approved': member.approved and \ _('Approved') or _('Not yet approved'), } return info
def __call__(self, settings, store_url, order_contents, template): portal = getPortal() pm = getToolByName(portal, 'portal_membership') user = pm.getAuthenticatedMember() if 'Anonymous' not in user.getRoles(): view_order = '''\ You can view the status of your order here ${store_url}/@@getpaid-order/${order_id} ''' kwargs = { 'view_order_information': view_order } temp = _(template, mapping=kwargs) template = translate(temp) kwargs = {'to_email': self.order.contact_information.email, 'from_name': settings.store_name, 'from_email': settings.contact_email, 'total_price': u"%0.2f" % self.order.getTotalPrice(), 'shipping_cost': u"%0.2f" % self.order.getShippingCost(), 'store_url': store_url, 'order_id': self.order.order_id, 'order_contents': order_contents, 'view_order_information': '' } msg = _(template, mapping=kwargs) return translate(msg)
def update(self): request = self.request if 'form.customize' in request: id = request.get('layoutId') if id in self.context.layouts: IStatusMessage(request).add( _(u'Layout already customized.'), 'error') return info = queryUtility(ILayoutInformation, id) if info is None: IStatusMessage(request).add(_(u"Can't find layout."), 'error') return source = info.layoutclass.template.read() pt = LayoutPageTemplate() pt.source = source self.context.setLayout(id, pt) IStatusMessage(request).add(_(u'Layout has been customized.')) self.redirect('%s/'%id) if 'form.back' in request: self.redirect('index.html')
def update(self): request = self.request context = self.context if 'form.add' in request: source = request.get('form.amazon.widget', '').strip() if not source: IStatusMessage(request).add(_("You can't add empty string.")) else: widgets = list(self.context.widgets) widgets.append(source) self.context.widgets = widgets IStatusMessage(request).add(_("Amazon widget has been added.")) elif 'form.widget.save' in request: idx = request.get('widgetIdx') source = request.get('form.widget', '').strip() if not source: IStatusMessage(request).add(_("You can't set empty string.")) else: widgets = list(self.context.widgets) widgets[idx] = source self.context.widgets = widgets IStatusMessage(request).add(_("Amazon widget has been saved.")) elif 'form.widget.remove' in request: idx = request.get('widgetIdx') widgets = list(self.context.widgets) del widgets[idx] self.context.widgets = widgets IStatusMessage(request).add(_("Amazon widget has been removed."))
def fullNumber(self, value): if IDraftedContent.providedBy(self): location = self.__parent__.getLocation() parents = filter(IUserManual.providedBy, [location] + getParents(location)) else: parents = filter(IUserManual.providedBy, getParents(self)) manual = parents[-1] numbers = map(int, value.split('.')) ct = getUtility(IContentType, name='content.usermanualpage') del self.__parent__[self.__name__] for number in numbers[0:-1]: try: manual = IOrder(manual).getByPosition(number) except KeyError: m = ct.create(_(u'Autocreated page'), _(u'Autocreated page description')) m.number = number ct.__bind__(manual).add(m) manual = m self.number = numbers[-1] manual[INameChooser(manual).chooseName(self.__name__, self)] = self IOrder(self.__parent__).rebuild() if IUserManualPage.providedBy(self.__parent__): return '%s.%s'%(self.__parent__.fullNumber, self.number) return str(self.number)
def update(self): super(ContentsNameColumn, self).update() # Given a sequence of tuples of old, new ids we rename if 'applyButton' in self.table.environ: ids = self.table.environ['activeIds'] newids = self.request.get("newIds", ()) renamed = False renamer = IContainerItemRenamer( removeAllProxies(self.table.context)) for oldid, newid in zip(ids, newids): if newid != oldid: try: # Exclude incorrect characters from new id validchars = "-_.%s%s" % ( string.lowercase, string.digits) newid = ''.join( c for c in newid.lower() if c in validchars) renamer.renameItem(oldid, newid) except DuplicationError: IStatusMessage(self.request).add( _('Item with this name already exists.'), 'error') return renamed = True ids[ids.index(oldid)] = newid if renamed: IStatusMessage(self.request).add(_('Items have been renamed.'))
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.'))
class PersonalAcknowledgementsWorkspaceFactory(object): component.adapts(IPersonalSpace) interface.implements(IPersonalAcknowledgementsWorkspaceFactory) name = u'Acknowledgements' title = _('Acknowledgements') description = _("Personal acknowledgements") weight = 9 def __init__(self, space): self.space = space def get(self): view = PersonalAcknowledgementsWorkspace() view.__parent__ = self.space return view install = get def uninstall(self): pass def isInstalled(self): return False def isAvailable(self): return True
def mapTypesVocabulary(context): return SimpleVocabulary(( SimpleTerm('HYBRID', 'HYBRID', _(u'Hybrid. This map type displays a transparent layer of major streets on satellite images.')), SimpleTerm('ROADMAP', 'ROADMAP', _(u'Roadmap. This map type displays a normal street map.')), SimpleTerm('SATELLITE', 'SATELLITE', _(u"Satellite. This map type displays satellite images.")), SimpleTerm('TERRAIN', 'TERRAIN', _(u"Terrain. This map type displays maps with physical features such as terrain and vegetation.")), ))
def __call__(self, field, value): if self.min is not None: if value < self.min: min_err = _(self.min_err, mapping={'val':value, 'min':self.min}) raise Invalid(field, min_err) if self.max is not None: if value > self.max: max_err = _(self.max_err, mapping={'val':value, 'max':self.max}) raise Invalid(field, max_err)
def msgEmptyTable(self): context = self.context if IWorkspaceContentType.providedBy(context): principal = context.__parent__.__parent__.principal else: principal = context.__parent__.principal if principal.id == self.request.principal.id: return _(u'You do not have any content.') else: return _(u'He/she does not have any content.')
def handleBan(self, action): request = self.request data, errors = self.extractData() if not data["principals"]: IStatusMessage(request).add(_(u"Please select member."), "warning") return self.context.ban(data["principals"]) IStatusMessage(request).add(_(u"Members has been banned.")) self.redirect(".")
def __call__(self, field, value): if self.min is not None: if len(value) < self.min: min_err = _('Shorter than minimum length ${min}', mapping={'min':self.min}) raise Invalid(field, min_err) if self.max is not None: if len(value) > self.max: max_err = _('Longer than maximum length ${max}', mapping={'max':self.max}) raise Invalid(field, max_err)
def validate(self, password): """ Validate password """ if len(password) < self.min_length: #return _('Password should be at least ${count} characters.', # mapping={'count': self.min_length}) return 'Password should be at least %s characters.'%\ self.min_length elif self.letters_digits and \ (password.isalpha() or password.isdigit()): return _('Password should contain both letters and digits.') elif self.letters_mixed_case and \ (password.isupper() or password.islower()): return _('Password should contain letters in mixed case.')
def getPrincipal(id=None): """ get current interaction principal """ if id is None: interaction = queryInteraction() if interaction is not None: for participation in interaction.participations: if participation.principal is not None: return participation.principal else: try: return getUtility(IAuthentication).getPrincipal(id) except PrincipalLookupError: return Principal('unknown', _('Unknown'), _('Unknown'), 'unknown', 'unknown')
def update(self): context = self.context request = self.request self.allowEdit = checkPermission('zojax.ModifyWikiContent', context) if 'returnToHistory' in request: return if 'revert' in request: rev = request.get('rev', u'') if rev not in context.history: IStatusMessage(request).add(_("Can't find revision."),'warning') else: revision = self.context.history[rev] revision.revert(request.principal.id) IStatusMessage(request).add(_('Wiki page has been reverted.')) self.redirect('index.html') return rev = request.get('rev', u'') history = context.history if rev in history: revId = int(rev) self.revId = revId+1 self.revTotal = len(self.context.history) self.revision = self.context.history[rev] profile = IPersonalProfile(self.revision.getPrincipal(), None) self.principal = getattr( profile, 'title', _('Unknown')) or _('Unknown') if revId > 0: diff = [] for line in history.diff(revId-1, revId): if line[:2] in ('??', '--', '++'): diff.append( '<span class="wiki-diff-tag">%s</span>'% cgi.escape(line[2:])) elif line[:1] == '+': diff.append( '<span class="wiki-diff-added">%s</span>'% cgi.escape(line[1:])) elif line[:1] == '-': diff.append( '<span class="wiki-diff-removed">%s</span>'% cgi.escape(line[1:])) self.diff = u'\n'.join(diff)
def handleUnban(self, action): request = self.request data, errors = self.extractData() uids = request.get("principal.users", ()) if not uids: IStatusMessage(request).add(_(u"Please select members."), "warning") return self.context.unban(uids) IStatusMessage(request).add(_(u"Members have been unbanned.")) self.redirect(".")
def update(self): context = self.context request = self.request id = context.id if 'form.button.accept' in request: if request.get('invitation') == id: invitation = getUtility( IInvitations).get(request.get('invitation')) if invitation is not None: invitation.accept() IStatusMessage(request).add( _('Invitation has been accepted.')) self.redirect(request.URL) return if 'form.button.reject' in request: if request.get('invitation') == id: invitation = getUtility( IInvitations).get(request.get('invitation')) if invitation is not None: invitation.reject() IStatusMessage(request).add( _('Invitation has been rejected.')) self.redirect(request.URL) return group = removeSecurityProxy(context.object) visible = checkPermission('zope.View', group) owner = IOwnership(context).owner profile = IPersonalProfile(owner, None) message = cgi.escape(context.message) message = message.replace(' ', ' ') message = message.replace('\n', '<br />') self.invitation = { 'id': id, 'title': group.title, 'description': group.description, 'created': IDCTimes(group).created, 'members': len(group.members), 'url': u'%s/'%absoluteURL(group, request), 'message': message, 'default': not visible or not bool(getattr(group, 'logo', None)), 'sender': getattr(profile, 'title', _('Unknown member'))}
def items(self): request = self.request auth = getUtility(IAuthentication) comments = getCatalog().search(contexts=(self.context,), approved=(True,))[:15] for comment in comments: if not comment: continue url = absoluteURL(comment.content, request) info = { 'link': '%s/'%url, 'description': comment.comment, 'guid': '%s/#comments%s'%(url, comment.__name__), 'pubDate': rfc822.formatdate(time.mktime(comment.date.timetuple())), 'isPermaLink': True} author = u'Unknown' try: principal = auth.getPrincipal(comment.author) profile = IPersonalProfile(principal) author = profile.title info['author'] = u'%s (%s)'%(profile.email, author) except PrincipalLookupError: pass info['title'] = _(u'by ${author} on ${content}', mapping={'author': author, 'content': comment.content.title}) yield info
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 items(self): request = self.request auth = getUtility(IAuthentication) discussion = IContentDiscussion(self.context) for idx in discussion: comment = discussion[idx] url = absoluteURL(comment.content, request) info = { 'link': '%s/'%url, 'description': comment.comment, 'guid': '%s/#comments%s'%(url, comment.__name__), 'pubDate': rfc822.formatdate(time.mktime(comment.date.timetuple())), 'isPermaLink': True} author = u'Unknown' try: principal = auth.getPrincipal(comment.author) profile = IPersonalProfile(principal) author = profile.title info['author'] = u'%s (%s)'%(profile.email, author) except PrincipalLookupError: pass info['title'] = _('by ${author}', mapping={'author': author}) yield info
def passwordSchemaValidator(field, appstruct): if appstruct['password'] and appstruct['confirm_password']: if appstruct['password'] != appstruct['confirm_password']: raise form.Invalid( field, _("Password and Confirm Password should be the same.")) passwordValidator(field, appstruct['password'])
def update(self): request = self.request context = removeAllProxies(self.context) query = dict(noSecurityChecks=True) if 'form.button.reindex' in request: catalog = context.catalog catalog.clear() for rid, record in context.records.items(): if record.object is None: context.remove(rid) for rid, record in context.records.items(): catalog.index_doc(rid, record) IStatusMessage(request).add( _('Activity catalog has been reindexed.')) if request.get('searchtype', 'all') != 'all': query['type'] = {'any_of': (request['searchtype'],)} results = context.search(**query) self.batch = Batch(results, size=20, context=context, request=request) self.auth = getUtility(IAuthentication) self.formatter = getFormatter(self.request, 'fancyDatetime', 'medium') self.voc = getUtility(IVocabularyFactory, 'acitivity.record.descriptions')(getSite())
def handleSend(self, action): request = self.request data, errors = self.extractData() if errors: IStatusMessage(request).add(self.formErrorsMessage, 'error') else: message = data['message'] members = self.context.members getPrincipal = getUtility(IAuthentication).getPrincipal invitations = getUtility(IInvitations) group = removeAllProxies(self.context) for pid in request.get('principal.users', ()): try: principal = getPrincipal(pid) except PrincipalLookupError: continue if not invitations.catalog.search( group, type = {'any_of': ('invitation.member',)}, principal = {'any_of': (pid,)}): removeSecurityProxy(members).invite(pid, message) IStatusMessage(request).add(_(u'Invitations have been sent.')) self.redirect('.')
def inviteHandler(self, action): data, errors = self.extractData() if errors: IStatusMessage(self.request).add( _('Please fix indicated errors.'), 'warning') else: invitation = getUtility(IPortalRegistration).invitePerson( self.request.principal.id, data['name'], data['email'], data['subject'], data['message']) template = getMultiAdapter((invitation, self.request), IMailTemplate) template.send((data['email'],)) IStatusMessage(self.request).add(_('Invitation has been sent.')) self.redirect('.')
def __set__(self, inst, value): field = self.__field.bind(inst) field.validate(value) if field.readonly and \ inst.__data__.get(self.__name, _marker) is not _marker: raise ValueError(self.__name, _(u'Field is readonly')) inst.__data__[self.__name] = value
def handleView(self, action): data, errors = self.extractData() if errors or not data['principal']: IStatusMessage(self.request).add( _(u'Please select principal.'), 'warning') else: self.redirect('%s/@@index.html'%data['principal'])
def update(self): super(ContentItem, self).update() item = IItem(self.context, None) if item is not None: self.title = item.title or _('[No title]') self.description = item.description self.item = item
def items(self): request = self.request results = self.context['members'].values() auth = getUtility(IAuthentication) for member in results: try: principal = auth.getPrincipal(member.__name__) except PrincipalLookupError: principal = None space = IPersonalSpace(principal, None) profile = IPersonalProfile(principal, None) image = getattr(profile, 'profileImage', None) if image and IImage.providedBy(image): w, h = image.width, image.height if w > 128: xscale = 128.0/w else: xscale = 1.0 if h > 128: yscale = 120.0/h else: yscale = 1.0 scale = xscale < yscale and xscale or yscale image = (int(round(w*scale)), int(round(h*scale))) default = False else: image = (128, 97) default = True info = { 'id': member.__name__, 'title': getattr(profile, 'title', _(u'Unknown')), 'description': getattr(principal, 'description', u''), 'manager': u'', 'personalspace': u'', 'joined': member.joined, 'imagex': image[0], 'imagey': image[1], 'default': default} if space is not None: info['manager'] = space.title info['personalspace'] = absoluteURL(space, self.request) info = { 'title': info['title'], 'description': info['description'], 'guid': info['personalspace'] or info['id'], 'pubDate': rfc822.formatdate(time.mktime( info['joined'].timetuple())), 'isPermaLink': True} if profile is not None: info['author'] = u'%s (%s)'%(profile.email, profile.title) yield info
def update(self): includeInplaceSource(jssource) request = self.request context = self.context context = IMembersAware(getSpace(context), None) if context is None: return notifications = [] for name, notification in getAdapters((self.context,), IContentNotification): notifications.append((notification.title, name, notification)) notifications.sort() self.notifications = [notification for title, name, notification in notifications] members = [] spaces = list(getUtility(ICatalog).searchResults( type={'any_of': ('content.space',)}, traversablePath={'any_of': [context]})) spaces.append(context) for space in spaces: for member in space.members.values(): principal = member.principal if principal is None or principal.id=='unknown': continue title = member.title position = -1 for pos, memb in enumerate(members): if member.title in memb: position = pos if position != -1: members[position][1]['spaces'].append(space.title) else: members.append((title, {'id': principal.id, 'title': title, 'spaces': [space.title] })) self.renderDict = self.createRenderDict(sorted(spaces, key=lambda sp: sp.title), members) self.members = [val[1] for val in members] if 'notifications.save' in request: checked = {} for id in request.get('notifications', ()): pid, nid = id.split(':', 1) data = checked.setdefault(nid, []) data.append(pid) for notification in self.notifications: data = checked.get(notification.type, []) for member in self.members: if member['id'] in data: notification.subscribe(member['id']) else: notification.unsubscribe(member['id']) IStatusMessage(request).add( _('Email notification subscriptions have been updated.'))
def __init__(self, regex, msg=None): if isinstance(regex, basestring): self.match_object = re.compile(regex) else: self.match_object = regex if msg is None: self.msg = _("String does not match expected pattern") else: self.msg = msg
def __setitem__(self, key, value): """ See zope.interface.common.mapping.IWriteMapping This is restriced depending on the value of the 'complete' and 'open_to_users' attribute. >>> from quotationtool.categorization.categoryset import CategorySet >>> from quotationtool.categorization.category import Category >>> from quotationtool.categorization import testing >>> from zope.security.management import newInteraction >>> interaction = newInteraction() >>> descriptions = testing.generateCategorizableItemDescriptions(root) >>> container = testing.generateCategoriesContainer(root) >>> catset = container['catset'] = CategorySet() >>> catset['cat1'] = Category() >>> catset.complete = True >>> catset['cat2'] = Category() Traceback (most recent call last): ... UserError: categoryset-setitem-error-complete >>> catset.complete = False >>> catset.open_to_users = False >>> catset['cat2'] = Category() """ if self.complete: raise UserError( _( 'categoryset-setitem-error-complete', u"The set of category labels is 'complete'. New category labels cannot be added. Sorry." )) if not self.open_to_users: interaction = getInteraction() if not interaction.checkPermission( 'quotationtool.categorization.EditCategory', self): raise UserError( _( 'categoryset-setitem-error-notopentousers', u"This set of category labels is not 'open to users'. You don't have the permission to add a new category label. Sorry." )) super(CategorySet, self).__setitem__(key, value)
def __call__(self, settings, store_url, order_contents, template): kwargs = {'to_email': settings.contact_email, 'from_name': settings.store_name, 'from_email': settings.contact_email, 'total_price': u"%0.2f" % self.order.getTotalPrice(), 'shipping_cost': u"%0.2f" % self.order.getShippingCost(), 'store_url': store_url, 'order_id': self.order.order_id, 'order_contents': order_contents, } msg = _(template, mapping=kwargs) return translate(msg)
class PersonalAcknowledgementsWorkspace(Location): interface.implements(IPersonalAcknowledgementsWorkspace) title = _('Acknowledgements') __name__ = u'personal-acknowledgements'
class AcknowledgementActivityRecord(ContentActivityRecord): interface.implements(IAcknowledgementActivityRecord, IContentActivityRecord) type = u'acknowledgement' verb = _('enable Acknowledgement')
class AcknowledgementActivityRecordDescription(object): interface.implements(IActivityRecordDescription) title = _(u'Acknowledgement') description = _(u'Acknowledgement was enabled for Content object.')