def update(self): status = '' container = IMutableSchema(self.context) request = self.request if 'DELETE' in request: if not 'ids' in request: self.errors = (_("Must select a field to delete"),) status = _msg_anErrorOccurred for id in request.get('ids', []): del container[id] elif 'MOVE_UP' in request or 'MOVE_DOWN' in request: up = request.get('MOVE_UP') down = request.get('MOVE_DOWN') name = up or down delta = up and -1 or 1 names = self.fieldNames() if name not in names: #TODO variable insertion must not be expanded until # after the translation... preferably use mapping here self.errors = (_("Invalid field name: %s" % name),) status = _msg_anErrorOccurred p = names.index(name) + delta try: self.context.moveField(name, p) except IndexError: #TODO variable insertion must not be expanded until # after the translation... preferably use mapping here self.errors = (_("Invalid position: %s" % p),) status = _msg_anErrorOccurred self.update_status = status return status
def __call__(self): """Render the current value """ if self._renderedValueSet(): value = self._data else: value = self.context.default if value == self.context.missing_value: value = self._translate(_("SourceDisplayWidget-missing", default="Nothing")) else: terms = zapi.getMultiAdapter( (self.source, self.request), zope.app.form.browser.interfaces.ITerms, ) try: term = terms.getTerm(value) except LookupError: value = self._translate(_("SourceDisplayWidget-invalid", default="Invalid value")) else: value = self.renderTermForDisplay(term) return value
class IReaderDirective(Interface): """ ZCML Directive that registers a naaya.ldapdump reader """ path = fields.Path( title=_("Path"), description=_("Path to configuration file for this dump"), required=True, )
class INaayaCallDirective(Interface): """ Call something """ factory = GlobalObject( title=_("Factory"), description=_("Call the given factory. That's all we do. Simple."), required=True, )
def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' content = self.adapted if Update in self.request: changed = False try: changed = applyWidgetsChanges(self, self.schema, target=content, names=self.fieldNames) # We should not generate events when an adapter is used. # That's the adapter's job. if changed and self.context is self.adapted: description = Attributes(self.schema, *self.fieldNames) notify(ObjectModifiedEvent(content, description)) except WidgetsError, errors: self.errors = errors status = _("An error occurred.") transaction.abort() else: setUpEditWidgets(self, self.schema, source=self.adapted, ignoreStickyValues=True, names=self.fieldNames) if changed: self.changed() formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') status = _("Updated on ${date_time}", mapping={'date_time': formatter.format(datetime.utcnow())})
def containerViews(_context, for_, contents=None, add=None, index=None, layer=IDefaultBrowserLayer): """Set up container views for a given content type.""" if for_ is None: raise ValueError("A for interface must be specified.") if contents is not None: from zope.app.menus import zmi_views page(_context, name='contents.html', permission=contents, for_=for_, layer=layer, class_=Contents, attribute='contents', menu=zmi_views, title=_('Contents')) if index is not None: page(_context, name='index.html', permission=index, for_=for_, layer=layer, class_=Contents, attribute='index') if add is not None: from zope.app.menus import zmi_actions viewObj = view(_context, name='+', layer=layer, menu=zmi_actions, title=_('Add'), for_=for_, permission=add, class_=Adding) viewObj.page(_context, name='index.html', attribute='index') viewObj.page(_context, name='action.html', attribute='action') viewObj()
def byteDisplay(size): if size == 0: return _('0 KB') if size <= 1024: return _('1 KB') if size > 1048576: return _('${size} MB', mapping={'size': '%0.02f' % (size / 1048576.0)}) return _('${size} KB', mapping={'size': '%d' % (size / 1024.0)})
def getViewTypeTitles(self): return { "browser": _("Browser"), "xmlrpc": _("XML-RPC"), "http": _("HTTP"), "ftp": _("FTP"), "other": _("Other"), }
def pack(self): """Do the packing!""" days = int(self.request.form.get('days', 0)) status = '' if 'PACK' in self.request: try: self.request.publication.db.pack(days=days) status = _('ZODB successfully packed.') except FileStorageError, err: status = _(err)
class INaayaContentDirective(Interface): """ Register a content """ 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, )
def handle_edit_action(self, action, data): if form.applyChanges(self.context, self.form_fields, data, self.adapters): zope.event.notify( zope.app.event.objectevent.ObjectModifiedEvent(self.context)) # TODO: Needs locale support. See also Five.form.EditView. self.status = _("Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())}) else: self.status = _('No changes')
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 __call__(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return u'<a href="@@login.html?nextURL=%s">%s</a>' % ( urllib.quote(self.request.getURL()), translate(_("[Login]"), context=self.request, default="[Login]"), ) elif ILogoutSupported(self.request, None) is not None: return u'<a href="@@logout.html?nextURL=%s">%s</a>' % ( urllib.quote(self.request.getURL()), translate(_("[Logout]"), context=self.request, default="[Logout]"), ) else: return None
def action(self): """Do the shutdown/restart!""" control = self.serverControl() time = self.request.get('time', 0) if 'restart' in self.request: control.restart(time) return _("The server will be restarted in ${number} seconds.", mapping={"number": time}) elif 'shutdown' in self.request: control.shutdown(time) return _("The server will be shutdown in ${number} seconds.", mapping={"number": time})
def __call__(self): """Render the widget""" assert self.context.value_type is not None render = [] # length of sequence info sequence = self._getRenderedValue() num_items = len(sequence) min_length = self.context.min_length max_length = self.context.max_length # generate each widget from items in the sequence - adding a # "remove" button for each one for i in range(num_items): value = sequence[i] render.append('<tr><td>') if num_items > min_length: render.append( '<input class="editcheck" type="checkbox" ' 'name="%s.remove_%d" />\n' % (self.name, i) ) widget = self._getWidget(i) widget.setRenderedValue(value) error = widget.error() if error: render.append(error) render.append('\n') render.append(widget() + '</td></tr>\n') # possibly generate the "remove" and "add" buttons buttons = '' if render and num_items > min_length: button_label = _('remove-selected-items', "Remove selected items") button_label = translate(button_label, context=self.request, default=button_label) buttons += ('<input type="submit" value="%s" name="%s.remove"/>' % (button_label, self.name)) if max_length is None or num_items < max_length: field = self.context.value_type button_label = _('Add %s') button_label = translate(button_label, context=self.request, default=button_label) button_label = button_label % (field.title or field.__name__) buttons += '<input type="submit" name="%s.add" value="%s" />\n' % ( self.name, button_label) if buttons: render.append('<tr><td>%s</td></tr>\n' % buttons) return ('<table border="0">\n%s</table>\n%s' % (''.join(render), self._getPresenceMarker(num_items)))
def handle_edit_action(self, action, data): if form.applyChanges( self.context, self.form_fields, data, self.adapters): zope.event.notify( zope.app.event.objectevent.ObjectModifiedEvent(self.context) ) # TODO: Needs locale support. See also Five.form.EditView. self.status = _( "Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())} ) else: self.status = _('No changes')
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 update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' content = self.adapted if Update in self.request.form.keys(): changed = False try: changed = applyWidgetsChanges(self, self.schema, target=content, names=self.fieldNames) # We should not generate events when an adapter is used. # That's the adapter's job. We need to unwrap the objects to # compare them, as they are wrapped differently. # Additionally, we can't use Acquisition.aq_base() because # it strangely returns different objects for these two even # when they are identical. In particular # aq_base(self.adapted) != self.adapted.aq_base :-( if changed and getattr(self.context, 'aq_base', self.context)\ is getattr(self.adapted, 'aq_base', self.adapted): description = Attributes(self.schema, *self.fieldNames) notify(ObjectModifiedEvent(content, description)) except WidgetsError, errors: self.errors = errors status = _("An error occurred.") transaction.abort() else: setUpEditWidgets(self, self.schema, source=self.adapted, ignoreStickyValues=True, names=self.fieldNames) if changed: self.changed() # XXX: Needs locale support: #formatter = self.request.locale.dates.getFormatter( # 'dateTime', 'medium') #status = _("Updated on ${date_time}", # mapping={'date_time': # formatter.format(datetime.utcnow())}) status = _("Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())})
def getZopeVersion(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" try: version_utility = getUtility(IZopeVersion) except ComponentLookupError: return _("Unavailable") return version_utility.getZopeVersion()
def handle_edit_action(self, action, data): changed = applyChanges( self.context, self.form_fields, data, self.adapters) if changed: attrs = lifecycleevent.Attributes(interfaces.IVideo, *changed) event.notify( lifecycleevent.ObjectModifiedEvent(self.context, attrs) ) # TODO: Needs locale support. See also Five.form.EditView. self.status = _("Successfully updated") else: self.status = _('No changes') statusmessages_ifaces.IStatusMessage( self.request).addStatusMessage(self.status, 'info') redirect = self.request.response.redirect return redirect(self.context.absolute_url()+'/view')
def rename(self): tool = self.activeTool regManager = self.context[tool.folder].registrationManager new_names = self.request['new_names'] old_names = self.request['old_names'] msg='' for reg in regManager.values(): if reg.provided.isOrExtends(tool.interface) and \ reg.name in old_names: old_name=reg.name new_name = new_names[old_names.index(old_name)] if new_name!=reg.name: if self.toolExists(self.activeTool.interface,new_name): if not msg: msg=_(u'The given tool name is already being used.') else: orig_status = reg.status reg.status = interfaces.registration.InactiveStatus reg.name = new_names[old_names.index(old_name)] reg.status = orig_status self.renameList.remove(old_name) self.newNames.remove(new_name) else: self.renameList.remove(old_name) self.newNames.remove(new_name) if msg: raise UserError(msg)
class EditFormDirective(FiveFormDirective): view = EditView default_template = 'edit.pt' title = _('Edit') def _handle_menu(self): if self.menu: menuItemDirective(self._context, self.menu, self.for_ or self.schema, '@@' + self.name, self.title, permission=self.permission, layer=self.layer) def __call__(self): self._processWidgets() self._handle_menu() self._context.action( discriminator=self._discriminator(), callable=EditViewFactory, args=self._args(), kw={'menu': self.menu}, )
def update(self): """ """ msg = u'' if "INSTALL-SUBMIT" in self.request: self.install() msg = _(u'Tools successfully installed.') if "UNINSTALL-SUBMIT" in self.request: self.uninstall() msg = _(u'Tools successfully uninstalled.') if "ADD-TOOL-SUBMIT" in self.request: try: self.action(self.request['type_name'], self.request['id']) except UserError, err: self.addTool = True self.addName = self.contentName msg=err
class IFileAddForm(Interface): # XXX should we add a seperate id field? We can just use the # filename of the uploaded file, but what to do on filename # conflicts file = schema.Object(schema=INamedFile, title=_(u"File to add"), required=True)
def RegisterableMoveSubscriber(registerable, event): """A registerable cannot be moved as long as it has registrations in the registration manager.""" if event.oldParent is not None and event.newParent is not None: if event.oldParent is not event.newParent: raise DependencyError( _("Can't move a registered component from its container."))
def checkObject(container, name, object): """Check containement constraints for an object and container """ # check __setitem__ precondition containerProvided = providedBy(container) __setitem__ = containerProvided.get("__setitem__") if __setitem__ is not None: precondition = __setitem__.queryTaggedValue("precondition") if precondition is not None: precondition(container, name, object) # check the constraint on __parent__ __parent__ = providedBy(object).get("__parent__") if __parent__ is not None: try: validate = __parent__.validate except AttributeError: pass else: validate(container) if not containerProvided.extends(IContainer): # If it doesn't implement IContainer, it can't contain stuff. raise TypeError(_("Container is not a valid Zope container."))
def getAdapterInfoDictionary(reg): """Return a PT-friendly info dictionary for an adapter registration.""" factory = getRealFactory(reg.value) path = getPythonPath(factory) url = None if isReferencable(path): url = path.replace('.', '/') if isinstance(reg.doc, (str, unicode)): doc = reg.doc zcml = None else: doc = None zcml = getParserInfoInfoDictionary(reg.doc) return { 'provided': getInterfaceInfoDictionary(reg.provided), 'required': [getInterfaceInfoDictionary(iface) for iface in reg.required if iface is not None], 'name': getattr(reg, 'name', _('<subscription>')), 'factory': path, 'factory_url': url, 'doc': doc, 'zcml': zcml}
def sizeForDisplay(self): """See `ISized`""" bytes = self._container.getSize() byte_size = byteDisplay(bytes) num_items = len(self._container) mapping = byte_size.mapping if mapping is None: mapping = {} mapping.update({'items': str(num_items)}) if num_items == 1: return _("${items} item / " + byte_size , mapping=mapping) else: return _("${items} items / " + byte_size , mapping=mapping)
def _toFieldValue(self, input): value = super(Bytes, self)._toFieldValue(input) if type(value) is unicode: try: value = value.encode('ascii') except UnicodeError, v: raise ConversionError(_("Invalid textual data"), v)
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, types.ClassType, types.TypeType, 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': reg.name or _('<i>no name</i>'), 'url_name': utilitymodule.encodeName(reg.name or '__noname__'), 'iface_id': iface_id, 'path': path, 'url': url}
def update(self): try: return super(FileEdit, self).update() except CharsetTooWeak, charset: self.update_status = _("The character set you specified ($charset)" " cannot encode all characters in text.", mapping={'charset': charset}) return self.update_status
def _toFieldValue(self, input): if input == self._missing: return self.context.missing_value else: try: return parseDatetimetz(input) except (DateTimeError, ValueError, IndexError), v: raise ConversionError(_("Invalid datetime data"), v)
def _toFieldValue(self, input): if input == self._missing: return self.context.missing_value else: try: return float(input) except ValueError, v: raise ConversionError(_("Invalid floating point data"), v)
def _toFieldValue(self, input): if input is None or input == '': return self.context.missing_value try: seek = input.seek read = input.read except AttributeError, e: raise ConversionError(_('Form input is not a file object'), e)
def getPermissionIds(name, checker=_marker, klass=_marker): """Get the permissions of an attribute.""" assert (klass is _marker) != (checker is _marker) entry = {} if klass is not _marker: checker = getCheckerForInstancesOf(klass) if checker is not None and INameBasedChecker.providedBy(checker): entry['read_perm'] = _evalId(checker.permission_id(name)) \ or _('n/a') entry['write_perm'] = _evalId(checker.setattr_permission_id(name)) \ or _('n/a') else: entry['read_perm'] = entry['write_perm'] = None return entry
def _toFieldValue(self, value): value = super(TextAreaWidget, self)._toFieldValue(value) if value: try: value = unicode(value) except ValueError, v: raise ConversionError(_("Invalid unicode data"), v) else: value = value.replace("\r\n", "\n")
def applyUpdates(self): message = '' if 'submit_update' in self.request.form: id = self.request.form.get(self.name) if id == "disable": active = self.context.active() if active is not None: self.context.activate(None) message = _("Disabled") else: for info in self.context.info(): infoid = zapi.getPath(info['registration']) if infoid == id and not info['active']: self.context.activate(info['registration']) message = _("Updated") break return message
def _getFormInput(self): prefix = self.name + '.' year = int(self.request.form.get(prefix + self.elements[2][1], None)) month = int(self.request.form.get(prefix + self.elements[1][1], None)) day = int(self.request.form.get(prefix + self.elements[0][1], None)) if year and month and day: try: return datetime.date(year, month, day) except ValueError, v: raise ConversionError(_("Invalid datetime data"), v)
class FileAddForm(FormBase): label = _(u"Add a new file") form_fields = form.Fields(IFileAddForm).select("file") form_fields["file"].custom_widget = NamedFileWidget def getFilePath(self, file): return os.path.join(self.context.getFilesystemPath(), file.filename) def addValidate(self, action, data): errors = self.validate(action, data) if not errors: # IE includes the full path (security violation!). Strip it off. data['file'].filename = data['file'].filename.split('\\')[-1] if self.context.has_key(data['file'].filename): error = WidgetInputError("file", u"File to add", FileExistsError()) errors.append(error) return errors @form.action(_("Add file"), validator=addValidate) def addFile(self, action, data): file = data["file"] path = self.getFilePath(file) # We care about security so use O_CREAT|O_EXCL to prevent us # from hitting symlinks or other race attacks. try: # For OSes which support it (Windows) we need to use the # O_BINARY flag to prevent cr/lf rewriting. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY except AttributeError: flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL fd = os.open(path, flags, 0644) os.write(fd, file.data) os.close(fd) reflex = self.context.aq_inner[file.filename] reflex.indexObject() pt = getToolByName(self.context, "plone_utils") pt.addPortalMessage(_(u"File uploaded and indexed")) return self.request.response.redirect(self.context.absolute_url())
def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' content = self.adapted if Update in self.request.form.keys(): changed = False try: changed = applyWidgetsChanges(self, self.schema, target=content, names=self.fieldNames) # We should not generate events when an adapter is used. # That's the adapter's job. if changed and self.context is self.adapted: notify(ObjectModifiedEvent(content)) except WidgetsError, errors: self.errors = errors status = _("An error occurred.") transaction.abort() else: setUpEditWidgets(self, self.schema, source=self.adapted, ignoreStickyValues=True, names=self.fieldNames) if changed: self.changed() # XXX: Needs locale support: #formatter = self.request.locale.dates.getFormatter( # 'dateTime', 'medium') #status = _("Updated on ${date_time}", # mapping={'date_time': # formatter.format(datetime.utcnow())}) status = _("Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())})
class EditForm(Acquisition.Explicit, zope.formlib.form.EditForm): # Overrides the formlib.form.FormBase.template attributes implemented # using NamedTemplates. NamedTemplates using ZopeTwoPageTemplateFile (like # formlib does by default) cannot work in Zope2. # XXX Maybe we need to have Five-compatible NamedTemplates? template = ZopeTwoPageTemplateFile('activity.pt') # Overrides formlib.form.FormBase.update. Make sure user input is # decoded first and the page encoding is set before proceeding. zope.interface.implements(zope.formlib.interfaces.IPageForm) def __init__(self, context, request): super(EditForm, self).__init__(context, request) # This needs to stay here, otherwise the publisher falls # on its face. :/ self.request.debug = None #setPageEncoding(self.request) def __call__(self, *a, **kw): return super(EditForm, self).__call__(*a, **kw) return unicode(result, 'iso-8859-15') def setUpWidgets(self, *args, **kw): super(EditForm, self).setUpWidgets(*args, **kw) # Some widget post-processing to support a better layout # - compact -> display the widget in front of the title for widget in self.widgets: widget.compact = False if isinstance(widget, zope.app.form.browser.boolwidgets.CheckBoxWidget): widget.compact = True def update(self): processInputs(self.request) super(EditForm, self).update() @zope.formlib.form.action(_("Apply"), condition=zope.formlib.form.haveInputWidgets) def handle_edit_action(self, action, data): if zope.formlib.form.applyChanges(self.context, self.form_fields, data, self.adapters): zope.event.notify( zope.app.event.objectevent.ObjectModifiedEvent(self.context)) # TODO: Needs locale support. See also Five.form.EditView. self.status = _("Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())}) else: self.status = _('No changes')
class INaayaSimpleViewDirective(Interface): """ Define a simple zope3 view """ for_ = GlobalInterface( title=u"The interface this view is for.", required=True, ) name = TextLine( title=u"The name of the view.", description=u"The name shows up in URLs/paths. For example 'foo'.", required=True, ) handler = GlobalObject( title=_("Handler"), description=_("Function that handles the view."), required=True, ) permission = Permission( title=u"Permission", description=u"The permission needed to use the view.", required=False, )
def update(self): if self.update_status is not None: # We've been called before. Just return the previous result. return self.update_status if self.request.form.has_key(Update): self.update_status = '' try: data = getWidgetsData(self, self.schema, names=self.fieldNames) self.createAndAdd(data) except WidgetsError, errors: self.errors = errors self.update_status = _("An error occurred.") return self.update_status self.request.response.redirect(self.nextURL())
class EditFormBase(FiveFormlibMixin, form.EditFormBase): # Overrides formlib.form.EditFormBase.handle_edit_action, to remove # dependecy on request.locale @form.action(_("Apply"), condition=form.haveInputWidgets) def handle_edit_action(self, action, data): if form.applyChanges(self.context, self.form_fields, data, self.adapters): zope.event.notify( zope.app.event.objectevent.ObjectModifiedEvent(self.context)) # TODO: Needs locale support. See also Five.form.EditView. self.status = _("Updated on ${date_time}", mapping={'date_time': str(datetime.utcnow())}) else: self.status = _('No changes')
def addFile(self, action, data): file = data["file"] path = self.getFilePath(file) # We care about security so use O_CREAT|O_EXCL to prevent us # from hitting symlinks or other race attacks. try: # For OSes which support it (Windows) we need to use the # O_BINARY flag to prevent cr/lf rewriting. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY except AttributeError: flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL fd = os.open(path, flags, 0644) os.write(fd, file.data) os.close(fd) reflex = self.context.aq_inner[file.filename] reflex.indexObject() pt = getToolByName(self.context, "plone_utils") pt.addPortalMessage(_(u"File uploaded and indexed")) return self.request.response.redirect(self.context.absolute_url())
class INaayaRstkMethodDirective(Interface): """ Register a RSTK method """ handler = GlobalObject( title=_("Implementation of the method"), required=True, ) name = TextLine( title=u"Name of method (defaults to __name__ attribute of handler)", required=False, ) context = Bool( title=u"Send context as first argument", required=False, ) bundle = TextLine( title=u"Bundle to register the method (default 'Naaya')", required=False, ) getattrPatch = Bool( title=u"Backwards-compatibility patch for old getattr-style access", required=False, )
class FileExistsError(ValidationError): __doc__ = _(u"A file with the same filename already exists.")
def __call__(self): self.index() pt = getToolByName(self.context, "plone_utils") pt.addPortalMessage(_(u"Reflector (re)indexed")) return self.request.response.redirect(self.context.absolute_url())
class IRootPathDirective(Interface): path = fields.Path( title=_("Path"), description=_("Path prefix where to look for CIRCA zip files."), required=True, )