def preprocess(self): names = [] for level in range(self.levels + 1): t = (TILESIZE << (self.levels - level)) for x in range((self.width + (t - 1)) / t): for y in range((self.height + (t - 1)) / t): names.append(self.getTile(level, x, y, 1)) # open the zip file for writing, and write stuff to it file = zipfile.ZipFile(self.filepath + "/zoom{}.zip".format(self.node.id), "w") for name in names: file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) os.unlink(name) file.close() l = config.get("paths.datadir") self.node.addFile( tree.FileNode(name=self.filepath[len(l):] + "/zoom{}.zip".format(self.node.id), mimetype="application/zip", type="zoom"))
def getContent(req, ids): user = users.getUserFromRequest(req) if "lza" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") v = {} v['error'] = "" nodes = [] for id in ids: node = tree.getNode(id) access = acl.AccessData(req) if not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") nodes.append(node) if "createlza" in req.params: # remove old file if existing for f in node.getFiles(): if f.getType() == "lza": node.removeFile(f) # create new file for f in node.getFiles(): if f.getType() in ("original", "document"): try: archive = l.LZA(f.retrieveFile()) schema = node.getSchema() # test for lza export mask if (getMetaType(schema).getMask("lza")): m = getMetaType(schema).getMask("lza") meta = l.LZAMetadata(m.getViewHTML([node], 8)) else: # generate error message meta = l.LZAMetadata(""" <?xpacket begin="\xef\xbb\xbf" id="mediatum_metadata"?> <lza:data> <lza:error>-definition missing-</lza:error> </lza:data><?xpacket end="w"?> """) archive.writeMediatumData(meta) node.addFile( tree.FileNode(archive.buildLZAName(), "lza", f.getMimeType())) except l.FiletypeNotSupported: v['error'] = "edit_lza_wrongfiletype" elif "removelza" in req.params: for f in node.getFiles(): if f.getType() == "lza": node.removeFile(f) v['id'] = req.params.get("id", "0") v['tab'] = req.params.get("tab", "") v['ids'] = ids v['nodes'] = nodes v['t'] = t v['language'] = lang(req) meta = {} for id in ids: node = tree.getNode(id) for f in node.getFiles(): if f.getType() == "lza": try: archive = l.LZA(f.retrieveFile(), f.getMimeType()) meta[id] = archive.getMediatumData() except IOError: v['error'] = "edit_lza_ioerror" v['meta'] = meta return req.getTAL("web/edit/modules/lza.html", v, macro="edit_lza")
def show_workflow_node(self, node, req, data=None): check_context() user = users.getUserFromRequest(req) access = AccessData(req) current_workflow = getNodeWorkflow(node) current_workflow_step = getNodeWorkflowStep(node) FATAL_ERROR = False FATAL_ERROR_STR = "" if "gotrue" in req.params: if not PYPDF_MODULE_PRESENT: del req.params['gotrue'] return self.show_workflow_node(node, req) radio_apply_reset_accept = req.params.get('radio_apply_reset_accept', '') if radio_apply_reset_accept == 'reset': for f in node.getFiles(): f_name = f.getName() if f_name.startswith('addpic2pdf_%s_node_%s_' % (str(current_workflow_step.id), str(node.id))) and f.type.startswith('p_document'): msg = "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)" % ( current_workflow_step.id, f_name, node.name, str(node.id), user.name, str(req.ip)) logging.getLogger("backend").info(msg) node.removeFile(f) try: os.remove(f.retrieveFile()) except: pass del req.params['gotrue'] return self.show_workflow_node(node, req) elif radio_apply_reset_accept == 'accept': p_document_files = [f for f in node.getFiles() if f.getType() == 'p_document' and f.getName().startswith( 'addpic2pdf_%s_node_%s_' % (str(current_workflow_step.id), str(node.id)))] if len(p_document_files) > 0: p_document_file = p_document_files[0] document_file = [f for f in node.getFiles() if f.getType() == 'document'][0] o_document_file = tree.FileNode(document_file._path, 'o_document', document_file.mimetype) node.removeFile(document_file) node.addFile(o_document_file) o_document_name = o_document_file.getName() for f in node.getFiles(): if f.type in ['thumb', 'fileinfo', 'fulltext'] or f.type.startswith('present'): if os.path.splitext(f.getName())[0] == os.path.splitext(o_document_name)[0]: new_f = tree.FileNode(f._path, 'o_' + f.getType(), f.mimetype) node.removeFile(f) node.addFile(new_f) new_document_file = tree.FileNode(p_document_file._path, 'document', p_document_file.mimetype) node.removeFile(p_document_file) node.addFile(new_document_file) if hasattr(node, "event_files_changed"): node.event_files_changed() else: pass del req.params['gotrue'] return self.forwardAndShow(node, True, req) elif radio_apply_reset_accept == 'apply': drag_logo_fullname = req.params.get("input_drag_logo_fullname", None) if not drag_logo_fullname: req.params["addpic2pdf_error"] = "%s: %s" % ( format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_logo_selected")) del req.params['gotrue'] return self.show_workflow_node(node, req) drag_logo_filepath = [f.retrieveFile() for f in current_workflow_step.getFiles() if f.getName() == drag_logo_fullname][0] pos_cm = req.params.get("input_poffset_cm", "0, 0") x_cm, y_cm = [float(x.strip()) for x in pos_cm.split(",")] pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node) current_pageno = int(req.params.get("input_current_page", "0").strip()) radio_select_targetpages = req.params.get("radio_select_targetpages", "").strip() input_select_targetpages = req.params.get("input_select_targetpages", "").strip() printer_range = [] page_count = get_pdf_pagecount(pdf_in_filepath) _parser_error = False try: if radio_select_targetpages == "current_page": printer_range = [current_pageno] elif radio_select_targetpages == "all": printer_range = range(0, page_count) elif radio_select_targetpages == "pair": printer_range = [x for x in range(0, page_count) if x % 2] if input_select_targetpages: printer_range = [x for x in printer_range if x in parse_printer_range( input_select_targetpages, maximum=page_count + 1)] elif radio_select_targetpages == "impair": printer_range = [x for x in range(0, page_count) if not x % 2] if input_select_targetpages: printer_range = [x for x in printer_range if x in parse_printer_range( input_select_targetpages, maximum=page_count + 1)] elif radio_select_targetpages == "range_only" and input_select_targetpages: printer_range = parse_printer_range(input_select_targetpages, maximum=page_count + 1) except ValueError as e: _parser_error = True if _parser_error: req.params["addpic2pdf_error"] = "%s: %s" % ( format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_error")) del req.params['gotrue'] return self.show_workflow_node(node, req) printer_range = map(int, list(printer_range)) if not printer_range: req.params["addpic2pdf_error"] = "%s: %s" % ( format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_selected_empty")) del req.params['gotrue'] return self.show_workflow_node(node, req) x = x_cm * cm # cm = 28.346456692913385 y = y_cm * cm pic_dpi = get_pic_info(drag_logo_filepath).get('dpi', None) scale = 1.0 if pic_dpi: dpi_x, dpi_y = pic_dpi if dpi_x != dpi_y: req.params["addpic2pdf_error"] = "%s: %s" % ( format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_logo_dpix_dpiy")) dpi = int(dpi_x) if dpi == 72: scale = 1.0 else: scale = 1.0 * 72.0 / dpi else: dpi = 300 scale = 1.0 * 72.0 / dpi #dpi = 72 #scale = 1.0 tmppath = config.get("paths.datadir") + "tmp/" date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-') filetempname = tmppath + \ "temp_addpic_pdf_wfs_%s_node_%s_%s_%s_.pdf" % ( str(current_workflow_step.id), str(node.id), date_str, str(random.random())) url = req.params.get('input_drag_logo_url', '') fn_out = filetempname build_logo_overlay_pdf(pdf_in_filepath, drag_logo_filepath, fn_out, x, y, scale=scale, mask='auto', pages=printer_range, follow_rotate=True, url=(" " * ADD_NBSP) + url) for f in node.getFiles(): f_name = f.getName() if f_name.startswith('addpic2pdf_%s_node_%s_' % (str(current_workflow_step.id), str(node.id), )) and f.type.startswith('p_document'): msg = "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)" % ( current_workflow_step.id, f_name, node.name, str(node.id), user.name, str(req.ip)) logging.getLogger("backend").info(msg) node.removeFile(f) try: os.remove(f.retrieveFile()) except: pass break date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-') nodeFile = importFileToRealname("_has_been_processed_%s.pdf" % (date_str), filetempname, prefix='addpic2pdf_%s_node_%s_' % ( str(current_workflow_step.id), str(node.id), ), typeprefix="p_") node.addFile(nodeFile) try: os.remove(filetempname) except: pass del req.params['gotrue'] return self.show_workflow_node(node, req) if "gofalse" in req.params: return self.forwardAndShow(node, False, req) # part of show_workflow_node not handled by "gotrue" and "gofalse" try: pdf_filepath = [f.retrieveFile() for f in node.getFiles() if f.getType().startswith('document')][0] error_no_pdf = False except: error_no_pdf = t(lang(req), "admin_wfstep_addpic2pdf_no_pdf_document_for_this_node") if not PYPDF_MODULE_PRESENT or error_no_pdf: error = "" if not PYPDF_MODULE_PRESENT: error += t(lang(req), "admin_wfstep_addpic2pdf_no_pypdf") if error_no_pdf: error += error_no_pdf pdf_dimensions = {'d_pageno2size': {0: [595.275, 841.889]}, 'd_pageno2rotate': {0: 0}} # A4 keep_params = copyDictValues(req.params, {}, KEEP_PARAMS) context = {"key": req.params.get("key", req.session.get("key", "")), "error": error, "node": node, "files": node.getFiles(), "wfs": current_workflow_step, "wfs_files": [], "logo_info": {}, "logo_info_list": [], "getImageSize": lambda x: (0, 0), "pdf_page_count": 0, "pdf_dimensions": pdf_dimensions, "json_pdf_dimensions": json.dumps(pdf_dimensions), "keep_params": json.dumps(keep_params), "startpageno": 0, "FATAL_ERROR": 'true', "user": users.getUserFromRequest(req), "prefix": self.get("prefix"), "buttons": self.tableRowButtons(node)} return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf") try: pdf_dimensions = get_pdf_dimensions(pdf_filepath) pdf_pagecount = get_pdf_pagecount(pdf_filepath) except Exception as e: msg = "workflow step addpic2pdf(%s): Error: %s" % (current_workflow_step.id, str(e)) logging.getLogger("backend").error(msg) pdf_dimensions = {'d_pages': 0, 'd_pageno2size': (0, 0), 'd_pageno2rotate': 0} pdf_pagecount = 0 FATAL_ERROR = True FATAL_ERROR_STR += " - %s" % (str(e)) #wfs_files = [f for f in current_workflow_step.getFiles() if os.path.isfile(f.retrieveFile())] wfs_files0, wfs_files = getFilelist(current_workflow_step, 'logoupload') url_mapping = [line.strip() for line in current_workflow_step.get("url_mapping").splitlines() if line.strip() and line.find("|") > 0] url_mapping = dict(map(lambda x: (x[0].strip(), x[1].strip()), [line.split("|", 1) for line in url_mapping])) logo_info = {} logo_info_list = [] for f in [f for f in wfs_files if f.getName().startswith('m_upload_logoupload')]: f_path = f.retrieveFile() try: _size = list(get_pic_size(f_path)) _dpi = get_pic_dpi(f_path) except Exception as e: logging.getLogger("backend").error("workflow step addpic2pdf(%s): Error: %s" % (current_workflow_step.id, str(e))) FATAL_ERROR = True FATAL_ERROR_STR += (" - ERROR loading logo '%s'" % str(f_path)) + str(e) continue logo_filename = f.getName() logo_url = "" for key in url_mapping: if logo_filename.find(key) >= 0: logo_url = url_mapping[key] break logo_info[logo_filename] = {'size': _size, 'dpi': _dpi, 'url': logo_url} if _dpi == 'no-info': _dpi = 72.0 logo_info_list.append({'size': _size, 'dpi': _dpi, 'url': logo_url}) if len(logo_info) == 0: logging.getLogger("backend").error("workflow step addpic2pdf(%s): Error: no logo images found" % (current_workflow_step.id)) FATAL_ERROR = True FATAL_ERROR_STR += " - Error: no logo images found" keep_params = copyDictValues(req.params, {}, KEEP_PARAMS) context = {"key": req.params.get("key", req.session.get("key", "")), "error": req.params.get('addpic2pdf_error', ''), "node": node, "files": node.getFiles(), "wfs": current_workflow_step, "wfs_files": wfs_files, "logo_info": logo_info, "logo_info_list": logo_info_list, "getImageSize": get_pic_size, "pdf_page_count": pdf_pagecount, "pdf_dimensions": pdf_dimensions, "json_pdf_dimensions": json.dumps(pdf_dimensions), "keep_params": json.dumps(keep_params), "startpageno": startpageno, "FATAL_ERROR": {False: 'false', True: 'true'}[bool(FATAL_ERROR)], "user": users.getUserFromRequest(req), "prefix": self.get("prefix"), "buttons": self.tableRowButtons(node)} if FATAL_ERROR: context["error"] += " - %s" % (FATAL_ERROR_STR) return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf")
def xml_start_element(self, name, attrs): try: node = self.nodes[-1] except: node = None if name == "nodelist": if "exportversion" in attrs: logging.getLogger("backend").info("starting xml import: %s" % str(attrs)) elif name == "node": self.node_already_seen = False parent = node try: type = attrs["type"].encode("utf-8") except: type = "directory" if "id" not in attrs: attrs["id"] = str(random.random()) old_id = attrs["id"] if old_id in self.id2node: node = self.id2node[old_id] self.node_already_seen = True return elif type in ["mapping"]: node = tree.Node(name=(attrs["name"] + "_imported_" + old_id).encode("utf-8"), type=type) else: node = tree.Node(name=attrs["name"].encode("utf-8"), type=type) if "read" in attrs: node.setAccess("read", attrs["read"].encode("utf-8")) if "write" in attrs: node.setAccess("write", attrs["write"].encode("utf-8")) if "data" in attrs: node.setAccess("data", attrs["data"].encode("utf-8")) if self.verbose: msg = "created node '%s', '%s', '%s', old_id from attr='%s'" % (node.name, node.type, str(node.id), str(attrs["id"])) logging.getLogger("backend").info(msg) self.id2node[attrs["id"].encode("utf-8")] = node node.tmpchilds = [] self.nodes += [node] if self.root is None: self.root = node return elif name == "attribute" and not self.node_already_seen: attr_name = attrs["name"].encode("utf-8") if "value" in attrs: if attr_name in ["valuelist"]: node.setAttribute(attr_name, attrs["value"].encode("utf-8").replace("\n\n", "\n").replace("\n", ";").replace(";;", ";")) else: node.setAttribute(attr_name, attrs["value"].encode("utf-8")) else: self.attributename = attr_name elif name == "child" and not self.node_already_seen: id = u(attrs["id"]) node.tmpchilds += [id] elif name == "file" and not self.node_already_seen: try: type = attrs["type"].encode("utf-8") except: type = None try: mimetype = attrs["mime-type"].encode("utf-8") except: mimetype = None filename = attrs["filename"].encode("utf-8") node.addFile(tree.FileNode(name=filename, type=type, mimetype=mimetype))
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) node = tree.getNode(ids[0]) update_error = False access = acl.AccessData(req) msg = "%s|web.edit.modules.files.getContend|req.fullpath=%r|req.path=%r|req.params=%r|ids=%r" % ( get_user_id(req), req.fullpath, req.path, req.params, ids) log.debug(msg) if not access.hasWriteAccess(node) or "files" in users.getHideMenusForUser( user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") if 'data' in req.params: if req.params.get( 'data' ) == 'children': # get formated list of childnodes of selected directory req.writeTAL("web/edit/modules/files.html", {'children': node.getChildren()}, macro="edit_files_popup_children") if req.params.get( 'data') == 'additems': # add selected node as children for childid in req.params.get('items').split(";"): if childid.strip() != "": childnode = tree.getNode(childid.strip()) for p in childnode.getParents(): p.removeChild(childnode) node.addChild(childnode) req.writeTAL("web/edit/modules/files.html", { 'children': node.getChildren(), 'node': node }, macro="edit_files_children_list") if req.params.get( 'data') == 'removeitem': # remove selected childnode node try: remnode = tree.getNode(req.params.get('remove')) if len(remnode.getParents()) == 1: users.getUploadDir(user).addChild(remnode) node.removeChild(remnode) except: # node not found pass req.writeTAL("web/edit/modules/files.html", { 'children': node.getChildren(), 'node': node }, macro="edit_files_children_list") if req.params.get('data') == 'reorder': i = 0 for id in req.params.get('order').split(","): if id != "": n = tree.getNode(id) n.setOrderPos(i) i += 1 if req.params.get('data') == 'translate': req.writeTALstr( '<tal:block i18n:translate="" tal:content="msgstr"/>', {'msgstr': req.params.get('msgstr')}) return "" if req.params.get("style") == "popup": v = {"basedirs": [tree.getRoot('home'), tree.getRoot('collections')]} id = req.params.get("id", tree.getRoot().id) v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s';\nvar node = %s;" % ( id, req.params.get('parent'), id) v["idstr"] = ",".join(ids) v["node"] = node req.writeTAL("web/edit/modules/files.html", v, macro="edit_files_popup_selection") return "" if "operation" in req.params: op = req.params.get("operation") if op == "delete": for key in req.params.keys(): # delete file if key.startswith("del|"): filename = key[4:-2].split("|") for file in node.getFiles(): if file.getName( ) == filename[1] and file.type == filename[0]: # remove all files in directory if file.getMimeType() == "inode/directory": for root, dirs, files in os.walk( file.retrieveFile()): for name in files: try: os.remove(root + "/" + name) except: pass os.removedirs(file.retrieveFile() + "/") if len([ f for f in node.getFiles() if f.getName() == filename[1] and f.type == filename[0] ]) > 1: # remove single file from database if there are duplicates node.removeFile(file, single=True) else: # remove single file node.removeFile(file) try: os.remove(file.retrieveFile()) except: pass break break elif key.startswith("delatt|"): for file in node.getFiles(): if file.getMimeType() == "inode/directory": try: os.remove(file.retrieveFile() + "/" + key.split("|")[2][:-2]) except: pass break break elif op == "change": uploadfile = req.params.get("updatefile") if uploadfile: create_version_error = False # Create new version when change file if (req.params.get('generate_new_version') and not hasattr(node, "metaFields")): if (req.params.get('version_comment', '').strip() == '' or req.params.get('version_comment', '').strip() == ' '): create_version_error = True req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) ret += req.getTAL("web/edit/modules/files.html", {}, macro="version_error") else: current = node node = node.createNewVersion(user) for attr, value in current.items(): if node.get( attr) != "": # do not overwrite attributes pass else: node.set(attr, value) req.setStatus(httpstatus.HTTP_MOVED_TEMPORARILY) ret += req.getTAL("web/edit/modules/metadata.html", { 'url': '?id=' + node.id + '&tab=files', 'pid': None }, macro="redirect") if req.params.get( "change_file" ) == "yes" and not create_version_error: # remove old files for f in node.getFiles(): if f.getType() in node.getSysFiles(): node.removeFile(f) node.set( "system.version.comment", '(' + t(req, "edit_files_new_version_exchanging_comment") + ')\n' + req.params.get('version_comment', '')) if req.params.get( "change_file") == "no" and not create_version_error: node.set( "system.version.comment", '(' + t(req, "edit_files_new_version_adding_comment") + ')\n' + req.params.get('version_comment', '')) if req.params.get("change_file") in [ "yes", "no" ] and not create_version_error: file = importFile(uploadfile.filename, uploadfile.tempname) # add new file node.addFile(file) logging.getLogger('usertracing').info( user.name + " changed file of node " + node.id + " to " + uploadfile.filename + " (" + uploadfile.tempname + ")") attpath = "" for f in node.getFiles(): if f.getMimeType() == "inode/directory": attpath = f.getName() break if req.params.get( "change_file" ) == "attdir" and not create_version_error: # add attachmentdir dirname = req.params.get("inputname") if attpath == "": # add attachment directory attpath = req.params.get("inputname") if not os.path.exists(getImportDir() + "/" + attpath): os.mkdir(getImportDir() + "/" + attpath) node.addFile( tree.FileNode(name=getImportDir() + "/" + attpath, mimetype="inode/directory", type="attachment")) file = importFileIntoDir( getImportDir() + "/" + attpath, uploadfile.tempname) # add new file node.set( "system.version.comment", '(' + t( req, "edit_files_new_version_attachment_directory_comment" ) + ')\n' + req.params.get('version_comment', '')) pass if req.params.get( "change_file" ) == "attfile" and not create_version_error: # add file as attachment if attpath == "": # no attachment directory existing file = importFile(uploadfile.filename, uploadfile.tempname) # add new file file.mimetype = "inode/file" file.type = "attachment" node.addFile(file) else: # import attachment file into existing attachment directory file = importFileIntoDir( getImportDir() + "/" + attpath, uploadfile.tempname) # add new file node.set( "system.version.comment", '(' + t(req, "edit_files_new_version_attachment_comment") + ')\n' + req.params.get('version_comment', '')) pass elif op == "addthumb": # create new thumbanil from uploaded file uploadfile = req.params.get("updatefile") if uploadfile: thumbname = os.path.join( getImportDir(), hashlib.md5(str( random.random())).hexdigest()[0:8]) + ".thumb" file = importFile(thumbname, uploadfile.tempname) # add new file makeThumbNail(file.retrieveFile(), thumbname) makePresentationFormat(file.retrieveFile(), thumbname + "2") if os.path.exists( file.retrieveFile()): # remove uploaded original os.remove(file.retrieveFile()) for f in node.getFiles(): if f.type in ["thumb", "presentation", "presentati"]: if os.path.exists(f.retrieveFile()): os.remove(f.retrieveFile()) node.removeFile(f) node.addFile( tree.FileNode(name=thumbname, type="thumb", mimetype="image/jpeg")) node.addFile( tree.FileNode(name=thumbname + "2", type="presentation", mimetype="image/jpeg")) logging.getLogger('usertracing').info( user.name + " changed thumbnail of node " + node.id) elif op == "postprocess": if hasattr(node, "event_files_changed"): try: node.event_files_changed() logging.getLogger('usertracing').info( user.name + " postprocesses node " + node.id) except: update_error = True v = { "id": req.params.get("id", "0"), "tab": req.params.get("tab", ""), "node": node, "update_error": update_error, "user": user, "files": filter(lambda x: x.type != 'statistic', node.getFiles()), "statfiles": filter(lambda x: x.type == 'statistic', node.getFiles()), "attfiles": filter(lambda x: x.type == 'attachment', node.getFiles()), "att": [], "nodes": [node], "access": access } for f in v["attfiles"]: # collect all files in attachment directory if f.getMimeType() == "inode/directory": for root, dirs, files in os.walk(f.retrieveFile()): for name in files: af = tree.FileNode(root + "/" + name, "attachmentfile", getMimeType(name)[0]) v["att"].append(af) return req.getTAL("web/edit/modules/files.html", v, macro="edit_files_file")