def __init__(self, field_name, widget_title, errors=None): """Initialize Error `errors` is a ``ValidationError`` or a list of ValidationError objects """ UserError.__init__(self, field_name, widget_title, errors) self.field_name = field_name self.widget_title = widget_title self.errors = errors
def checkName(self, name, object): # ObjectManager can only deal with ASCII names. Specially # ObjectManager._checkId can only deal with strings. try: name = name.encode('ascii') except UnicodeDecodeError: raise UserError("Id must contain only ASCII characters.") try: self.context._checkId(name, allow_dup=False) except BadRequest as e: msg = ' '.join(e.args) or "Id is in use or invalid" raise UserError(msg)
def add(self, category_set): name = category_set.title if name in self.context: raise UserError(_('categoryset-duplication-error', u"Category Set named ${title} already exists!", mapping = {'title': name})) self.context[name] = category_set
def chooseName(self, name, object): if not name: name = object.__class__.__name__ else: if PY2: try: name = name.encode('ascii') except UnicodeDecodeError: raise UserError("Id must contain only ASCII characters.") dot = name.rfind('.') if dot >= 0: suffix = name[dot:] name = name[:dot] else: suffix = '' n = name + suffix i = 0 while True: i += 1 try: self.context._getOb(n) except (AttributeError, KeyError): break n = name + '-' + str(i) + suffix # Make sure the name is valid. We may have started with # something bad. self.checkName(n, object) return n
def action(self, type_name='', id=''): if not type_name: raise UserError(_(u"You must select the type of object to add.")) if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if queryMultiAdapter((self, self.request), name=view_name) is not None: url = "%s/%s=%s" % (absoluteURL(self, self.request), type_name, id) self.request.response.redirect(url) return if not self.contentName: self.contentName = id factory = getUtility(IFactory, type_name) content = factory() notify(ObjectCreatedEvent(content)) self.add(content) self.request.response.redirect(self.nextURL())
def oidIsValid(arg_oid): """ check the arg_oid for valid oid string """ try: oid = str(arg_oid) uid = oid[:-1] crc = oid[-1] icrc_cmp = 0 int_list = [int(i, 16) for i in uid] for i in int_list: icrc_cmp ^= i crc_cmp = u"%x" % icrc_cmp if crc != crc_cmp: raise UserError(_("Oid is not correct.")) except: raise UserError(_("Oid is not correct.")) return True
def add(self, obj): name = obj.interface.__module__ + '.' + obj.interface.__name__ try: self.context[name] = obj except DuplicationError: raise UserError( _('categorizableitemdescrption-add-duplication-error', u"Interface already defined."))
def signUp(self, login, title, password, confirmation): if confirmation != password: raise UserError( _('password-confirmation-error', u"Password and confirmation didn't match")) folder = self._signupfolder() if login in folder: raise UserError( _('duplicate-login-error', u"This login has already been chosen.")) principal_id = folder.signUp(login, password, title) role_manager = IPrincipalRoleManager(self.context) role_manager = removeSecurityProxy(role_manager) for role in folder.signup_roles: role_manager.assignRoleToPrincipal(role, principal_id) self.request.response.redirect("@@welcome.html")
def checkName(self, name, content): if isinstance(name, str): name = unicode(name) elif not isinstance(name, unicode): raise TypeError("Invalid name type", type(name)) if u'-' in name: # valueKey() return True raise UserError("Invalid name for SQLAlchemy object")
def checkName(self, name, object): """Limit ids Ids can only contain printable, non-space, 7-bit ASCII strings: >>> from zope.app.authentication.idpicker import IdPicker >>> IdPicker({}).checkName(u'1', None) True >>> IdPicker({}).checkName(u'bob', None) True >>> IdPicker({}).checkName(u'bob\xfa', None) ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... UserError: Ids must contain only printable 7-bit non-space ASCII characters >>> IdPicker({}).checkName(u'big bob', None) ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... UserError: Ids must contain only printable 7-bit non-space ASCII characters Ids also can't be over 100 characters long: >>> IdPicker({}).checkName(u'x' * 100, None) True >>> IdPicker({}).checkName(u'x' * 101, None) Traceback (most recent call last): ... UserError: Ids can't be more than 100 characters long. """ NameChooser.checkName(self, name, object) if not ok(name): raise UserError( _("Ids must contain only printable 7-bit non-space" " ASCII characters")) if len(name) > 100: raise UserError(_("Ids can't be more than 100 characters long.")) return True
def getData(self): charset = extractCharset(self.context.contentType) try: return { 'contentType': self.context.contentType, 'data': self.context.data.decode(charset) } except LookupError: msg = _( "The character set specified in the content type" " ($charset) is not supported.", mapping={'charset': charset}) raise UserError(msg) except UnicodeDecodeError: msg = _( "The character set specified in the content type" " ($charset) does not match file content.", mapping={'charset': charset}) raise UserError(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 changePassword(self, title, password=None, confirmation=None): if confirmation != password: raise UserError( _('password-confirmation-error', u"Password and confirmation didn't match")) folder = self._signupfolder() pau = getUtility(IAuthentication) info = folder.principalInfo( self.request.principal.id[len(pau.prefix):]) if info is None: raise UserError( _( 'unkown-accoount-error', u"Can only change the title and password of users who signed up." )) folder.changePasswordTitle(info.login, password, title) self.request.response.redirect(".")
def update(self): # assert that there are no other classification processes if findWorkItemsForItemAndProcessId(self.context, 'quotationtool.reclassify') or \ findWorkItemsForItemAndProcessId(self.context, 'quotationtool.classify'): raise UserError( _(u"This database item is subject of a classification task already. It must be finished before a new classification process is started." )) super(ReclassificationForm, self).update() self.updateAttributionSubForm() if self.checkPermission(): self.info = self.info_for_editors
def addSiteManager(self): """Convert a possible site to a site >>> from zope.traversing.interfaces import IContainmentRoot >>> from zope.interface import implements >>> class PossibleSite(object): ... implements(IContainmentRoot) ... def setSiteManager(self, sm): ... from zope.interface import directlyProvides ... directlyProvides(self, zope.component.interfaces.ISite) >>> folder = PossibleSite() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() Now we'll make our folder a site: >>> MakeSite(folder, request).addSiteManager() Now verify that we have a site: >>> zope.component.interfaces.ISite.providedBy(folder) 1 Note that we've also redirected the request: >>> request.response.getStatus() 302 >>> request.response.getHeader('location') '++etc++site/@@SelectedManagementView.html' If we try to do it again, we'll fail: >>> MakeSite(folder, request).addSiteManager() Traceback (most recent call last): ... UserError: This is already a site """ if zope.component.interfaces.ISite.providedBy(self.context): raise UserError(_(u'This is already a site')) # We don't want to store security proxies (we can't, # actually), so we have to remove proxies here before passing # the context to the SiteManager. bare = removeSecurityProxy(self.context) sm = LocalSiteManager(bare) self.context.setSiteManager(sm) self.request.response.redirect( "++etc++site/@@SelectedManagementView.html")
def getContent(self): comment_id = self.request.form.get('id', None) try: comment_id = int(comment_id) intids = zope.component.getUtility(IIntIds, context=self.context) self.comment = intids.queryObject(id, default=None) if not interfaces.IComment.providedBy(self.comment): raise Exception except: raise UserError(_(u"Invalid object ID")) return self.comment
def __init__(self, context, request): super(SingleCommentPagelet, self).__init__(context, request) id = request.form.get('id', None) try: id = int(id) intids = zope.component.getUtility(IIntIds, context=self.context) self.comment = intids.queryObject(id, default=None) if not interfaces.IComment.providedBy(self.comment): raise Exception except: raise UserError(_(u"Invalid object ID"))
def fields(self): helper_widget = zope.component.getMultiAdapter( (interfaces.IBiblatexEntry['entry_type'], self.request), IFieldWidget) helper_widget.name = self.prefix + 'widgets.entry_type' if not helper_widget.name in self.request.form: raise UserError( _("You have to choose an entry type." + unicode(self.request.form))) helper_widget.update() _type = helper_widget.value[0] # we get a list from request.form try: interfaces.IBiblatexEntry['entry_type'].validate(_type) except Exception: raise UserError(_("Invalid entry type.")) self.type = getEntryTypeSafely(_type) flds = ('entry_type', ) flds += getRequiredTuple(self.type.required) flds += getTuple(self.type.optional) flds += self.more_fields return field.Fields(interfaces.IBiblatexEntry).select(*flds)
def selectObjectToView(self): obj = None if 'oid' not in self.request: obj = self.findClosestPersistent() # Sanity check: if we're running in standalone mode, # self.context is a Folder in the just-created MappingStorage, # which we're not interested in. if obj is not None and obj._p_jar is not self.jar: obj = None if obj is None: if 'oid' in self.request: try: oid = int(self.request['oid'], 0) except ValueError: raise UserError('OID is not an integer: %r' % self.request['oid']) else: oid = self.getRootOid() try: obj = self.jar.get(p64(oid)) except POSKeyError: raise UserError('There is no object with OID 0x%x' % oid) return obj
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 action(self, type_name='', id=''): if not type_name: raise UserError(_(u"You must select the type of object to add.")) if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if queryMultiAdapter((self, self.request), name=view_name) is not None: url = "%s/%s=%s" % ( absoluteURL(self, self.request), type_name, id) self.request.response.redirect(url) return if not self.contentName: self.contentName = id # TODO: If the factory wrapped by LocationProxy is already a Proxy, # then ProxyFactory does not do the right thing and the # original's checker info gets lost. No factory that was # registered via ZCML and was used via addMenuItem worked # here. (SR) factory = getUtility(IFactory, type_name) if not type(factory) is zope.security.checker.Proxy: factory = LocationProxy(factory, self, type_name) factory = zope.security.checker.ProxyFactory(factory) content = factory() # Can't store security proxies. # Note that it is important to do this here, rather than # in add, otherwise, someone might be able to trick add # into unproxying an existing object, content = removeSecurityProxy(content) notify(ObjectCreatedEvent(content)) self.add(content) self.request.response.redirect(self.nextURL())
def fields(self): # use a widget to get the entry type from the request helper_widget = zope.component.getMultiAdapter( (interfaces.IBiblatexEntry['entry_type'], self.request), IFieldWidget) helper_widget.name = self.prefix + 'widgets.entry_type' if helper_widget.name in self.request.form: helper_widget.update() _type = helper_widget.value[0] # we get a list from request.form try: interfaces.IBiblatexEntry['entry_type'].validate(_type) except Exception: raise UserError( _("Wrong entry type: ${TYPE}", mapping={'TYPE': _type})) else: _type = getattr(self.context, 'entry_type') self.type = getEntryTypeSafely(_type) flds = getRequiredTuple(self.type.required) + ('entry_type', ) return field.Fields(interfaces.IBiblatexEntry).select(*flds)
def checkName(self, name, object): try: self.context._checkId(name, allow_dup=False) except BadRequest as e: msg = ' '.join(e.args) or "Id is in use or invalid" raise UserError(msg)