def xliff_import(self, howmuch, file, REQUEST=None): """XLIFF is the XML Localization Interchange File Format designed by a group of software providers. It is specified by www.oasis-open.org """ try: data = file.read() xliff = XLFFile(string=data) except: return MessageDialog( title='Parse error', message=_('impossible to parse the file'), action='manage_Import_form', ) num_notes = 0 num_trans = 0 (file_ids, sources, targets) = xliff.get_languages() if howmuch == 'clear': # Clear the message catalogue prior to import self._messages = {} self._languages = () self._default_language = sources[0] # update languages if len(sources) > 1 or sources[0] != self._default_language: return MessageDialog( title='Language error', message=_('incompatible language sources'), action='manage_Import_form', ) for lang in targets: if lang != self._default_language and lang not in self._languages: self._languages += (lang, ) # get messages for file in xliff.files: cur_target = file.attributes.get('target-language', '') for msg in file.body.keys(): if not self._messages.has_key(msg) and howmuch == 'existing': pass else: if not self._messages.has_key(msg): self._messages[msg] = {} if cur_target and file.body[msg].target: self._messages[msg][cur_target] = file.body[msg].target num_trans += 1 if file.body[msg].notes: ns = [n.text for n in file.body[msg].notes] comment = ' '.join(ns) self._messages[msg]['note'] = comment num_notes += 1 if REQUEST is not None: return MessageDialog( title = _(u'Messages imported'), message = (_(u'Imported %d messages and %d notes to %s') % \ (num_trans, num_notes, ' '.join(targets))), action = 'manage_messages')
def manage_changePermissions(self, REQUEST): """Change all permissions settings, called by management screen. """ valid_roles = self.valid_roles() indexes = range(len(valid_roles)) have = REQUEST.has_key permissions = self.ac_inherited_permissions(1) fails = [] for ip in range(len(permissions)): roles = [] for ir in indexes: if have("p%dr%d" % (ip, ir)): roles.append(valid_roles[ir]) name, value = permissions[ip][:2] try: p = Permission(name, value, self) if not have('a%d' % ip): roles = tuple(roles) p.setRoles(roles) except: fails.append(name) if fails: return MessageDialog(title="Warning!", message="Some permissions had errors: " + escape(', '.join(fails)), action='manage_access') return MessageDialog(title='Success!', message='Your changes have been saved', action='manage_access')
def _addUser(self, name, password, confirm, roles, domains, REQUEST=None): if not name: return MessageDialog(title='Illegal value', message='A username must be specified', action='manage_main') if not password or not confirm: if not domains: return MessageDialog( title='Illegal value', message='Password and confirmation must be specified', action='manage_main') if self.getUser(name) or (self._emergency_user and name == self._emergency_user.getUserName()): return MessageDialog( title='Illegal value', message='A user with the specified name already exists', action='manage_main') if (password or confirm) and (password != confirm): return MessageDialog( title='Illegal value', message='Password and confirmation do not match', action='manage_main') if not roles: roles = [] if not domains: domains = [] if domains and not self.domainSpecValidate(domains): return MessageDialog(title='Illegal value', message='Illegal domain specification', action='manage_main') self._doAddUser(name, password, roles, domains) if REQUEST: return self._mainUser(self, REQUEST)
def manage_delProperties(self, ids=None, REQUEST=None): """Delete one or more properties specified by 'ids'.""" if REQUEST: # Bugfix for property named "ids" (Casey) if ids == self.getProperty('ids', None): ids = None ids = REQUEST.get('_ids', ids) if ids is None: return MessageDialog( title='No property specified', message='No properties were specified!', action='./manage_propertiesForm', ) propdict = self.propdict() nd = self._reserved_names for id in ids: if not hasattr(aq_base(self), id): raise BadRequest, ('The property <em>%s</em> does not exist' % escape(id)) if (not 'd' in propdict[id].get('mode', 'wd')) or (id in nd): return MessageDialog( title='Cannot delete %s' % id, message='The property <em>%s</em> cannot be deleted.' % escape(id), action='manage_propertiesForm') self._delProperty(id) if REQUEST is not None: return self.manage_propertiesForm(self, REQUEST)
def manage_renameObject(self, id, new_id, REQUEST=None): """Rename a particular sub-object, the *old* way. FIXME: hack that could be removed once Zope 2.4.x goes back to a useful semantics...""" try: self._checkId(new_id) except: raise CopyError, MessageDialog(title='Invalid Id', message=sys.exc_info()[1], action='manage_main') ob = self._getOb(id) if not ob.cb_isMoveable(): raise CopyError, eNotSupported % id self._verifyObjectPaste(ob) try: ob._notifyOfCopyTo(self, op=1) except: raise CopyError, MessageDialog(title='Rename Error', message=sys.exc_info()[1], action='manage_main') self._delObject(id) ob = aq_base(ob) ob._setId(new_id) # Note - because a rename always keeps the same context, we # can just leave the ownership info unchanged. self._setObject(new_id, ob, set_owner=False) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=True) return None
def manage_changeCriteria(self, REQUEST): """Changes all criteria for a bibliography type given, called by management screen """ reference_type = REQUEST.get('bibtype') has = REQUEST.has_key if reference_type != 'all': reference_types = [reference_type] else: bib_tool = getToolByName(self, 'portal_bibliography') reference_types = bib_tool.getReferenceTypes() for reference_type in reference_types: criteria = [] for criterion in self._criteria[reference_type]: # the form bibtype_criterion is not useful for now, but it was set up # in case we want to use one submit input for all the bibliography types if has("%s_%s" % (reference_type, criterion)): criteria.append(criterion) try: self.setCriteriaForType(reference_type, criteria) except: return MessageDialog( title='Warning!', message='Your changes have not been saved', action='manageImportCriteria') return MessageDialog(title='Success!', message='Your changes have been saved', action='manageImportCriteria')
def manage_addZSQLiteConnection(self, id: str, title: str, data_dir: str, connection: str = '', REQUEST=None) -> 'manage_main': """Add a DB connection to a folder""" db_path = os.path.join(data_dir, connection) if not id: return MessageDialog( title='Edited', message='Please provide an id for the database adapter!', action='javascript:history.back()') try: check_database(dbpath=db_path) except sqlite3_OperationalError as e: return MessageDialog(title='Edited', message=extract_error(e), action='javascript:history.back()') # Note - ZSQLiteDA's connect immediately check is alway false self._setObject(id, Connection(id, title, connection, REQUEST)) if REQUEST is not None: return self.manage_main(self, REQUEST)
def manage_delObjects(self, ids=[], REQUEST=None): """Delete a subordinate object The objects specified in 'ids' get deleted. """ if type(ids) is type(''): ids=[ids] if not ids: return MessageDialog(title='No items specified', message='No items were specified!', action ='./manage_main',) try: p=self._reserved_names except: p=() for n in ids: if n in p: return MessageDialog(title='Not Deletable', message='<EM>%s</EM> cannot be deleted.' % escape(n), action ='./manage_main',) while ids: id=ids[-1] v=self._getOb(id, self) if v.wl_isLocked(): raise ResourceLockedError, ( 'Object "%s" is locked via WebDAV' % v.getId()) if v is self: raise BadRequest, '%s does not exist' % escape(ids[-1]) self._delObject(id) del ids[-1] if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def manage_addToContainer(self, container, nextURL=''): if nextURL: if hasattr(getattr(container, 'aq_base', container), self.id): return MessageDialog(title='Item Exists', message='This object already contains a %s' % self.meta_type, action=nextURL) self.addToContainer(container) if nextURL: return MessageDialog(title='Item Added', message='This object now has a %s' % escape(self.meta_type), action=nextURL)
def tmx_import(self, howmuch, file, REQUEST=None, RESPONSE=None): """Imports a TMX level 1 file. """ try: data = file.read() tmx = TMXFile(string=data) except: return MessageDialog( title='Parse error', message=_('impossible to parse the file'), action='manage_Import_form', ) num_notes = 0 num_trans = 0 if howmuch == 'clear': # Clear the message catalogue prior to import self._messages = {} self._languages = () self._default_language = tmx.get_srclang() for id, msg in tmx.messages.items(): if not self._messages.has_key(id) and howmuch == 'existing': continue msg.msgstr.pop(self._default_language) if not self._messages.has_key(id): self._messages[id] = {} for lang in msg.msgstr.keys(): # normalize the languageTag and extract the core (core, local) = LanguageTag.decode(lang) lang = LanguageTag.encode((core, local)) if lang not in self._languages: self._languages += (lang, ) if msg.msgstr[lang].text: self._messages[id][lang] = msg.msgstr[lang].text if core != lang and core != self._default_language: if core not in self._languages: self._languages += (core, ) if not msg.msgstr.has_key(core): self._messages[id][core] = msg.msgstr[lang].text if msg.notes: ns = [m.text for m in msg.notes] self._messages[id]['note'] = u' '.join(ns) num_notes += 1 num_trans += 1 if REQUEST is not None: message = _(u'Imported %d messages and %d notes') return MessageDialog(title=_(u'Messages imported'), message=message % (num_trans, num_notes), action='manage_messages')
def _addRole(self, role, REQUEST=None): if not role: return MessageDialog(title='Incomplete', message='You must specify a role name', action='manage_access') if role in self.__ac_roles__: return MessageDialog(title='Role Exists', message='The given role is already defined', action='manage_access') data = list(self.__ac_roles__) data.append(role) self.__ac_roles__ = tuple(data) if REQUEST is not None: return self.manage_access(REQUEST)
def dummyFunction(zope): """ dummy function because we don't want to use the ZMI for some classes. """ return MessageDialog(title="Add Issue Error", message="Don't add Issue Tracker Issues with the Zope management interface;"\ "instead, use the Issue Tracker only", action="manage_main")
def tmx_import(self, file, REQUEST=None, RESPONSE=None): """Imports a TMX level 1 file. """ try: data = file.read() tmx = TMXFile(string=data) except: return MessageDialog(title = 'Parse error', message = _('impossible to parse the file') , action = 'manage_import',) for id, msg in tmx.messages.items(): for prop, d in self._local_properties.items(): if d[self._default_language][0] == id: msg.msgstr.pop(self._default_language) for lang in msg.msgstr.keys(): # normalize the languageTag and extract the core (core, local) = LanguageTag.decode(lang) lang = LanguageTag.encode((core, local)) if lang not in self._languages: self._languages += (lang,) texte = msg.msgstr[lang].text if texte: self.set_localpropvalue(prop, lang, texte) if core != lang and core != self._default_language: if core not in self._languages: self._languages += (core,) if not msg.msgstr.has_key(core): self.set_localpropvalue(prop, lang, texte) if REQUEST is not None: RESPONSE.redirect('manage_localPropertiesForm')
def manageProperties(self, title='', path='', mbox_ignore=[], index_header='', index_footer='', allow_zip=0, imap_servername='', imap_username='', imap_password='', cron_key='', update_cache='', REQUEST=None): """ save properties """ self.title = title self._path = path.strip() self.allow_zip = allow_zip self.mbox_ignore = self.lines_to_list(mbox_ignore) self.index_header = index_header self.index_footer = index_footer self.imap_servername = imap_servername.strip() self.imap_username = imap_username.strip() self.imap_password = imap_password.strip() self.cron_key = cron_key.strip() if update_cache: # update cache if wanted self.updateArchives(0) self._p_changed = 1 if REQUEST is not None: return MessageDialog( title='Edited', message="The properties of %s have been changed!" % self.id, action='./manage_main', )
def updata(self): """Convert SiteAccess objects from 1.x to 2.x""" _cvt_btr(self.REQUEST['PARENTS'][-1]) from App.Dialogs import MessageDialog return MessageDialog(title='Update Complete', message='Update Complete!', action='./manage_main')
def manage_addToContainer(self, container, nextURL=''): self.addToContainer(container) if nextURL: return MessageDialog(title='Item Added', message='This object now has a %s' % self.meta_type, action=nextURL)
def _delUsers(self, names, REQUEST=None): if not names: return MessageDialog(title='Illegal value', message='No users specified', action='manage_main') self._doDelUsers(names) if REQUEST: return self._mainUser(self, REQUEST)
def _setId(self, id): """ Never allow renaming! """ if id != self.getId(): raise ValueError( MessageDialog(title='Invalid Id', message='Cannot change the id of this object', action='./manage_main'))
def manage_edit(self, title, base, path, REQUEST=None): """ Set the title, base, and path. """ self.__init__(title, base, path) if REQUEST: return MessageDialog(title='SiteRoot changed.', message='SiteRoot changed.', action='%s/manage_main' % REQUEST['URL1'])
def manage_addAccessRule(self, method_id=None, REQUEST=None, **ignored): """Point a __before_traverse__ entry at the specified method""" # We want the original object, not stuff in between, and no acquisition self = self.this() self = getattr(self, 'aq_base', self) priority = (1, 'AccessRule') if method_id is None or (REQUEST and REQUEST.form.has_key('none')): rules = unregisterBeforeTraverse(self, 'AccessRule') if rules: try: del getattr(self, rules[0].name).icon except: pass if REQUEST: return MessageDialog(title='No Access Rule', message='This object now has no Access Rule', action='%s/manage_main' % REQUEST['URL1']) elif method_id and hasattr(self, method_id): rules = unregisterBeforeTraverse(self, 'AccessRule') if rules: try: del getattr(self, rules[0].name).icon except: pass hook = AccessRule(method_id) registerBeforeTraverse(self, hook, 'AccessRule', 1) try: getattr(self, method_id).icon = 'misc_/SiteAccess/AccessRule.gif' except: pass if REQUEST: return MessageDialog( title='Access Rule Set', message='"%s" is now the Access Rule for this object' % escape(method_id), action='%s/manage_main' % REQUEST['URL1']) else: if REQUEST: return MessageDialog( title='Invalid Method Id', message='"%s" is not the Id of a method of this object' % escape(method_id), action='%s/manage_main' % REQUEST['URL1'])
def async_move(context, success_event, fail_event, **kwargs): """ Async job """ newid = kwargs.get('newid', '') email = kwargs.get('email', '') anno = IAnnotations(context) job_id = anno.get('async_move_job') if not newid: wrapper = IContextWrapper(context)( error=u'Invalid newid' ) notify(fail_event(wrapper)) raise CopyError(eNoItemsSpecified) try: _op, mdatas = _cb_decode(newid) except: raise CopyError(eInvalid) oblist = [] app = context.getPhysicalRoot() for mdata in mdatas: m = loadMoniker(mdata) try: ob = m.bind(app) except ConflictError: raise except: raise CopyError(eNotFound) oblist.append(ob) wrapper = IContextWrapper(context)( folder_move_from=oblist and aq_parent( aq_inner(oblist[0])).absolute_url(), folder_move_to=context.absolute_url(), folder_move_objects=', '.join([obj.getId() for obj in oblist]), asyncmove_email=email ) try: manage_pasteObjects_no_events(context, cb_copy_data=newid) except Exception, err: logger.exception(err) wrapper.error = err.message wrapper.job_id = job_id notify(fail_event(wrapper)) raise CopyError(MessageDialog( title='Error', message=err.message, action='manage_main', ))
def manage_editProperties(self, REQUEST): """ Override from propertiyManager so we can trap errors """ try: return ConfmonPropManager.manage_editProperties(self, REQUEST) except IpAddressError, e: return MessageDialog(title="Input Error", message=e.args[0], action="manage_main")
def manage_edit(self, title, connection_string, check=None, REQUEST=None): """Change connection """ self.edit(title, connection_string, check) if REQUEST is not None: return MessageDialog( title='Edited', message='<strong>%s</strong> has been edited.' % escape(self.id), action ='./manage_main', )
def manage_addAbbrevIdCooker(self, REQUEST=None): """ """ try: self._setObject('abbrev', AbbrevIdCooker()) except: return MessageDialog( title='Bibliography tool warning message', message='The id cooker you attempted to add already exists.', action='manage_main') return self.manage_main(self, REQUEST)
def manage_editProperties(self, REQUEST): """Edit object properties via the web.""" for prop in self._propertyMap(): name = prop['id'] if 'w' in prop.get('mode', 'wd'): value = REQUEST.get(name, '') self._updateProperty(name, value) return MessageDialog(title='Success!', message='Your changes have been saved', action='manage')
def manage_proxy(self, roles=(), REQUEST=None): "Change Proxy Roles" self._validateProxy(roles) self._validateProxy() self.ZCacheable_invalidate() self._proxy_roles = tuple(roles) if REQUEST: return MessageDialog(title='Success!', message='Your changes have been saved', action='manage_main')
def _changeUser(self, name, password, confirm, roles, domains, REQUEST=None): if password == 'password' and confirm == 'pconfirm': # Protocol for editUser.dtml to indicate unchanged password password = confirm = None if not name: return MessageDialog(title='Illegal value', message='A username must be specified', action='manage_main') if password == confirm == '': if not domains: return MessageDialog( title='Illegal value', message='Password and confirmation must be specified', action='manage_main') if not self.getUser(name): return MessageDialog(title='Illegal value', message='Unknown user', action='manage_main') if (password or confirm) and (password != confirm): return MessageDialog( title='Illegal value', message='Password and confirmation do not match', action='manage_main') if not roles: roles = [] if not domains: domains = [] if domains and not self.domainSpecValidate(domains): return MessageDialog(title='Illegal value', message='Illegal domain specification', action='manage_main') self._doChangeUser(name, password, roles, domains) if REQUEST: return self._mainUser(self, REQUEST)
def xliff_import(self, file, REQUEST=None): """ XLIFF is the XML Localization Interchange File Format designed by a group of software providers. It is specified by www.oasis-open.org """ try: data = file.read() xliff = XLFFile(string=data) except: return MessageDialog(title = 'Parse error', message = _('impossible to parse the file') , action = 'manage_import',) num_trans = 0 (file_ids, sources, targets) = xliff.get_languages() # update languages if len(sources) > 1 or sources[0] != self._default_language: return MessageDialog(title = 'Language error', message = _('incompatible language sources') , action = 'manage_import',) for lang in targets: if lang != self._default_language and lang not in self._languages: self._languages += (lang,) # get messages for file in xliff.files: cur_target = file.attributes.get('target-language', '') for msg in file.body.keys(): for (prop, val) in self._local_properties.items(): if val[self._default_language][0] == msg: if cur_target and file.body[msg].target: texte = file.body[msg].target self.set_localpropvalue(prop, cur_target, texte) num_trans += 1 if REQUEST is not None: return MessageDialog( title = _(u'Messages imported'), message = (_(u'Imported %d messages to %s') % (num_trans, ' '.join(targets))), action = 'manage_localPropertiesForm')
def unrestricted_rename(self, id, new_id): """Rename a particular sub-object Copied from OFS.CopySupport Less strict version of manage_renameObject: * no write look check * no verify object check from PortalFolder so it's allowed to rename even unallowed portal types inside a folder """ try: self._checkId(new_id) except: raise CopyError, MessageDialog(title='Invalid Id', message=sys.exc_info()[1], action='manage_main') ob = self._getOb(id) #!#if ob.wl_isLocked(): #!# raise ResourceLockedError, 'Object "%s" is locked via WebDAV' % ob.getId() if not ob.cb_isMoveable(): raise CopyError, eNotSupported % escape(id) #!#self._verifyObjectPaste(ob) #!#CopyContainer._verifyObjectPaste(self, ob) try: ob._notifyOfCopyTo(self, op=1) except: raise CopyError, MessageDialog(title='Rename Error', message=sys.exc_info()[1], action='manage_main') self._delObject(id) ob = aq_base(ob) ob._setId(new_id) # Note - because a rename always keeps the same context, we # can just leave the ownership info unchanged. self._setObject(new_id, ob, set_owner=0) ob = self._getOb(new_id) ob._postCopy(self, op=1) #!#if REQUEST is not None: #!# return self.manage_main(self, REQUEST, update_menu=1) return None
def manage_workspace(self, REQUEST): """ZMI function to return the workspace of the related object""" if self.obj: objurl = self.obj.getPrimaryUrlPath() REQUEST['RESPONSE'].redirect(objurl + '/manage_workspace') else: return MessageDialog( title = "No Relationship Error", message = "This relationship does not currently point" \ " to an object", action = "manage_main")