def get(self): try: user_id = utils.get_user_id(request) res = TrainModel.query.filter_by(user_id=user_id).all() schema = TrainModelSchema(exclude=['api_key'], many=True) data = schema.dump(res) return data except: traceback.print_exc() return None, 500
def post(self): try: user_id = utils.get_user_id(request) model_id = utils.get_filename_from_path(request, '') data = request.get_json() train_model = TrainModel(name=data['name'], description=data['description'], model_id=model_id, score=data['score'], user_id=user_id, api_key=secrets.token_hex()) db.session.add(train_model) db.session.commit() return self.get() except: traceback.print_exc() return [], 500
def register(self, image): faces = self.model.get(image) if len(faces) != 1: log_util.logger.info("没有检测到人脸,无法注册") return None # 判断人脸是否存在 embedding = np.array(faces[0].embedding).reshape((1, -1)) embedding = preprocessing.normalize(embedding) is_exits = False for com_face in self.faces_embedding: r = self.feature_compare(embedding, com_face["feature"], self.config.threshold) if r: is_exits = True if is_exits: log_util.logger.info("人脸已存在,无法注册") return None old_user_id = [d["user_id"] for d in self.faces_embedding] user_id = get_user_id(old_user_id) # 符合注册条件保存图片,同时把特征添加到人脸特征库中 cv2.imencode('.png', image)[1].tofile( os.path.join(self.config.face_db, '%s.png' % user_id)) self.faces_embedding.append({"user_id": user_id, "feature": embedding}) return user_id
def content(req): user = current_user language = lang(req) if not user.is_editor: return req.writeTAL("web/edit/edit.html", {}, macro="error") if 'id' in req.params and len(req.params) == 1: nid = long(req.params.get('id')) node = q(Data).get(nid) if node is not None: cmd = "cd (%s %r, %r)" % (nid, node.name, node.type) logg.info("%s: %s", user.login_name, cmd) else: cmd = "ERROR-cd to non-existing id=%r" % nid logg.error("%s: %s", user.login_name, cmd) if 'action' in req.params and req.params['action'] == 'upload': pass content = {'script': '', 'body': ''} v = {'dircontent': '', 'notdirectory': 0, 'operations': ''} try: v['nodeiconpath'] = getEditorIconPath(node) except: v['nodeiconpath'] = "webtree/directory.gif" path = req.path[1:].split("/") if len(path) >= 4: req.params["style"] = "popup" req.params["id"] = path[1] req.params["tab"] = path[2] req.params["option"] = path[3] getEditModules() if not user.is_editor: return req.writeTAL("web/edit/edit.html", {}, macro="error") # remove all caches for the frontend area- we might make changes there for sessionkey in ["contentarea", "navframe"]: with suppress(Exception, warn=False): del req.session[sessionkey] ids = getIDs(req) if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload": return upload_help(req) if len(ids) > 0: if ids[0] == "all": ids = get_ids_from_req(req) node = q(Node).get(long(ids[0])) tabs = "content" if isinstance(node, Root): tabs = "content" elif node is user.upload_dir: tabs = "upload" else: tabs = node.get_default_edit_tab() v["notdirectory"] = 0 current = req.params.get("tab", tabs) logg.debug("... %s inside %s.%s: -> !!! current = %s !!!", get_user_id(req), __name__, funcname(), current) msg = "%s selected editor module is %s" % (user.login_name, current) jsfunc = req.params.get("func", "") if jsfunc: msg = msg + (', js-function: %r' % jsfunc) logg.info(msg) # some tabs operate on only one file # if current in ["files", "view", "upload"]: if current in ["files", "upload"]: ids = ids[0:1] # display current images if not isinstance(q(Data).get(ids[0]), Container): v["notdirectory"] = 1 items = [] if current != "view": for id in ids: node = q(Data).get(id) if hasattr(node, "show_node_image"): if not isDirectory(node) and not node.isContainer(): items.append((id, node.show_node_image())) else: items.append(("", node.show_node_image())) v["items"] = items if logg.isEnabledFor(logging.DEBUG): logg.debug("... %s inside %s.%s: -> display current images: items: %s", get_user_id(req), __name__, funcname(), [_t[0] for _t in items]) nid = req.params.get('src', req.params.get('id')) if nid is None: raise ValueError("invalid request, neither 'src' not 'id' parameter is set!") folders_only = False if nid.find(',') > 0: # more than one node selected # use the first one for activateEditorTreeNode # and display only folders nid = nid.split(',')[0] folders_only = True n = q(Data).get(nid) if current == 'metadata' and 'save' in req.params: pass s = [] while n: if not folders_only: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, get_edit_label(n, language))] + s folders_only = False; p = n.parents # XXX: we only check the first parent. This is wrong, how could be solve this? # first_parent = p[0] if isinstance(first_parent, Data) and first_parent.has_read_access(): n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s) else: # or current directory n = q(Data).get(long(ids[0])) s = [] while n: if len(s) == 0: s = ['%s' % (get_edit_label(n, language))] else: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, get_edit_label(n, language))] + s p = n.parents if p and not isinstance(p[0], Root): n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s) if current == "globals": basedir = config.get("paths.datadir") file_to_edit = None if "file_to_edit" in req.params: file_to_edit = req.params["file_to_edit"] if not file_to_edit: # todo: getstartpagedict doesnt exist d = node.getStartpageDict() if d and language in d: file_to_edit = d[language] found = False for f in node.files: if f.mimetype == 'text/html': filepath = f.abspath.replace(basedir, '') if file_to_edit == filepath: found = True break else: t2 = current.split("_")[-1] if t2 in editModules.keys(): c = editModules[t2].getContent(req, ids) if isinstance(c, int): # module returned a custom http status code instead of HTML content return c elif c: content["body"] += c else: logg.debug('empty content') return else: req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error") if req.params.get("style", "") != "popup": # normal page with header v["tabs"] = handletabs(req, ids, tabs) v["script"] = content["script"] v["body"] = content["body"] v["paging"] = showPaging(req, current, ids) v["node"] = node v["ids"] = req.params.get("ids", "").split(",") if req.params.get("ids", "") == "": v["ids"] = req.params.get("id", "").split(",") v["tab"] = current v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations") v['user'] = user v['language'] = lang(req) v['t'] = t # add icons to breadcrumbs ipath = 'webtree/directory.gif' if node and node.isContainer(): if node.name == 'home' or 'Arbeitsverzeichnis' in node.name or node == current_user.home_dir: ipath = 'webtree/homeicon.gif' elif node.name in ('Uploads', 'upload'): ipath = 'webtree/uploadicon.gif' elif node.name in ('Papierkorb', 'trash'): ipath = 'webtree/trashicon.gif' else: ipath = getEditorIconPath(node) v["dircontent"] += ' <img src="' + '/img/' + ipath + '" />' return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
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 excludeid = req.params.get('excludeid', None) if excludeid: grandchildren = [] for child in node.getChildren(): for grandchild in child.getChildren(): if not grandchild.isContainer(): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.getChildren() if str(c.id) != excludeid], 'grandchildren': grandchildren}, macro="edit_files_popup_children") else: grandchildren = [] for child in node.getChildren(): for grandchild in child.getChildren(): if not grandchild.isContainer(): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.getChildren() if str(c.id) != excludeid], 'grandchildren': grandchildren}, macro="edit_files_popup_children") elif req.params.get('data') =='grandchildren': grandchildren = [] for child in node.getChildren(): if not child.isContainer(): for grandchild in child.getChildren(): if not grandchild.isContainer(): if not grandchild.isContainer(): grandchildren.append(grandchild) if len(node.getChildren())==0: req.writeTAL("web/edit/modules/files.html", {'grandchildren': []}, macro="edit_files_popup_grandchildren") else: req.writeTAL("web/edit/modules/files.html", {'grandchildren': grandchildren}, macro="edit_files_popup_grandchildren") 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(): if p.isContainer(): logging.getLogger('editor').info("Removed childnode: {} from node: {}. - caused by adding".format(childnode.id, node.id)) 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 if node.type != 'directory': try: if v['current_id'] == None: v['current_id'] = node.id except KeyError: pass 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 if uploadfile.filename: if getMimeType(uploadfile.filename)[0] == 'other': return '<h2 style="width:100%; text-align:center ;color:red">file-format is not supported (upload canceled / use attachment)</h2>' 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: if uploadfile.filename: if getMimeType(uploadfile.filename)[0] == 'other': return '<h2 style="width:100%; text-align:center ;color:red">file-format is not supported (upload canceled / use attachment)</h2>' 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")
for k in dir(req.params['file']): if k in ['__doc__', '__init__', '__module__', '__str__', 'adddata', 'close', ]: continue msg.append("%r: %r" % (k, getattr(req.params['file'], k))) msg = "... req.params['file'] = %r" % (', '.join(msg)) logger.debug(msg) proceed_to_uploadcomplete = True realname = realname.replace(' ', '_') # check this: import to realnamne or random name ? f = importFileToRealname(realname, tempname) #f = importFile(realname,tempname) n = tree.getNode(req.params.get('id')) n.addFile(f) req.write("") logger.debug("%r|%s.%s: added file to node %r (%r, %r)" % (get_user_id(req), __name__, funcname(), n.id, n.name, n.type)) if not proceed_to_uploadcomplete: return None # upload done -> deliver view of object if proceed_to_uploadcomplete or req.params.get('action') == "uploadcomplete": logger.debug("upload done -> deliver view of object") if proceed_to_uploadcomplete: req.params['file'] = realname mime = getMimeType(req.params.get('file')) data_extra = req.params.get('data_extra', '') if data_extra == 'tofile': ctx = {
if req.params.get('action') == "upload": if 'file' in req.params: # plupload realname = mybasename( req.params['file'].filename.decode("utf8")) tempname = req.params['file'].tempname.decode("utf8") proceed_to_uploadcomplete = True realname = realname.replace(' ', '_') # XXX: check this: import to realnamne or random name ? f = importFileToRealname(realname, tempname) node = q(Node).get(req.params.get('id')) node.files.append(f) db.session.commit() req.write("") logg.debug("%s|%s.%s: added file to node %s (%s, %s)", get_user_id(req), __name__, funcname(), node.id, node.name, node.type) if not proceed_to_uploadcomplete: return None # upload done -> deliver view of object if proceed_to_uploadcomplete or req.params.get( 'action') == "uploadcomplete": logg.debug("upload done -> deliver view of object") if proceed_to_uploadcomplete: req.params['file'] = realname mime = getMimeType(req.params.get('file')) data_extra = req.params.get('data_extra', '') if data_extra == 'tofile':
def content(req): user = users.getUserFromRequest(req) access = AccessData(req) language = lang(req) if not access.user.isEditor(): return req.writeTAL("web/edit/edit.html", {}, macro="error") if "id" in req.params and len(req.params) == 1: nid = req.params.get("id") try: node = tree.getNode(nid) except: node = None if node: cmd = "cd (%s %r, %r)" % (nid, node.name, node.type) logger.info("%s: %s" % (user.getName(), cmd)) # logging.getLogger("usertracing").info("%s: in editor %s" % (user.getName(), cmd)) else: cmd = "ERROR-cd to non-existing id=%r" % nid logger.error("%s: %s") % (user.getName(), cmd) if "action" in req.params and req.params["action"] == "upload": pass content = {"script": "", "body": ""} v = {"dircontent": "", "notdirectory": 0, "operations": ""} try: v["nodeiconpath"] = getEditorIconPath(node) except: v["nodeiconpath"] = "webtree/directory.gif" path = req.path[1:].split("/") if len(path) >= 4: req.params["style"] = "popup" req.params["id"] = path[1] req.params["tab"] = path[2] req.params["option"] = path[3] getEditModules() if not access.user.isEditor(): return req.writeTAL("web/edit/edit.html", {}, macro="error") # remove all caches for the frontend area- we might make changes there for sessionkey in ["contentarea", "navframe"]: try: del req.session[sessionkey] except: pass ids = getIDs(req) if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload": return upload_help(req) if len(ids) > 0: node = tree.getNode(ids[0]) tabs = "content" if node.type == "root": tabs = "content" elif node.id == users.getUploadDir(access.getUser()).id: tabs = "upload" elif node.id == users.getImportDir(access.getUser()).id: tabs = "imports" elif hasattr(node, "getDefaultEditTab"): tabs = node.getDefaultEditTab() v["notdirectory"] = 0 current = req.params.get("tab", tabs) logger.debug("... %s inside %s.%s: -> !!! current = %r !!!" % (get_user_id(req), __name__, funcname(), current)) msg = "%s selected editor module is %r" % (user.getName(), current) jsfunc = req.params.get("func", "") if jsfunc: msg = msg + (", js-function: %r" % jsfunc) logger.info(msg) # some tabs operate on only one file # if current in ["files", "view", "upload"]: if current in ["files", "upload"]: ids = ids[0:1] # display current images if not tree.getNode(ids[0]).isContainer(): v["notdirectory"] = 1 items = [] if current != "view": for id in ids: node = tree.getNode(id) if hasattr(node, "show_node_image"): if not isDirectory(node) and not node.isContainer(): items.append((id, node.show_node_image())) else: items.append(("", node.show_node_image())) v["items"] = items logger.debug( "... %s inside %s.%s: -> display current images: items: %r" % (get_user_id(req), __name__, funcname(), [_t[0] for _t in items]) ) try: n = tree.getNode(req.params.get("src", req.params.get("id"))) if current == "metadata" and "save" in req.params: pass s = [] while n: try: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.getLabel(lang=language)) ] + s except: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.name) ] + s p = n.getParents() if p: n = p[0] else: n = None v["dircontent"] = " <b>»</b> ".join(s[1:]) except: logger.exception("ERROR displaying current images") else: # or current directory n = tree.getNode(ids[0]) s = [] while n: if len(s) == 0: try: s = ["%s" % (n.getLabel(lang=language))] except: s = ["%s" % (n.name)] else: try: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.getLabel(lang=language)) ] + s except: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.name) ] + s p = n.getParents() if p: n = p[0] else: n = None v["dircontent"] = " <b>»</b> ".join(s[1:]) if current == "globals": basedir = config.get("paths.datadir") file_to_edit = None if "file_to_edit" in req.params: file_to_edit = req.params["file_to_edit"] if not file_to_edit: d = node.getStartpageDict() if d and lang(req) in d: file_to_edit = d[lang(req)] found = False for f in node.getFiles(): if f.mimetype == "text/html": filepath = f.retrieveFile().replace(basedir, "") if file_to_edit == filepath: found = True result = edit_editor(req, node, f) if result == "error": logger.error("error editing %r" % f.retrieveFile()) break if not found: edit_editor(req, node, None) elif current == "tab_metadata": edit_metadata(req, ids) # undefined elif current == "tab_upload": edit_upload(req, ids) # undefined elif current == "tab_import": edit_import(req, ids) # undefined elif current == "tab_globals": req.write("") elif current == "tab_lza": edit_lza(req, ids) # undefined elif current == "tab_logo": edit_logo(req, ids) # undefined else: t = current.split("_")[-1] if t in editModules.keys(): c = editModules[t].getContent(req, ids) if c: content["body"] += c # use standard method of module else: logger.debug("empty content") return else: req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error") if req.params.get("style", "") != "popup": # normal page with header v["tabs"] = handletabs(req, ids, tabs) v["script"] = content["script"] v["body"] = content["body"] v["paging"] = showPaging(req, current, ids) v["node"] = node v["ids"] = req.params.get("ids", "").split(",") if req.params.get("ids", "") == "": v["ids"] = req.params.get("id", "").split(",") v["tab"] = current v["operations"] = req.getTAL( "web/edit/edit_common.html", {"iscontainer": node.isContainer()}, macro="show_operations" ) user = users.getUserFromRequest(req) v["user"] = user v["language"] = lang(req) v["t"] = translation_t v["spc"] = [Menu("sub_header_frontend", "../", target="_parent")] if user.isAdmin(): v["spc"].append(Menu("sub_header_administration", "../admin", target="_parent")) if user.isWorkflowEditor(): v["spc"].append(Menu("sub_header_workflow", "../publish", target="_parent")) v["spc"].append(Menu("sub_header_logout", "../logout", target="_parent")) # add icons to breadcrumbs ipath = "webtree/directory.gif" if node and node.isContainer(): if node.name == "home" or "Arbeitsverzeichnis" in node.name: ipath = "webtree/homeicon.gif" elif node.name == "Uploads": ipath = "webtree/uploadicon.gif" elif node.name == "Importe": ipath = "webtree/importicon.gif" elif node.name == "Inkonsistente Daten": ipath = "webtree/faultyicon.gif" elif node.name == "Papierkorb": ipath = "webtree/trashicon.gif" else: ipath = getEditorIconPath(node) v["dircontent"] += ' <img src="' + "/img/" + ipath + '" />' return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
def content(req): user = users.getUserFromRequest(req) access = AccessData(req) language = lang(req) if not access.user.isEditor(): return req.writeTAL("web/edit/edit.html", {}, macro="error") if 'id' in req.params and len(req.params) == 1: nid = req.params.get('id') try: node = tree.getNode(nid) except: node = None if node: cmd = "cd (%s %r, %r)" % (nid, node.name, node.type) logger.info("%s: %s" % (user.getName(), cmd)) #logging.getLogger("usertracing").info("%s: in editor %s" % (user.getName(), cmd)) else: cmd = "ERROR-cd to non-existing id=%r" % nid logger.error("%s: %s") % (user.getName(), cmd) if 'action' in req.params and req.params['action'] == 'upload': pass content = {'script': '', 'body': ''} v = {'dircontent': '', 'notdirectory': 0, 'operations': ''} try: v['nodeiconpath'] = getEditorIconPath(node) except: v['nodeiconpath'] = "webtree/directory.gif" path = req.path[1:].split("/") if len(path) >= 4: req.params["style"] = "popup" req.params["id"] = path[1] req.params["tab"] = path[2] req.params["option"] = path[3] getEditModules() if not access.user.isEditor(): return req.writeTAL("web/edit/edit.html", {}, macro="error") # remove all caches for the frontend area- we might make changes there for sessionkey in ["contentarea", "navframe"]: try: del req.session[sessionkey] except: pass ids = getIDs(req) if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload": return upload_help(req) if len(ids) > 0: node = tree.getNode(ids[0]) tabs = "content" if node.type == "root": tabs = "content" elif node.id == users.getUploadDir(access.getUser()).id: tabs = "upload" elif node.id == users.getImportDir(access.getUser()).id: tabs = "imports" elif hasattr(node, "getDefaultEditTab"): tabs = node.getDefaultEditTab() v["notdirectory"] = 0 current = req.params.get("tab", tabs) logger.debug("... %s inside %s.%s: -> !!! current = %r !!!" % (get_user_id(req), __name__, funcname(), current)) msg = "%s selected editor module is %r" % (user.getName(), current) jsfunc = req.params.get("func", "") if jsfunc: msg = msg + (', js-function: %r' % jsfunc) logger.info(msg) # some tabs operate on only one file # if current in ["files", "view", "upload"]: if current in ["files", "upload"]: ids = ids[0:1] # display current images if not tree.getNode(ids[0]).isContainer(): v["notdirectory"] = 1 items = [] if current != "view": for id in ids: node = tree.getNode(id) if hasattr(node, "show_node_image"): if not isDirectory(node) and not node.isContainer(): items.append((id, node.show_node_image())) else: items.append(("", node.show_node_image())) v["items"] = items logger.debug("... %s inside %s.%s: -> display current images: items: %r" % (get_user_id(req), __name__, funcname(), [_t[0] for _t in items])) try: n = tree.getNode(req.params.get('src', req.params.get('id'))) if current == 'metadata' and 'save' in req.params: pass s = [] while n: try: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.getLabel(lang=language))] + s except: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.name)] + s p = n.getParents() if p: n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s[1:]) except: logger.exception('ERROR displaying current images') else: # or current directory n = tree.getNode(ids[0]) s = [] while n: if len(s) == 0: try: s = ['%s' % (n.getLabel(lang=language))] except: s = ['%s' % (n.name)] else: try: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.getLabel(lang=language))] + s except: s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, n.name)] + s p = n.getParents() if p: n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s[1:]) if current == "globals": basedir = config.get("paths.datadir") file_to_edit = None if "file_to_edit" in req.params: file_to_edit = req.params["file_to_edit"] if not file_to_edit: d = node.getStartpageDict() if d and lang(req) in d: file_to_edit = d[lang(req)] found = False for f in node.getFiles(): if f.mimetype == 'text/html': filepath = f.retrieveFile().replace(basedir, '') if file_to_edit == filepath: found = True result = edit_editor(req, node, f) if result == "error": logger.error("error editing %r" % f.retrieveFile()) break if not found: edit_editor(req, node, None) elif current == "tab_metadata": edit_metadata(req, ids) # undefined elif current == "tab_upload": edit_upload(req, ids) # undefined elif current == "tab_import": edit_import(req, ids) # undefined elif current == "tab_globals": req.write("") elif current == "tab_lza": edit_lza(req, ids) # undefined elif current == "tab_logo": edit_logo(req, ids) # undefined else: t = current.split("_")[-1] if t in editModules.keys(): c = editModules[t].getContent(req, ids) if c: content["body"] += c # use standard method of module else: logger.debug('empty content') return else: req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error") if req.params.get("style", "") != "popup": # normal page with header v["tabs"] = handletabs(req, ids, tabs) v["script"] = content["script"] v["body"] = content["body"] v["paging"] = showPaging(req, current, ids) v["node"] = node v["ids"] = req.params.get("ids", "").split(",") if req.params.get("ids", "") == "": v["ids"] = req.params.get("id", "").split(",") v["tab"] = current v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations") user = users.getUserFromRequest(req) v['user'] = user v['language'] = lang(req) v['t'] = translation_t v['spc'] = [Menu("sub_header_frontend", "../", target="_parent")] if user.isAdmin(): v['spc'].append(Menu("sub_header_administration", "../admin", target="_parent")) if user.isWorkflowEditor(): v['spc'].append(Menu("sub_header_workflow", "../publish", target="_parent")) v['spc'].append(Menu("sub_header_logout", "../logout", target="_parent")) # add icons to breadcrumbs ipath = 'webtree/directory.gif' if node and node.isContainer(): if node.name == 'home' or 'Arbeitsverzeichnis' in node.name: ipath = 'webtree/homeicon.gif' elif node.name == 'Uploads': ipath = 'webtree/uploadicon.gif' elif node.name == 'Importe': ipath = 'webtree/importicon.gif' elif node.name == 'Inkonsistente Daten': ipath = 'webtree/faultyicon.gif' elif node.name == 'Papierkorb': ipath = 'webtree/trashicon.gif' else: ipath = getEditorIconPath(node) v["dircontent"] += ' <img src="' + '/img/' + ipath + '" />' return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
def getContent(req, ids): ret = "" user = current_user node = q(Node).get(ids[0]) update_error = False update_error_extension = False logg.debug("%s|web.edit.modules.files.getContend|req.fullpath=%s|req.path=%s|req.params=%s|ids=%s", get_user_id(req), req.fullpath, req.path, req.params, ids) if not node.has_write_access() or "files" in current_user.hidden_edit_functions: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") if 'data' in req.params: if 'data' in req.params: from contenttypes.container import Container if req.params.get('data') == 'children': # get formated list of childnodes of selected directory excludeid = str(req.params.get('excludeid', None)) if excludeid: grandchildren = [] for child in node.getChildren(): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.children.all() if str(c.id) != excludeid], 'grandchildren': grandchildren, "csrf": req.csrf_token.current_token}, macro="edit_files_popup_children") else: grandchildren = [] for child in node.children.all(): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.getChildren() if str(c.id) != excludeid], 'grandchildren': grandchildren, "csrf": req.csrf_token.current_token}, macro="edit_files_popup_children") elif req.params.get('data') =='grandchildren': grandchildren = [] for child in node.children.all(): if not isinstance(child, Container): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) if len(node.getChildren())==0: req.writeTAL("web/edit/modules/files.html", {'grandchildren': [], "csrf": req.csrf_token.current_token}, macro="edit_files_popup_grandchildren") else: req.writeTAL("web/edit/modules/files.html", {'grandchildren': grandchildren, "csrf": req.csrf_token.current_token}, macro="edit_files_popup_grandchildren") if req.params.get('data') == 'additems': # add selected node as children for childid in req.params.get('items').split(";"): if childid.strip() != "": childnode = q(Node).get(childid.strip()) # don't try to add node as child to itself ! if childnode != node: for p in childnode.parents: if isinstance(p, Container): p.children.remove(childnode) node.children.append(childnode) req.writeTAL("web/edit/modules/files.html", {'children': node.children, 'node': node, "csrf": req.csrf_token.current_token}, macro="edit_files_children_list") if req.params.get('data') == 'removeitem': # remove selected childnode node with suppress(Exception): remnode = q(Node).get(req.params.get('remove')) if len(remnode.parents) == 1: users.getUploadDir(user).children.append(remnode) node.children.remove(remnode) req.writeTAL("web/edit/modules/files.html", {'children': node.children, 'node': node, "csrf": req.csrf_token.current_token}, macro="edit_files_children_list") if req.params.get('data') == 'reorder': i = 0 for id in req.params.get('order').split(","): if id != "": n = q(Node).get(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'), "csrf": req.csrf_token.current_token}) db.session.commit() return "" if req.params.get("style") == "popup": v = {"basedirs": [q(Home).one(), q(Collections).one()]} id = req.params.get("id", q(Root).one().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 v["csrf"] = req.csrf_token.current_token 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.files: if file.base_name == filename[1] and file.filetype == filename[0]: # remove all files in directory if file.mimetype == "inode/directory": for root, dirs, files in os.walk(file.abspath): for name in files: try: os.remove(root + "/" + name) except: logg.exception("exception while removing file, ignore") os.removedirs(file.abspath + "/") node.files.remove(file) with suppress(Exception, warn=False): os.remove(file.abspath) break break elif key.startswith("delatt|"): for file in node.files: if file.mimetype == "inode/directory": try: os.remove(file.abspath + "/" + key.split("|")[2][:-2]) except: logg.exception("exception while removing file, ignore") break break elif op == "change": _handle_change(node, req) if req.reply_code != httpstatus.HTTP_OK and req.reply_code != httpstatus.HTTP_MOVED_TEMPORARILY: if req.reply_code is httpstatus.HTTP_NOT_ACCEPTABLE: update_error_extension = True else: update_error = True elif op == "addthumb": # create new thumbanil from uploaded file uploadfile = req.params.get("updatefile") if uploadfile: thumbname = os.path.join(getImportDir(), hashlib.md5(ustr(random.random())).hexdigest()[0:8]) + ".thumb" file = importFile(thumbname, uploadfile.tempname) # add new file make_thumbnail_image(file.abspath, thumbname) make_presentation_image(file.abspath, thumbname + "2") if os.path.exists(file.abspath): # remove uploaded original os.remove(file.abspath) for f in node.files: if f.type in ["thumb", "presentation"]: if os.path.exists(f.abspath): os.remove(f.abspath) node.files.remove(f) node.files.append(File(thumbname, "thumb", "image/jpeg")) node.files.append(File(thumbname + "2", "presentation", "image/jpeg")) logg.info("%s changed thumbnail of node %s", user.login_name, node.id) elif op == "postprocess": try: node.event_files_changed() logg.info("%s postprocesses node %s", user.login_name, node.id) except: update_error = True db.session.commit() v = {"id": req.params.get("id", "0"), "tab": req.params.get("tab", ""), "node": node, "update_error": update_error, "update_error_extension": update_error_extension, "user": user, "files": filter(lambda x: x.type != 'statistic', node.files), "statfiles": filter(lambda x: x.type == 'statistic', node.files), "attfiles": filter(lambda x: x.type == 'attachment', node.files), "att": [], "nodes": [node], "csrf": req.csrf_token.current_token } for f in v["attfiles"]: # collect all files in attachment directory if f.mimetype == "inode/directory": for root, dirs, files in os.walk(f.abspath): for name in files: af = File(root + "/" + name, "attachmentfile", getMimeType(name)[0]) v["att"].append(af) return req.getTAL("web/edit/modules/files.html", v, macro="edit_files_file")
proceed_to_uploadcomplete = False # upload file to current node as attachment if req.params.get('action') == "upload": if 'file' in req.params: # plupload realname = mybasename(req.params['file'].filename.decode("utf8")) tempname = req.params['file'].tempname.decode("utf8") proceed_to_uploadcomplete = True realname = realname.replace(' ', '_') # XXX: check this: import to realnamne or random name ? f = importFileToRealname(realname, tempname) node = q(Node).get(req.params.get('id')) node.files.append(f) db.session.commit() req.write("") logg.debug("%s|%s.%s: added file to node %s (%s, %s)", get_user_id(req), __name__, funcname(), node.id, node.name, node.type) if not proceed_to_uploadcomplete: return None # upload done -> deliver view of object if proceed_to_uploadcomplete or req.params.get('action') == "uploadcomplete": logg.debug("upload done -> deliver view of object") if proceed_to_uploadcomplete: req.params['file'] = realname mime = getMimeType(req.params.get('file')) data_extra = req.params.get('data_extra', '') if data_extra == 'tofile': ctx = {
def getContent(req, ids): ret = "" user = current_user node = q(Node).get(ids[0]) update_error = False update_error_extension = False logg.debug( "%s|web.edit.modules.files.getContend|req.fullpath=%s|req.path=%s|req.params=%s|ids=%s", get_user_id(req), req.fullpath, req.path, req.params, ids) if not node.has_write_access( ) or "files" in current_user.hidden_edit_functions: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") if 'data' in req.params: if 'data' in req.params: from contenttypes.container import Container if req.params.get( 'data' ) == 'children': # get formated list of childnodes of selected directory excludeid = str(req.params.get('excludeid', None)) if excludeid: grandchildren = [] for child in node.getChildren(): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", { 'children': [ c for c in node.children.all() if str(c.id) != excludeid ], 'grandchildren': grandchildren }, macro="edit_files_popup_children") else: grandchildren = [] for child in node.children.all(): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) req.writeTAL("web/edit/modules/files.html", { 'children': [ c for c in node.getChildren() if str(c.id) != excludeid ], 'grandchildren': grandchildren }, macro="edit_files_popup_children") elif req.params.get('data') == 'grandchildren': grandchildren = [] for child in node.children.all(): if not isinstance(child, Container): for grandchild in child.children.all(): if not isinstance(grandchild, Container): grandchildren.append(grandchild) if len(node.getChildren()) == 0: req.writeTAL("web/edit/modules/files.html", {'grandchildren': []}, macro="edit_files_popup_grandchildren") else: req.writeTAL("web/edit/modules/files.html", {'grandchildren': grandchildren}, macro="edit_files_popup_grandchildren") if req.params.get( 'data') == 'additems': # add selected node as children for childid in req.params.get('items').split(";"): if childid.strip() != "": childnode = q(Node).get(childid.strip()) # don't try to add node as child to itself ! if childnode != node: for p in childnode.parents: if isinstance(p, Container): p.children.remove(childnode) node.children.append(childnode) req.writeTAL("web/edit/modules/files.html", { 'children': node.children, 'node': node }, macro="edit_files_children_list") if req.params.get( 'data') == 'removeitem': # remove selected childnode node try: remnode = q(Node).get(req.params.get('remove')) if len(remnode.parents) == 1: users.getUploadDir(user).children.append(remnode) node.children.remove(remnode) except: # node not found logg.exception( "exception in getContent, node not found? ignore") pass req.writeTAL("web/edit/modules/files.html", { 'children': node.children, '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 = q(Node).get(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')}) db.session.commit() return "" if req.params.get("style") == "popup": v = {"basedirs": [q(Home).one(), q(Collections).one()]} id = req.params.get("id", q(Root).one().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.files: if file.base_name == filename[ 1] and file.filetype == filename[0]: # remove all files in directory if file.mimetype == "inode/directory": for root, dirs, files in os.walk(file.abspath): for name in files: try: os.remove(root + "/" + name) except: logg.exception( "exception while removing file, ignore" ) os.removedirs(file.abspath + "/") node.files.remove(file) try: os.remove(file.abspath) except: pass break break elif key.startswith("delatt|"): for file in node.files: if file.mimetype == "inode/directory": try: os.remove(file.abspath + "/" + key.split("|")[2][:-2]) except: logg.exception( "exception while removing file, ignore") break break elif op == "change": _handle_change(node, req) if req.reply_code != httpstatus.HTTP_OK and req.reply_code != httpstatus.HTTP_MOVED_TEMPORARILY: if req.reply_code is httpstatus.HTTP_NOT_ACCEPTABLE: update_error_extension = True else: update_error = True elif op == "addthumb": # create new thumbanil from uploaded file uploadfile = req.params.get("updatefile") if uploadfile: thumbname = os.path.join( getImportDir(), hashlib.md5(ustr( random.random())).hexdigest()[0:8]) + ".thumb" file = importFile(thumbname, uploadfile.tempname) # add new file make_thumbnail_image(file.abspath, thumbname) make_presentation_image(file.abspath, thumbname + "2") if os.path.exists(file.abspath): # remove uploaded original os.remove(file.abspath) for f in node.files: if f.type in ["thumb", "presentation"]: if os.path.exists(f.abspath): os.remove(f.abspath) node.files.remove(f) node.files.append(File(thumbname, "thumb", "image/jpeg")) node.files.append( File(thumbname + "2", "presentation", "image/jpeg")) logg.info("%s changed thumbnail of node %s", user.login_name, node.id) elif op == "postprocess": try: node.event_files_changed() logg.info("%s postprocesses node %s", user.login_name, node.id) except: update_error = True db.session.commit() v = { "id": req.params.get("id", "0"), "tab": req.params.get("tab", ""), "node": node, "update_error": update_error, "update_error_extension": update_error_extension, "user": user, "files": filter(lambda x: x.type != 'statistic', node.files), "statfiles": filter(lambda x: x.type == 'statistic', node.files), "attfiles": filter(lambda x: x.type == 'attachment', node.files), "att": [], "nodes": [node], } for f in v["attfiles"]: # collect all files in attachment directory if f.mimetype == "inode/directory": for root, dirs, files in os.walk(f.abspath): for name in files: af = File(root + "/" + name, "attachmentfile", getMimeType(name)[0]) v["att"].append(af) return req.getTAL("web/edit/modules/files.html", v, macro="edit_files_file")
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")
def content(req): user = current_user language = lang(req) if not user.is_editor: return req.writeTAL("web/edit/edit.html", {}, macro="error") if 'id' in req.params and len(req.params) == 1: nid = long(req.params.get('id')) node = q(Data).get(nid) if node is not None: cmd = "cd (%s %r, %r)" % (nid, node.name, node.type) logg.info("%s: %s", user.login_name, cmd) else: cmd = "ERROR-cd to non-existing id=%r" % nid logg.error("%s: %s", user.login_name, cmd) if 'action' in req.params and req.params['action'] == 'upload': pass content = {'script': '', 'body': ''} v = {'dircontent': '', 'notdirectory': 0, 'operations': ''} try: v['nodeiconpath'] = getEditorIconPath(node) except: v['nodeiconpath'] = "webtree/directory.gif" path = req.path[1:].split("/") if len(path) >= 4: req.params["style"] = "popup" req.params["id"] = path[1] req.params["tab"] = path[2] req.params["option"] = path[3] getEditModules() if not user.is_editor: return req.writeTAL("web/edit/edit.html", {}, macro="error") # remove all caches for the frontend area- we might make changes there for sessionkey in ["contentarea", "navframe"]: try: del req.session[sessionkey] except: pass ids = getIDs(req) if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload": return upload_help(req) if len(ids) > 0: if ids[0] == "all": ids = get_ids_from_req(req) node = q(Node).get(long(ids[0])) tabs = "content" if isinstance(node, Root): tabs = "content" elif node is user.upload_dir: tabs = "upload" else: tabs = node.get_default_edit_tab() v["notdirectory"] = 0 current = req.params.get("tab", tabs) logg.debug("... %s inside %s.%s: -> !!! current = %s !!!", get_user_id(req), __name__, funcname(), current) msg = "%s selected editor module is %s" % (user.login_name, current) jsfunc = req.params.get("func", "") if jsfunc: msg = msg + (', js-function: %r' % jsfunc) logg.info(msg) # some tabs operate on only one file # if current in ["files", "view", "upload"]: if current in ["files", "upload"]: ids = ids[0:1] # display current images if not isinstance(q(Data).get(ids[0]), Container): v["notdirectory"] = 1 items = [] if current != "view": for id in ids: node = q(Data).get(id) if hasattr(node, "show_node_image"): if not isDirectory(node) and not node.isContainer(): items.append((id, node.show_node_image())) else: items.append(("", node.show_node_image())) v["items"] = items if logg.isEnabledFor(logging.DEBUG): logg.debug( "... %s inside %s.%s: -> display current images: items: %s", get_user_id(req), __name__, funcname(), [_t[0] for _t in items]) nid = req.params.get('src', req.params.get('id')) if nid is None: raise ValueError( "invalid request, neither 'src' not 'id' parameter is set!") folders_only = False if nid.find(',') > 0: # more than one node selected # use the first one for activateEditorTreeNode # and display only folders nid = nid.split(',')[0] folders_only = True n = q(Data).get(nid) if current == 'metadata' and 'save' in req.params: pass s = [] while n: if not folders_only: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, get_edit_label(n, language)) ] + s folders_only = False p = n.parents # XXX: we only check the first parent. This is wrong, how could be solve this? # first_parent = p[0] if isinstance(first_parent, Data) and first_parent.has_read_access(): n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s) else: # or current directory n = q(Data).get(long(ids[0])) s = [] while n: if len(s) == 0: s = ['%s' % (get_edit_label(n, language))] else: s = [ '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' % (n.id, n.id, get_edit_label(n, language)) ] + s p = n.parents if p and not isinstance(p[0], Root): n = p[0] else: n = None v["dircontent"] = ' <b>»</b> '.join(s) if current == "globals": basedir = config.get("paths.datadir") file_to_edit = None if "file_to_edit" in req.params: file_to_edit = req.params["file_to_edit"] if not file_to_edit: # todo: getstartpagedict doesnt exist d = node.getStartpageDict() if d and language in d: file_to_edit = d[language] found = False for f in node.files: if f.mimetype == 'text/html': filepath = f.abspath.replace(basedir, '') if file_to_edit == filepath: found = True break else: t2 = current.split("_")[-1] if t2 in editModules.keys(): c = editModules[t2].getContent(req, ids) if isinstance(c, int): # module returned a custom http status code instead of HTML content return c elif c: content["body"] += c else: logg.debug('empty content') return else: req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error") if req.params.get("style", "") != "popup": # normal page with header v["tabs"] = handletabs(req, ids, tabs) v["script"] = content["script"] v["body"] = content["body"] v["paging"] = showPaging(req, current, ids) v["node"] = node v["ids"] = req.params.get("ids", "").split(",") if req.params.get("ids", "") == "": v["ids"] = req.params.get("id", "").split(",") v["tab"] = current v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations") v['user'] = user v['language'] = lang(req) v['t'] = t # add icons to breadcrumbs ipath = 'webtree/directory.gif' if node and node.isContainer(): if node.name == 'home' or 'Arbeitsverzeichnis' in node.name or node == current_user.home_dir: ipath = 'webtree/homeicon.gif' elif node.name in ('Uploads', 'upload'): ipath = 'webtree/uploadicon.gif' elif node.name in ('Papierkorb', 'trash'): ipath = 'webtree/trashicon.gif' else: ipath = getEditorIconPath(node) v["dircontent"] += ' <img src="' + '/img/' + ipath + '" />' return req.writeTAL("web/edit/edit.html", v, macro="frame_content")