def toZippedXml(self, REQUEST, get_data=True, incl_embedded=False): #-- Create temporary folder. tempfolder = tempfile.mktemp() ressources = self.exportRessources(tempfolder, REQUEST, incl_embedded=incl_embedded) #-- Get xml-export. xml = self.toXml(REQUEST, incl_embedded) #-- Write xml-export to file. xmlfilename = _fileutil.getOSPath( '%s/%s_%s.xml' % (tempfolder, self.getHome().id, self.meta_id)) _fileutil.exportObj(xml, xmlfilename) #-- Get zip-file. zipfiles = _fileutil.getOSPath('%s/*' % tempfolder) rtn = _fileutil.buildZipArchive(zipfiles, get_data) #-- Remove temporary folder. if not _globals.debug(self): _fileutil.remove(tempfolder, deep=1) return rtn
def initTheme(self, theme, new_id, REQUEST): filename = _fileutil.extractFilename(theme) id = filename[:filename.rfind('.')] ### Store copy of ZEXP in INSTANCE_HOME/import-folder. filepath = INSTANCE_HOME + '/import/' + filename if theme.startswith('http://'): initutil = _globals.initutil() initutil.setConfProperty('HTTP.proxy', REQUEST.get('http_proxy', '')) zexp = _globals.http_import(initutil, theme) _fileutil.exportObj(zexp, filepath) else: packagepath = package_home(globals()) + '/import/' + filename try: os.stat(_fileutil.getOSPath(filepath)) except OSError: shutil.copy(packagepath, filepath) ### Import theme from ZEXP. _fileutil.importZexp(self, filename) ### Assign folder-id. if id != new_id: self.manage_renameObject(id=id, new_id=new_id) ### Return new ZMS home instance. return getattr(self, new_id)
def exportFolder(self, root, path, id, REQUEST, depth=0): if hasattr(root, id): folder = getattr(root, id) for ob in folder.objectValues(): if ob.meta_type == 'Folder': ob_id = ob.id exportFolder(self, ob, '%s/%s' % (path, id), ob_id, REQUEST, depth + 1) elif ob.meta_type not in [ 'User Folder' ] and 'content' not in folder.objectIds(['ZMS']): try: ob_id = ob.id() except: ob_id = str(ob.id) if ob.meta_type in ['DTML Document', 'DTML Method']: try: html = ob.raw html = _globals.dt_html(self, html, REQUEST) html = localHtml(ob, html) html = localIndexHtml( self, ob, len(ob.absolute_url().split('/')) - len(root.absolute_url().split('/')) + depth, html) ob = html except: pass _fileutil.exportObj(ob, '%s/%s/%s' % (path, id, ob_id))
def exportRessources(self, tempfolder, REQUEST, from_content=True, from_zms=False, from_home=False, incl_embedded=False): ressources = [] if from_zms: folder = 'misc_/zms' for obj_id in self.misc_.zms._d.keys(): _fileutil.exportObj(self.misc_.zms[obj_id], '%s/%s/%s' % (tempfolder, folder, obj_id)) exportFiles(self, self.getDocumentElement(), 'metaobj_manager', '%s/metaobj_manager' % tempfolder) if from_home: root = self.getHome() exportFiles(self, root.aq_parent, root.id, tempfolder) for id in root.objectIds(['Folder']): exportFolder(self, root, tempfolder, id, REQUEST) if from_content: base_path = tempfolder + '/' ressources.extend( _blobfields.recurse_downloadRessources(self, base_path, REQUEST, incl_embedded)) return ressources
def rotate(self, img, direction, qual=75): """ Rotate image. """ try: from PIL import Image except: import Image # Save image in temp-folder tempfolder = tempfile.mktemp() filepath = _fileutil.getOSPath('%s/%s' % (tempfolder, img.filename)) _fileutil.exportObj(img, filepath) # Rotate image im = Image.open(filepath) im = im.rotate(direction) im.save(filepath, "JPEG", quality=qual) # Read resized image from file-system f = open(filepath, 'rb') result_data = f.read() result_filename = _fileutil.extractFilename(filepath) result = {'data': result_data, 'filename': result_filename} f.close() # Remove temp-folder and images _fileutil.remove(tempfolder, deep=1) # Returns resulting image image = self.context.ImageFromData(result['data'], result['filename']) return image ################################################################################
def storeFile(self, file): filename = _fileutil.extractFilename(file.filename) if len(filename) > 0: fileext = _fileutil.extractFileExt(file.filename) filename = filename[:-(len(fileext) + 1)] + '_' + str( time.time()).replace('.', '') + '.' + fileext filepath = _fileutil.getOSPath('%s/%s' % (self.location, filename)) _fileutil.exportObj(file, filepath) return filename
def exportFiles(self, root, id, path): if hasattr(root, id): folder = getattr(root, id) for ob in folder.objectValues(['File', 'Image']): try: ob_id = ob.id() except: ob_id = str(ob.id) _fileutil.exportObj(ob, '%s/%s' % (path, ob_id))
def execProcessFilter(self, ob_process, folder, filename, REQUEST): processId = ob_process.get( 'id') processOb = self.getProcess( processId) if processOb is not None: processType = processOb.get( 'type', 'process') trans = ob_process.get( 'file', None) # Save transformation to file. if trans is not None and trans != '': transfilename = '%s/%s'%( folder, trans.getFilename()) _fileutil.exportObj( trans.getData(), transfilename) if processType in [ 'DTML Method', 'External Method', 'Script (Python)']: filename = processMethod(self, processId, filename, trans, REQUEST) else: filename = processFile(self, processId, filename, trans) # Return filename. return filename
def importFile(self, file, REQUEST, handler): message = '' # Get filename. if isinstance(file,ZPublisher.HTTPRequest.FileUpload): filename = file.filename else: filename = file.name _globals.writeBlock( self, '[importFile]: filename='+filename) # Create temporary folder. folder = tempfile.mktemp() os.mkdir(folder) # Save to temporary file. filename = _fileutil.getOSPath('%s/%s'%(folder,_fileutil.extractFilename(filename))) _fileutil.exportObj(file,filename) # Find XML-file. if _fileutil.extractFileExt(filename) == 'zip': _fileutil.extractZipArchive(filename) filename = None for deep in [0,1]: for ext in ['xml', 'htm', 'html' ]: if filename is None: filename = _fileutil.findExtension(ext, folder, deep) break if filename is None: raise zExceptions.InternalError('XML-File not found!') # Import Filter. if REQUEST.get('filter','') in self.getFilterIds(): filename = _filtermanager.importFilter(self, filename, REQUEST.get('filter',''), REQUEST) # Import XML-file. _globals.writeBlock( self, '[importFile]: filename='+filename) f = open(filename, 'r') message += handler(self, f) f.close() # Remove temporary files. _fileutil.remove(folder, deep=1) # Return with message. message += self.getZMILangStr('MSG_IMPORTED')%('<i>%s</i>'%_fileutil.extractFilename(filename)) return message
def processData(self, processId, data, trans=None): # Create temporary folder. folder = tempfile.mktemp() # Save data to file. filename = _fileutil.getOSPath('%s/in.dat'%folder) _fileutil.exportObj(data, filename) # Save transformation to file. if trans is not None and trans != '': transfilename = _fileutil.getOSPath('%s/%s'%(folder,trans.getFilename())) _fileutil.exportObj(trans, transfilename) # Process file. filename = processFile(self, processId, filename, trans) # Read data from file. f = open(filename, 'rb') data = f.read() f.close() # Remove temporary folder. if not _globals.debug( self): _fileutil.remove(folder, deep=1) # Return data. return data
def manage_submit(self, REQUEST, RESPONSE): """ZMSLog.manage_submit""" path = self.getPath(REQUEST) message = "" if REQUEST.get("btn") == "Execute": command = REQUEST['command'] _fileutil.executeCommand(path, command) message = "Command executed." elif REQUEST.get("btn") == "Upload": obj = REQUEST['file'] type = 'b' filename = "%s%s%s" % (path, os.sep, _fileutil.extractFilename(obj.filename)) _fileutil.exportObj(obj, filename, type) message = "Upload complete." return REQUEST.RESPONSE.redirect( self.url_append_params(REQUEST['HTTP_REFERER'], {'manage_tabs_message': message}))
def initExportFilter(self, id, REQUEST): # Set environment variables. instance_home = INSTANCE_HOME software_home = os.path.join(SOFTWARE_HOME, '..%s..' % os.sep) software_home = os.path.normpath(software_home) REQUEST.set( 'ZMS_FILTER', True) REQUEST.set( 'ZMS_FILTER_SOFTWARE_HOME', software_home) REQUEST.set( 'ZMS_FILTER_INSTANCE_HOME', instance_home) REQUEST.set( 'ZMS_FILTER_PACKAGE_HOME', _fileutil.getOSPath(package_home(globals()))) # Set local variables. ob_filter = self.getFilter(id) ob_filter_format = ob_filter.get('format','') incl_embedded = ob_filter_format == 'XML_incl_embedded' # Create temporary folder. tempfolder = tempfile.mktemp() ressources = self.exportRessources( tempfolder, REQUEST, from_zms=ob_filter_format=='XHTML', from_home=ob_filter_format=='XHTML', incl_embedded=incl_embedded) # Export data to file. if ob_filter_format == 'export': outfilename = _fileutil.getOSPath('%s/INDEX0'%tempfolder) elif ob_filter_format in ['XML','XML_incl_embedded']: # Set XML. data = self.toXml( REQUEST, incl_embedded) outfilename = _fileutil.getOSPath('%s/export.xml'%tempfolder) _fileutil.exportObj( data, outfilename) elif ob_filter_format == 'XHTML': # Set XHTML. data = self.toXhtml( REQUEST) outfilename = _fileutil.getOSPath('%s/export.html'%tempfolder) _fileutil.exportObj( data, outfilename) elif ob_filter_format == 'myXML': # Set myXML. data = self.getXmlHeader() + getattr( self, 'getObjToXml_DocElmnt')(context=self) outfilename = _fileutil.getOSPath('%s/export.xml'%tempfolder) _fileutil.exportObj( data, outfilename) else: raise zExceptions.InternalError("Unknown format '%s'"%ob_filter.get('format','')) return tempfolder, outfilename
def recurse_downloadRessources(self, base_path, REQUEST, incl_embedded): ressources = [] # Check Constraints. root = getattr(self, '__root__', None) if root is not None: return ressources ob = self if ob.meta_id == 'ZMSLinkElement' and ob.isEmbedded( REQUEST) and incl_embedded: ob = ob.getRefObj() # Attributes. langs = ob.getLangIds() prim_lang = ob.getPrimaryLanguage() obj_attrs = ob.getObjAttrs() for key in obj_attrs.keys(): obj_attr = ob.getObjAttr(key) datatype = obj_attr['datatype_key'] if datatype in _globals.DT_BLOBS: for lang in langs: try: if obj_attr['multilang'] or lang == prim_lang or ( obj_attr['multilang'] == 0 and lang != prim_lang): req = {'lang': lang, 'preview': 'preview'} obj_vers = ob.getObjVersion(req) blob = ob._getObjAttrValue(obj_attr, obj_vers, lang) if blob is not None: filename = blob.getFilename() filename = getLangFilename(ob, filename, lang) filename = '%s%s' % (base_path, filename) filename = _fileutil.getOSPath(filename) _fileutil.exportObj(blob, filename) ressources.append({ 'filepath': filename, 'content_type': blob.getContentType() }) except: _globals.writeError( ob, "[recurse_downloadRessources]: Can't export %s" % key) elif datatype == _globals.DT_LIST: for lang in langs: try: if obj_attr['multilang'] or lang == prim_lang or ( obj_attr['multilang'] == 0 and lang != prim_lang): req = {'lang': lang, 'preview': 'preview'} obj_vers = ob.getObjVersion(req) v = ob._getObjAttrValue(obj_attr, obj_vers, lang) i = 0 for r in v: uu = [] if type(r) is dict: for k in r.keys(): u = r[k] if isinstance(u, MyImage) or isinstance( u, MyFile): uu.append(u) elif isinstance(r, MyImage) or isinstance( r, MyFile): uu.append(r) for u in uu: filename = u.getFilename() filename = getLangFilename(ob, filename, lang) filename = '%s@%i/%s' % (base_path, i, filename) filename = _fileutil.getOSPath(filename) _fileutil.exportObj(u, filename) ressources.append({ 'filepath': filename, 'content_type': u.getContentType() }) i = i + 1 except: _globals.writeError( ob, "[recurse_downloadRessources]: Can't export %s" % key) # Process children. for child in ob.getChildNodes(): ressources.extend( recurse_downloadRessources(child, base_path + child.id + '/', REQUEST, incl_embedded)) # Return list of ressources. return ressources
def resize(self, img, size, mode='resize', sffx='_thumbnail', qual=75): """ Resize image. """ try: from PIL import Image except: import Image # Save image in temp-folder tempfolder = tempfile.mktemp() filepath = _fileutil.getOSPath('%s/%s' % (tempfolder, img.filename)) _fileutil.exportObj(img, filepath) # Resize image im = Image.open(filepath) im = im.convert('RGB') maxdim = max(list(size)) if mode == 'thumbnail': try: im.thumbnail((maxdim, maxdim), Image.ANTIALIAS) except: im.thumbnail((maxdim, maxdim)) im.save(infile, "JPEG", quality=qual) elif mode == 'resize': try: im = im.resize(size, Image.ANTIALIAS) except: im = im.resize(size) elif mode == 'square': try: width, height = im.size dst_width, dst_height = maxdim, maxdim if width > height: delta = width - height left = int(delta / 2) upper = 0 right = height + left lower = height else: delta = height - width left = 0 upper = int(delta / 2) right = width lower = width + upper im = im.crop((left, upper, right, lower)) im = im.resize((dst_width, dst_height), Image.ANTIALIAS) except: im.resize(size) im.save(filepath, "JPEG", quality=qual) # Read resized image from file-system f = open(filepath, 'rb') result_data = f.read() thumb_sffx = str(sffx) getfilename = _fileutil.extractFilename(filepath).split('.') filename = getfilename[0:-1] filename = ".".join(filename) filename = filename.replace('.', '_') extension = _fileutil.extractFileExt(filepath) result_filename = filename + thumb_sffx + '.' + extension result = {'data': result_data, 'filename': result_filename} f.close() # Remove temp-folder and images _fileutil.remove(tempfolder, deep=1) # Returns resulting image image = self.context.ImageFromData(result['data'], result['filename']) return image
def manage_customizeDesign(self, btn, lang, REQUEST, RESPONSE): """ ConfManager.manage_customizeDesign """ message = '' cssId = REQUEST.get('cssId', '') # Ex-/Import. # ----------- if btn in [ self.getZMILangStr('BTN_EXPORT'), self.getZMILangStr('BTN_IMPORT') ]: #-- Theme. home = self.getHome() home_id = home.id temp_folder = self.temp_folder # Init exclude-ids. excl_ids = [] # Add clients-folders to exclude-ids. for folder in home.objectValues(['Folder']): if len(folder.objectValues(['ZMS'])) > 0: excl_ids.append(absattr(folder.id)) # Add content-object artefacts to exclude-ids. for metaObjId in self.getMetaobjIds(): for metaObjAttrId in self.getMetaobjAttrIds(metaObjId): metaObjAttr = self.getMetaobjAttr(metaObjId, metaObjAttrId) if metaObjAttr[ 'type'] in self.metaobj_manager.valid_zopetypes: excl_ids.append(metaObjAttrId) # Filter ids. ids = filter(lambda x: x not in excl_ids, home.objectIds(self.metaobj_manager.valid_zopetypes)) if btn == self.getZMILangStr('BTN_EXPORT'): if home_id in temp_folder.objectIds(): temp_folder.manage_delObjects(ids=[home_id]) temp_folder.manage_addFolder(id=home_id, title=home.title_or_id()) folder = getattr(temp_folder, home_id) home.manage_copyObjects(ids, REQUEST) folder.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST) return RESPONSE.redirect( self.url_append_params( '%s/manage_exportObject' % temp_folder.absolute_url(), { 'id': home_id, 'download:int': 1 })) if btn == self.getZMILangStr('BTN_IMPORT'): v = REQUEST['theme'] temp_filename = _fileutil.extractFilename(v.filename) temp_id = temp_filename[:temp_filename.rfind('.')] filepath = INSTANCE_HOME + '/import/' + temp_filename _fileutil.exportObj(v, filepath) if temp_id in temp_folder.objectIds(): temp_folder.manage_delObjects(ids=[temp_id]) temp_folder.manage_importObject(temp_filename) folder = getattr(temp_folder, temp_id) home.manage_delObjects(ids=ids) folder.manage_copyObjects(folder.objectIds(), REQUEST) home.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST) _fileutil.remove(filepath) temp_folder.manage_delObjects(ids=[temp_id]) # Save. # ----- if btn == self.getZMILangStr('BTN_SAVE'): #-- Stylesheet. if REQUEST.has_key('cssId'): if REQUEST.get('default'): self.setConfProperty('ZMS.stylesheet', REQUEST.get('cssId')) css = self.getStylesheet(REQUEST.get('cssId')) data = REQUEST.get('stylesheet') title = css.title css.manage_edit(data, title) message = self.getZMILangStr('MSG_CHANGED') #-- Sitemap. if REQUEST.has_key('attr_layoutsitemap'): if len(REQUEST['attr_layoutsitemap']) > 0: self.attr_layoutsitemap = int( REQUEST['attr_layoutsitemap']) elif hasattr(self, 'attr_layoutsitemap'): delattr(self, 'attr_layoutsitemap') message = self.getZMILangStr('MSG_CHANGED') # Upload. # ------- elif btn == self.getZMILangStr('BTN_UPLOAD'): #-- ZMI Logo. self.zmi_logo = Image(id='logo', title='', file='') self.zmi_logo.manage_upload(REQUEST['file'], REQUEST) message = self.getZMILangStr('MSG_CHANGED') # Return with message. message = urllib.quote(message) return RESPONSE.redirect( 'manage_customizeDesignForm?lang=%s&manage_tabs_message=%s&cssId=%s' % (lang, message, cssId))
def toCdata(self, s, xhtml=0): rtn = '' # Return Text (HTML) in CDATA as XHTML. from _filtermanager import processCommand processId = 'tidy' if xhtml == 0 \ and self.getConfProperty('ZMS.export.xml.tidy',0) \ and processId in self.getProcessIds(): # Create temporary folder. folder = tempfile.mktemp() os.mkdir(folder) # Save <HTML> to file. filename = _fileutil.getOSPath('%s/xhtml.html' % folder) _fileutil.exportObj(s, filename) # Call <HTML>Tidy processOb = self.getProcess(processId) command = processOb.get('command') if command.find('{trans}') >= 0: trans = _fileutil.getOSPath( package_home(globals()) + '/conf/xsl/tidy.html2xhtml.conf') command = command.replace('{trans}', trans) filename = processCommand(self, filename, command) # Read <XHTML> from file. f = open(htmfilename, 'rb') rtn = f.read().strip() f.close() # Read Error-Log from file. f = open(logfilename, 'rb') log = f.read().strip() f.close() # Remove temporary files. _fileutil.remove(folder, deep=1) # Process <XHTML>. prefix = '<p>' if s[:len(prefix)] != prefix and rtn[:len(prefix)] == prefix: rtn = rtn[len(prefix):] suffix = '</p>' if s[-len(suffix):] != suffix and rtn[-len(suffix):] == suffix: rtn = rtn[:-len(suffix)] f.close() # Process Error-Log. if log.find('0 errors') < 0: rtn += '<!-- ' + log + '-->' # Return Text. elif xhtml == -1 \ or type(s) is float \ or type(s) is int: rtn = s # Return Text in CDATA. elif s is not None: # Hack for invalid characters s = s.replace(chr(30), '') # Hack for nested CDATA s = re.compile('\<\!\[CDATA\[(.*?)\]\]\>').sub('<!{CDATA{\\1}}>', s) rtn = '<![CDATA[%s]]>' % s # Return. return rtn