def manage_edit(self, data, title, SUBMIT='Change', dtpref_cols='100%', dtpref_rows='20', REQUEST=None): """ Replace contents with 'data', title with 'title'. The SUBMIT parameter is also used to change the size of the editing area on the default Document edit screen. If the value is "Smaller", the rows and columns decrease by 5. If the value is "Bigger", the rows and columns increase by 5. If any other or no value is supplied, the data gets checked for DTML errors and is saved. """ self._validateProxy(REQUEST) if self._size_changes.has_key(SUBMIT): return self._er(data, title, SUBMIT, dtpref_cols, dtpref_rows, REQUEST) if self.wl_isLocked(): raise ResourceLockedError('This item is locked via WebDAV') self.title = str(title) if isinstance(data, TaintedString): data = data.quoted() if not isinstance(data, basestring): data = data.read() self.munge(data) self.ZCacheable_invalidate() if REQUEST: message = "Saved changes." return self.manage_main(self, REQUEST, manage_tabs_message=message)
def manage_file_upload(self, file='', content_type='', REQUEST=None): """ Upload file from file handle or local directory """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if isinstance(file, str): file = open(file, 'rb') if content_type: file = HTTPUpload(file, content_type) content_type = self._get_content_type(file, file.read(100), self.id, self.content_type) file.seek(0) self._register() # Register with TM try: backup = REPOSITORY_EXTENSIONS in (MIMETYPE_APPEND, MIMETYPE_REPLACE) and \ self.filename and self.content_type != content_type new_fn = self._get_ufn(self.filename, content_type=content_type, backup=backup) self._update_data(file, self._temp_fsname(new_fn)) finally: self._dir__unlock() self.filename = new_fn self.content_type = content_type self._afterUpdate() if REQUEST is not None: return self.manage_main(self, REQUEST, manage_tabs_message='Upload complete.')
def manage_http_upload(self, url, REQUEST=None): """ Upload file from http-server """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") url = urllib.quote(url, '/:') file = urllib.urlopen(url) file = HTTPUpload(file) content_type = self._get_content_type(file, file.read(100), self.id, self.content_type) file.seek(0) self._register() # Register with TM try: backup = REPOSITORY_EXTENSIONS in (MIMETYPE_APPEND, MIMETYPE_REPLACE) and \ self.filename and self.content_type != content_type new_fn = self._get_ufn(self.filename, content_type=content_type, backup=backup) self._update_data(file, self._temp_fsname(new_fn)) finally: self._dir__unlock() self.filename = new_fn self.content_type = content_type self._afterUpdate() if REQUEST is not None: return self.manage_main(self, REQUEST, manage_tabs_message='Upload complete.')
def manage_cutObjects(self, ids=None, REQUEST=None): """Put a reference to the objects named in ids in the clip board""" if ids is None and REQUEST is not None: return eNoItemsSpecified elif ids is None: raise ValueError('ids must be specified') if type(ids) is type(''): ids=[ids] oblist=[] for id in ids: 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)) m = Moniker(ob) oblist.append(m.dump()) cp=(1, oblist) cp=_cb_encode(cp) if REQUEST is not None: resp=REQUEST['RESPONSE'] resp.setCookie('__cp', cp, path='%s' % cookie_path(REQUEST)) REQUEST['__cp'] = cp return self.manage_main(self, REQUEST) return cp
def manageProperties(self, REQUEST=None, **kwargs): """ """ if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG) if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if REQUEST is not None: schema_raw_data = dict(REQUEST.form) else: schema_raw_data = kwargs _lang = schema_raw_data.pop('_lang', schema_raw_data.pop('lang', None)) _releasedate = self.process_releasedate( schema_raw_data.pop('releasedate', ''), self.releasedate) schema_raw_data.pop('uploaded_file', None) versions_to_remove = schema_raw_data.pop('versions_to_remove', []) form_errors = self.process_submitted_form( schema_raw_data, _lang, _override_releasedate=_releasedate) if form_errors: raise ValueError(form_errors.popitem()[1]) # pick a random error user = self.REQUEST.AUTHENTICATED_USER.getUserName() # TODO: check this for ver_id in versions_to_remove: self.remove_version(int(ver_id) - 1, user) self._p_changed = 1 self.recatalogNyObject(self) if REQUEST: REQUEST.RESPONSE.redirect('manage_main?save=ok')
def manageUpload(self, file='', REQUEST=None): """ """ if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG) if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") self.handleMediaUpload(file) if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')
def manage_upload(self, file='', content_type='', REQUEST=None): """ Upload file from file handle or string buffer """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if isinstance(file, str): temp_file = TemporaryFile() temp_file.write(file) temp_file.seek(0) else: temp_file = file return self.manage_file_upload(temp_file, content_type, REQUEST)
def doSettings(self, REQUEST, title='', form_name='', template='', filename='object/title_or_id'): """Change title, form_name, template, filename.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") self.form_name = form_name self.template = template self.title = title self.filename = filename message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.manage_editFormPrintout(manage_tabs_message=message)
def pt_editAction(self, REQUEST, mailhost, text, content_type, expand): """Change the mailhost and document.""" if self.wl_isLocked(): from webdav.Lockable import ResourceLockedError raise ResourceLockedError("File is locked via WebDAV") self.expand = expand self._setPropValue('mailhost', mailhost) self.pt_edit(text, content_type) REQUEST.set('text', self.read()) # May not equal 'text'! message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.pt_editForm(manage_tabs_message=message)
def doSettings(self, REQUEST, title, pdf_stylesheet): """ Change title and pdf_stylesheet. """ if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") self.pdf_stylesheet = pdf_stylesheet self.pt_setTitle(title) #REQUEST.set('text', self.read()) # May not equal 'text'! message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.formSettings(manage_tabs_message=message)
def manage_edit(self, title, content_type, precondition='', filedata=None, REQUEST=None): """ Changes the title and content type attributes of the File or Image. """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") self.setTitle(title) if filedata is not None: self.update_data(filedata, content_type, len(filedata)) if REQUEST: message = "Saved changes." return self.manage_main(self, REQUEST, manage_tabs_message=message)
def saveUpload(self, file='', lang=None, REQUEST=None): """ """ if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG) if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if lang is None: lang = self.gl_get_selected_language() self.handleMediaUpload(file) self.recatalogNyObject(self) if REQUEST: self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate()) REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' % (self.absolute_url(), lang))
def finish(self): oblist = [] for ob in self.oblist: if ob.wl_isLocked(): raise ResourceLockedError('Object "%s" is locked via WebDAV' % ob.getId()) if not ob.cb_isMoveable(): raise CopyError(eNotSupported % escape(id)) m = Moniker(ob) oblist.append(m.dump()) cp = (1, oblist) cp = _cb_encode(cp) resp = self.request.response resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request)) self.request['__cp'] = cp
def manage_upload(self, file='', REQUEST=None): """ Replace the contents of the document with the text in 'file'. """ self._validateProxy(REQUEST) if self.wl_isLocked(): raise ResourceLockedError('This DTML Method is locked via WebDAV') if type(file) is not str: if REQUEST and not file: raise ValueError('No file specified') file = file.read() self.munge(file) self.ZCacheable_invalidate() if REQUEST: message = "Saved changes." return self.manage_main(self, REQUEST, manage_tabs_message=message)
def manage_edit(self, title, connection_id, arguments, template, SUBMIT='Change', dtpref_cols='100%', dtpref_rows='20', REQUEST=None): """Change database method properties The 'connection_id' argument is the id of a database connection that resides in the current folder or in a folder above the current folder. The database should understand SQL. The 'arguments' argument is a string containing an arguments specification, as would be given in the SQL method cration form. The 'template' argument is a string containing the source for the SQL Template. """ if SUBMIT in self._size_changes: return self._er(title, connection_id, arguments, template, SUBMIT, dtpref_cols, dtpref_rows, REQUEST) if self.wl_isLocked(): raise ResourceLockedError('SQL Method is locked via WebDAV') self.title = str(title) self.connection_id = str(connection_id) arguments = str(arguments) self.arguments_src = arguments self._arg = parse(arguments) template = str(template) self.src = template self.template = t = self.template_class(template) t.cook() self._v_cache = ({}, Bucket()) if REQUEST: if SUBMIT == 'Change and Test': return self.manage_testForm(REQUEST) message = 'ZSQL Method content changed' return self.manage_main(self, REQUEST, manage_tabs_message=message) return ''
def manage_upload(self, file='', content_type='', is_preview=0, create_prev=NO_PREVIEW, maxx='', maxy='', ratio=0, REQUEST=None): """ Upload image from file handle or string buffer """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if isinstance(file, str): temp_file = TemporaryFile() temp_file.write(file) temp_file.seek(0) else: temp_file = file return self.manage_file_upload(temp_file, content_type, is_preview, create_prev, maxx, maxy, ratio, REQUEST)
def pt_upload(self, REQUEST, file='', encoding='utf-8'): """Replace the document with the text in file.""" if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if isinstance(file, str): filename = None text = file else: if not file: raise ValueError('File not specified') filename = file.filename text = file.read() content_type = guess_type(filename, text) # if not content_type in ('text/html', 'text/xml'): # raise ValueError('Unsupported mimetype: %s' % content_type) self.pt_edit(text, content_type) return self.pt_editForm(manage_tabs_message='Saved changes')
def pt_editAction(self, REQUEST, title, text, content_type, expand): """Change the title and document.""" if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") self.expand = expand # The ZMI edit view uses utf-8! So we can safely assume # that 'title' and 'text' are utf-8 encoded strings - hopefully self.pt_setTitle(title, 'utf-8') text = unicode(text, 'utf-8') self.pt_edit(text, content_type, True) REQUEST.set('text', self.read()) # May not equal 'text'! REQUEST.set('title', self.title) message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.pt_editForm(manage_tabs_message=message)
def pt_upload(self, REQUEST, file=''): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if not isinstance(file, basestring): if not file: raise ValueError('File not specified') file = file.read() if file.startswith( "PK"): # FIXME: this condition is probably not enough # this is a OOo zip file, extract the content builder = OOoBuilder(file) attached_files_list = [ n for n in builder.getNameList() if n.startswith(self._OLE_directory_prefix) or n.startswith('Pictures') or n == 'META-INF/manifest.xml' ] # destroy a possibly pre-existing OLE document set if self.OLE_documents_zipstring: self.OLE_documents_zipstring = None # create a zip archive and store it if attached_files_list: memory_file = StringIO() try: zf = ZipFile(memory_file, mode='w', compression=ZIP_DEFLATED) except RuntimeError: zf = ZipFile(memory_file, mode='w') for attached_file in attached_files_list: zf.writestr(attached_file, builder.extract(attached_file)) zf.close() memory_file.seek(0) self.OLE_documents_zipstring = memory_file.read() self.content_type = builder.getMimeType() file = builder.prepareContentXml(self.ooo_xml_file_id) return ZopePageTemplate.pt_upload(self, REQUEST, file)
def manage_delObjects(self, ids=[], REQUEST=None): """Delete a subordinate object The objects specified in 'ids' get deleted. """ if isinstance(ids, basestring): 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 manageProperties(self, REQUEST=None, **kwargs): """ """ if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG) if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if REQUEST is not None: schema_raw_data = dict(REQUEST.form) else: schema_raw_data = kwargs _lang = schema_raw_data.pop('_lang', schema_raw_data.pop('lang', None)) _releasedate = self.process_releasedate( schema_raw_data.pop('releasedate', ''), self.releasedate) _approved = int(bool(schema_raw_data.pop('approved', False))) _subtitle = schema_raw_data.pop('subtitle', '') form_errors = self.process_submitted_form( schema_raw_data, _lang, _override_releasedate=_releasedate) if form_errors: raise ValueError(form_errors.popitem()[1]) # pick a random error self._setLocalPropValue('subtitle', _lang, _subtitle) if _approved != self.approved: if _approved == 0: _approved_by = None else: _approved_by = self.REQUEST.AUTHENTICATED_USER.getUserName() self.approveThis(_approved, _approved_by) self._p_changed = 1 self.recatalogNyObject(self) if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')
def manage_renameObject(self, id, new_id, REQUEST=None): """Rename a particular sub-object. """ 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) try: ob._notifyOfCopyTo(self, op=1) except ConflictError: raise except: raise CopyError(MessageDialog( title="Rename Error", message=sys.exc_info()[1], action ='manage_main')) notify(ObjectWillBeMovedEvent(ob, self, id, self, new_id)) try: self._delObject(id, suppress_events=True) except TypeError: self._delObject(id) warnings.warn( "%s._delObject without suppress_events is discouraged." % self.__class__.__name__, DeprecationWarning) 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. try: self._setObject(new_id, ob, set_owner=0, suppress_events=True) except TypeError: self._setObject(new_id, ob, set_owner=0) warnings.warn( "%s._setObject without suppress_events is discouraged." % self.__class__.__name__, DeprecationWarning) ob = self._getOb(new_id) notify(ObjectMovedEvent(ob, self, id, self, new_id)) notifyContainerModified(self) ob._postCopy(self, op=1) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1) return None
def manage_file_upload(self, file='', content_type='', is_preview=0, create_prev=NO_PREVIEW, maxx='', maxy='', ratio=0, REQUEST=None): """ Upload image from file handle or local directory """ if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if is_preview: if isinstance(file, str): file = open(file, 'rb') maxx, maxy = self._formatDimensions(maxx, maxy) if create_prev == UPLOAD_RESIZE and maxx != 0 and maxy != 0: self._register() # Register with TM try: new_fn = self._get_ufn(self.prev_filename, content_type='image/jpeg') self._update_data(file, self._temp_fsname(new_fn)) finally: self._dir__unlock() self._createPreview(new_fn, new_fn, maxx, maxy, ratio) else: if content_type: file = HTTPUpload(file, content_type) content_type = self._get_content_type(file, file.read(100), self.id, self.prev_content_type) file.seek(0) self._register() # Register with TM try: backup = REPOSITORY_EXTENSIONS in (MIMETYPE_APPEND, MIMETYPE_REPLACE) and \ self.prev_filename and self.prev_content_type != content_type new_fn = self._get_ufn(self.prev_filename, content_type=content_type, backup=backup) self._update_data(file, self._temp_fsname(new_fn)) finally: self._dir__unlock() self.prev_filename = new_fn self.prev_content_type = content_type self._initPreview() else: super(ExtImage, self).manage_file_upload(file, content_type) if create_prev == GENERATE: maxx, maxy = self._formatDimensions(maxx, maxy) if maxx != 0 and maxy != 0: self._register() # Register with TM try: new_fn = self._get_ufn(self.prev_filename, content_type='image/jpeg') self._createPreview(self.filename, new_fn, maxx, maxy, ratio) finally: self._dir__unlock() if REQUEST is not None: return self.manage_main(self, REQUEST, manage_tabs_message='Upload complete.')