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 type(file) is not StringType: 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 replaceIncludes(path): # Find the page template based on the path and remove path from dict document = self._resolvePath(path) document_text = ZopePageTemplate.pt_render( document, extra_context=extra_context) # Find the type of the embedded document document_type = document.content_type # Prepare a subdirectory to store embedded objects actual_idx = self.document_counter.next() dir_name = '%s%d' % (self._OLE_directory_prefix, actual_idx) if sub_document: # sub-document means sub-directory dir_name = sub_document + '/' + dir_name # Get the stylesheet of the embedded openoffice document ooo_stylesheet = document.ooo_stylesheet if ooo_stylesheet: ooo_stylesheet = getattr(here, ooo_stylesheet) # If ooo_stylesheet is dynamic, call it try: ooo_stylesheet = ooo_stylesheet() except AttributeError: pass temp_builder = OOoBuilder(ooo_stylesheet) stylesheet = temp_builder.extract('styles.xml') else: stylesheet = None # Start recursion if necessary sub_attached_files_dict = {} if 'office:include' in document_text: # small optimisation to avoid recursion if possible (document_text, sub_attached_files_dict) = self.renderIncludes( document_text, dir_name, extra_context, request) # Attach content, style and settings if any attached_files_dict[dir_name] = dict(document=document_text, doc_type=document_type, stylesheet=stylesheet) attached_files_dict.update(sub_attached_files_dict) # Build the new tag new_path = './%s' % dir_name.split('/')[-1] return new_path
def replaceIncludes(path): # Find the page template based on the path and remove path from dict document = self._resolvePath(path) document_text = ZopePageTemplate.pt_render(document, extra_context=extra_context) # Find the type of the embedded document document_type = document.content_type # Prepare a subdirectory to store embedded objects actual_idx = self.document_counter.next() dir_name = '%s%d'%(self._OLE_directory_prefix, actual_idx) if sub_document: # sub-document means sub-directory dir_name = sub_document + '/' + dir_name # Get the stylesheet of the embedded openoffice document ooo_stylesheet = document.ooo_stylesheet if ooo_stylesheet: ooo_stylesheet = getattr(here, ooo_stylesheet) # If ooo_stylesheet is dynamic, call it try: ooo_stylesheet = ooo_stylesheet() except AttributeError: pass temp_builder = OOoBuilder(ooo_stylesheet) stylesheet = temp_builder.extract('styles.xml') else: stylesheet = None # Start recursion if necessary sub_attached_files_dict = {} if 'office:include' in document_text: # small optimisation to avoid recursion if possible (document_text, sub_attached_files_dict ) = self.renderIncludes(document_text, dir_name, extra_context, request) # Attach content, style and settings if any attached_files_dict[dir_name] = dict(document=document_text, doc_type=document_type, stylesheet=stylesheet) attached_files_dict.update(sub_attached_files_dict) # Build the new tag new_path = './%s' % dir_name.split('/')[-1] return new_path
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 type(file) is not StringType: 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 pt_render(self, source=0, extra_context={}): # Get request request = extra_context.get('REQUEST', self.REQUEST) # Get parent object (the one to render this template on) here = getattr(self, 'aq_parent', None) if here is None: # This is a system error raise ValueError, 'Can not render a template without a parent acquisition context' # Retrieve master document ooo_document = None # If script is setting, call it if self.ooo_script_name: ooo_script = getattr(here, self.ooo_script_name) ooo_document = ooo_script(self.ooo_stylesheet) else: ooo_document = getattr(here, self.ooo_stylesheet) format = request.get('format') try: # If style is dynamic, call it if getattr(aq_base(ooo_document), '__call__', None) is not None: request.set('format', None) ooo_document = ooo_document() finally: request.set('format', format) # Create a new builder instance ooo_builder = OOoBuilder(ooo_document) # Pass builder instance as extra_context extra_context['ooo_builder'] = ooo_builder # And render page template doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) if isinstance(doc_xml, unicode): doc_xml = doc_xml.encode('utf-8') # Replace the includes (doc_xml,attachments_dict) = self.renderIncludes(here, doc_xml, extra_context, request) try: default_styles_text = ooo_builder.extract('styles.xml') except AttributeError: default_styles_text = None # Add the associated files for dir_name, document_dict in attachments_dict.iteritems(): # Special case : the document is an OOo one if document_dict['doc_type'].startswith(self._OOo_content_type_root) or \ document_dict['doc_type'].startswith(self._ODF_content_type_root): ooo_builder.addFileEntry(full_path=dir_name, media_type=document_dict['doc_type']) ooo_builder.addFileEntry(full_path=dir_name + '/content.xml', media_type='text/xml', content=document_dict['document']) styles_text = default_styles_text if document_dict.has_key('stylesheet') and document_dict['stylesheet']: styles_text = document_dict['stylesheet'] if styles_text: ooo_builder.addFileEntry(full_path=dir_name + '/styles.xml', media_type='text/xml', content=styles_text) else: # Generic case ooo_builder.addFileEntry(full_path=dir_name, media_type=document_dict['doc_type'], content=document_dict['document']) # Replace content.xml in master openoffice template ooo_builder.replace(self.ooo_xml_file_id, doc_xml) # Old templates correction try: self.OLE_documents_zipstring except AttributeError: self.OLE_documents_zipstring = None # Convert if necessary opts = extra_context.get("options", dict()) # Get batch_mode batch_mode = opts.get('batch_mode', None) # If the file has embedded OLE documents, restore it if self.OLE_documents_zipstring: additional_builder = OOoBuilder( self.OLE_documents_zipstring ) for name in additional_builder.getNameList(): ooo_builder.replace(name, additional_builder.extract(name) ) # Update the META informations ooo_builder.updateManifest() # Produce final result if batch_mode: ooo = ooo_builder.render() else: ooo = ooo_builder.render(name=self.title or self.id, source=source) if DevelopmentMode: # Validate XML in development mode from Products.ERP5OOo.tests.utils import Validator err_list = Validator().validate(ooo) if err_list: LOG('ERP5OOo', PROBLEM, 'Validation of %s failed:\n%s' % (self.getId(), ''.join(err_list))) extension = None mimetype = ooo_builder.getMimeType() mimetypes_registry = self.getPortalObject().mimetypes_registry mimetype_object_list = mimetypes_registry.lookup(mimetype) for mimetype_object in mimetype_object_list: if mimetype_object.extensions: extension = mimetype_object.extensions[0] break elif mimetype_object.globs: extension = mimetype_object.globs.strip('*.') break if extension: filename = '%s.%s' % (self._getFileName(), extension) else: filename = self._getFileName() from Products.ERP5Type.Document import newTempOOoDocument tmp_ooo = newTempOOoDocument(self, self.title_or_id()) tmp_ooo.edit(data=ooo, filename=filename, content_type=mimetype,) format = opts.get('format', request.get('format', None)) if format: # Performance improvement: # We already have OOo format data, so we do not need to call # convertToBaseFormat(), but just copy it into base_data property. tmp_ooo.setBaseData(ooo) tmp_ooo.setBaseContentType(mimetype) if request is not None and not batch_mode and not source: return tmp_ooo.index_html(REQUEST=request, RESPONSE=request.RESPONSE, format=format) return tmp_ooo.convert(format)[1]
def pt_render(self, source=0, extra_context={}): if source: return ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) # Get request request = extra_context.get('REQUEST', self.REQUEST) # Get parent object (the one to render this template on) here = getattr(self, 'aq_parent', None) if here is None: # This is a system error raise ValueError, 'Can not render a template without a parent acquisition context' # Retrieve master document ooo_document = None # If script is setting, call it if self.ooo_script_name: ooo_script = getattr(here, self.ooo_script_name) ooo_document = ooo_script(self.ooo_stylesheet) else: ooo_document = getattr(here, self.ooo_stylesheet) format = request.get('format') try: # If style is dynamic, call it if getattr(aq_base(ooo_document), '__call__', None) is not None: request.set('format', None) ooo_document = ooo_document() finally: request.set('format', format) # Create a new builder instance ooo_builder = OOoBuilder(ooo_document) # Pass builder instance as extra_context extra_context['ooo_builder'] = ooo_builder # And render page template doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) if isinstance(doc_xml, unicode): doc_xml = doc_xml.encode('utf-8') # Replace the includes (doc_xml, attachments_dict) = self.renderIncludes(here, doc_xml, extra_context, request) try: default_styles_text = ooo_builder.extract('styles.xml') except AttributeError: default_styles_text = None # Add the associated files for dir_name, document_dict in attachments_dict.iteritems(): # Special case : the document is an OOo one if document_dict['doc_type'].startswith(self._OOo_content_type_root) or \ document_dict['doc_type'].startswith(self._ODF_content_type_root): ooo_builder.addFileEntry(full_path=dir_name, media_type=document_dict['doc_type']) ooo_builder.addFileEntry(full_path=dir_name + '/content.xml', media_type='text/xml', content=document_dict['document']) styles_text = default_styles_text if document_dict.has_key( 'stylesheet') and document_dict['stylesheet']: styles_text = document_dict['stylesheet'] if styles_text: ooo_builder.addFileEntry(full_path=dir_name + '/styles.xml', media_type='text/xml', content=styles_text) else: # Generic case ooo_builder.addFileEntry(full_path=dir_name, media_type=document_dict['doc_type'], content=document_dict['document']) # Replace content.xml in master openoffice template ooo_builder.replace(self.ooo_xml_file_id, doc_xml) # Old templates correction try: self.OLE_documents_zipstring except AttributeError: self.OLE_documents_zipstring = None # Convert if necessary opts = extra_context.get("options", {}) # Get batch_mode batch_mode = opts.get('batch_mode', None) # If the file has embedded OLE documents, restore them if self.OLE_documents_zipstring: additional_builder = OOoBuilder(self.OLE_documents_zipstring) for name in additional_builder.getNameList(): if name not in ('META-INF/manifest.xml', ): # We don't replace manifest ooo_builder.replace(name, additional_builder.extract(name)) # Update the META information ooo_builder.updateManifest() # Produce final result if batch_mode: ooo = ooo_builder.render() else: ooo = ooo_builder.render(name=self.title or self.id, source=source) extension = None mimetype = ooo_builder.getMimeType() mimetypes_registry = self.getPortalObject().mimetypes_registry mimetype_object_list = mimetypes_registry.lookup(mimetype) for mimetype_object in mimetype_object_list: if mimetype_object.extensions: extension = mimetype_object.extensions[0] break elif mimetype_object.globs: extension = mimetype_object.globs.strip('*.') break if extension: filename = '%s.%s' % (self._getFileName(), extension) else: filename = self._getFileName() from Products.ERP5Type.Document import newTempOOoDocument tmp_ooo = newTempOOoDocument(self, self.title_or_id()) tmp_ooo.edit( data=ooo, filename=filename, content_type=mimetype, ) format = opts.get('format', request.get('format', None)) if format: # Performance improvement: # We already have OOo format data, so we do not need to call # convertToBaseFormat(), but just copy it into base_data property. tmp_ooo.setBaseData(ooo) tmp_ooo.setBaseContentType(mimetype) if request is not None and not batch_mode and not source: return tmp_ooo.index_html(REQUEST=request, RESPONSE=request.RESPONSE, format=format) return tmp_ooo.convert(format)[1]