def shownodelist(req, nodes, publishwarn=1, markunpublished=0, dir=None): req.session["nodelist"] = EditorNodeList(nodes) script_array = "allobjects = new Array();\n" nodelist = [] user = users.getUserFromRequest(req) for child in nodes: try: if isDirectory(child) or isCollection(child): continue script_array += "allobjects['%s'] = 0;\n" % child.id nodelist.append(child) except TypeError: continue chkjavascript = "" notpublished = {} if publishwarn or markunpublished: homedir = getHomeDir(user) homedirs = getAllSubDirs(homedir) if markunpublished: chkjavascript = """<script language="javascript">""" for node in nodes: ok = 0 for p in node.getParents(): if p not in homedirs: ok = 1 if not ok: if markunpublished: chkjavascript += """allobjects['check%s'] = 1; document.getElementById('check%s').checked = true; """ % (node.id, node.id) notpublished[node] = node chkjavascript += """</script>""" # if all nodes are properly published, don't bother # to warn the user if not notpublished: publishwarn = 0 unpublishedlink = None if publishwarn: user = users.getUserFromRequest(req) if dir: uploaddir = dir else: uploaddir = getUploadDir(user) unpublishedlink = "edit_content?tab=publish&id=" "" + uploaddir.id return req.getTAL("web/edit/edit_common.html", { "notpublished": notpublished, "chkjavascript": chkjavascript, "unpublishedlink": unpublishedlink, "nodelist": nodelist, "script_array": script_array, "language": lang(req) }, macro="show_nodelist")
def has_user(self, username, password): if username == self.user and (hashlib.md5(password).hexdigest() == self.passwd or password == self.passwd): return collection_ftpserver(self.basecontainer, port=self.port, debug="athana") else: user = users.checkLogin(username, password) if user: self.setUser(username, password, users.getUploadDir(user)) return collection_ftpserver(self.basecontainer, port=self.port, debug="athana") return None
def shownodelist(req, nodes, publishwarn=1, markunpublished=0, dir=None): req.session["nodelist"] = EditorNodeList(nodes) script_array = "allobjects = new Array();\n" nodelist = [] user = users.getUserFromRequest(req) for child in nodes: try: if isDirectory(child) or isCollection(child): continue script_array += "allobjects['%s'] = 0;\n" % child.id nodelist.append(child) except TypeError: continue chkjavascript = "" notpublished = {} if publishwarn or markunpublished: homedir = getHomeDir(user) homedirs = getAllSubDirs(homedir) if markunpublished: chkjavascript = """<script language="javascript">""" for node in nodes: ok = 0 for p in node.getParents(): if p not in homedirs: ok = 1 if not ok: if markunpublished: chkjavascript += """allobjects['check%s'] = 1; document.getElementById('check%s').checked = true; """ % (node.id, node.id) notpublished[node] = node chkjavascript += """</script>""" # if all nodes are properly published, don't bother # to warn the user if not notpublished: publishwarn = 0 unpublishedlink = None if publishwarn: user = users.getUserFromRequest(req) if dir: uploaddir = dir else: uploaddir = getUploadDir(user) unpublishedlink = "edit_content?tab=publish&id=""" + uploaddir.id return req.getTAL("web/edit/edit_common.html", {"notpublished": notpublished, "chkjavascript": chkjavascript, "unpublishedlink": unpublishedlink, "nodelist": nodelist, "script_array": script_array, "language": lang(req)}, macro="show_nodelist")
def upload_new_node(req, path, params, data): try: uploadfile = params['data'] del params['data'] except KeyError: uploadfile = None # get the user and verify the signature if params.get('user'): # user=users.getUser(params.get('user')) #userAccess = AccessData(user=user) _user = users.getUser(params.get('user')) if not _user: # user of dynamic class dummyuser: # dummy user class # return all groups with given dynamic user def getGroups(self): return [g.name for g in tree.getRoot('usergroups').getChildren() if g.get( 'allow_dynamic') == '1' and params.get('user') in g.get('dynamic_users')] def getName(self): return params.get('user') def getDirID(self): # unique identifier return params.get('user') def isAdmin(self): return 0 _user = dummyuser() userAccess = AccessData(user=_user) if userAccess.user: user = userAccess.user if not userAccess.verify_request_signature( req.fullpath + '?', params): userAccess = None else: userAccess = None else: user = users.getUser(config.get('user.guestuser')) userAccess = AccessData(user=user) parent = tree.getNode(params.get('parent')) # check user access if userAccess and userAccess.hasAccess(parent, "write"): pass else: s = "No Access" req.write(s) d = { 'status': 'fail', 'html_response_code': '403', 'errormessage': 'no access'} logger.error("user has no edit permission for node %s" % parent) return d['html_response_code'], len(s), d datatype = params.get('type') uploaddir = users.getUploadDir(user) n = tree.Node(name=params.get('name'), type=datatype) if isinstance(uploadfile, types.InstanceType): # file object used nfile = importFile(uploadfile.filename, uploadfile.tempname) else: # string used nfile = importFileFromData( 'uploadTest.jpg', base64.b64decode(uploadfile)) if nfile: n.addFile(nfile) else: logger.error("error in file uploadservice") try: # test metadata metadata = json.loads(params.get('metadata')) except ValueError: metadata = dict() # set provided metadata for key, value in metadata.iteritems(): n.set(u(key), u(value)) # service flags n.set("creator", user.getName()) n.set("creationtime", format_date()) parent.addChild(n) # process the file, we've added to the new node if hasattr(n, "event_files_changed"): try: n.event_files_changed() except OperationException as e: for file in n.getFiles(): if os.path.exists(file.retrieveFile()): os.remove(file.retrieveFile()) raise OperationException(e.value) # make sure the new node is visible immediately from the web service and # the search index gets updated n.setDirty() tree.remove_from_nodecaches(parent) d = { 'status': 'Created', 'html_response_code': '201', 'build_response_end': time.time()} s = "Created" # provide the uploader with the new node ID req.reply_headers['NodeID'] = n.id # we need to write in case of POST request, send as buffer will not work req.write(s) return d['html_response_code'], len(s), d
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")
return None # create node using given identifier (doi, ...) if req.params.get('action') == "obj_from_identifier": identifier_importer = req.params.get('identifier_importer') identifier = req.params.get('identifier') msg = "... in %s.%s: going to create new node without file from identifier (%r)" % (__name__, funcname(), identifier) logger.debug(msg) if identifier_importer in identifier_importers: identifierImporter = identifier_importers[identifier_importer] importer_func = identifierImporter.importer_func user = users.getUserFromRequest(req) importdir = users.getUploadDir(user) new_node = importer_func(identifier, importdir, req=req) res = {'id': req.params.get('id'), 'error': req.params.get('error', ''), 'connect_error_msg': req.params.get('connect_error_msg', '')} if new_node: new_node.set("creator", user.getName()) creation_time = str(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))) new_node.set("creationtime", creation_time) new_node.set("system.identifier_importer", identifier_importer) new_node.set("system.identifier_imported_from", identifier) clearFromCache(new_node) res['newid'] = new_node.id
def upload_new_node(req, path, params, data): try: uploadfile = params['data'] del params['data'] except KeyError: uploadfile = None # get the user and verify the signature if params.get('user'): # user=users.getUser(params.get('user')) #userAccess = AccessData(user=user) _user = users.getUser(params.get('user')) if not _user: # user of dynamic class dummyuser: # dummy user class # return all groups with given dynamic user def getGroups(self): return [ g.name for g in tree.getRoot('usergroups').getChildren() if g.get('allow_dynamic') == '1' and params.get('user') in g.get('dynamic_users') ] def getName(self): return params.get('user') def getDirID(self): # unique identifier return params.get('user') def isAdmin(self): return 0 _user = dummyuser() userAccess = AccessData(user=_user) if userAccess.user: user = userAccess.user if not userAccess.verify_request_signature(req.fullpath + '?', params): userAccess = None else: userAccess = None else: user = users.getUser(config.get('user.guestuser')) userAccess = AccessData(user=user) parent = tree.getNode(params.get('parent')) # check user access if userAccess and userAccess.hasAccess(parent, "write"): pass else: s = "No Access" req.write(s) d = { 'status': 'fail', 'html_response_code': '403', 'errormessage': 'no access' } logger.error("user has no edit permission for node %s" % parent) return d['html_response_code'], len(s), d datatype = params.get('type') uploaddir = users.getUploadDir(user) n = tree.Node(name=params.get('name'), type=datatype) if isinstance(uploadfile, types.InstanceType): # file object used nfile = importFile(uploadfile.filename, uploadfile.tempname) else: # string used nfile = importFileFromData('uploadTest.jpg', base64.b64decode(uploadfile)) if nfile: n.addFile(nfile) else: logger.error("error in file uploadservice") try: # test metadata metadata = json.loads(params.get('metadata')) except ValueError: metadata = dict() # set provided metadata for key, value in metadata.iteritems(): n.set(u(key), u(value)) # service flags n.set("creator", user.getName()) n.set("creationtime", format_date()) parent.addChild(n) # process the file, we've added to the new node if hasattr(n, "event_files_changed"): try: n.event_files_changed() except OperationException as e: for file in n.getFiles(): if os.path.exists(file.retrieveFile()): os.remove(file.retrieveFile()) raise OperationException(e.value) # make sure the new node is visible immediately from the web service and # the search index gets updated n.setDirty() tree.remove_from_nodecaches(parent) d = { 'status': 'Created', 'html_response_code': '201', 'build_response_end': time.time() } s = "Created" # provide the uploader with the new node ID req.reply_headers['NodeID'] = n.id # we need to write in case of POST request, send as buffer will not work req.write(s) return d['html_response_code'], len(s), d
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 action(req): global editModules access = AccessData(req) language = lang(req) user = users.getUserFromRequest(req) trashdir = users.getTrashDir(user) uploaddir = users.getUploadDir(user) faultydir = users.getFaultyDir(user) importdir = users.getImportDir(user) trashdir_parents = trashdir.getParents() action = req.params.get("action", "") changednodes = {} if not access.user.isEditor(): req.write("""permission denied""") req.setStatus(httpstatus.HTTP_FORBIDDEN) return if "tab" in req.params: tab = req.params.get("tab").split("_")[-1] return editModules[tab].getContent(req, [req.params.get("id")]) if action == "getlabels": nids = req.params.get("ids", []) nids = [nid.strip() for nid in nids.split(",") if nid.strip()] for nid in set(nids + [_n.id for _n in [trashdir, uploaddir, importdir, faultydir]]): try: changednodes[nid] = getTreeLabel(tree.getNode(nid), lang=language) except: msg = "could not make fancytree label for node %r" % nid logger.error(msg) res_dict = {"changednodes": changednodes} req.write(json.dumps(res_dict, indent=4)) return else: # all 'action's except 'getlabels' require a base dir (src) srcid = req.params.get("src") try: src = tree.getNode(srcid) except: req.writeTAL("web/edit/edit.html", {"edit_action_error": srcid}, macro="edit_action_error") return if req.params.get("action") == "addcontainer": node = tree.getNode(srcid) if not access.hasWriteAccess(node): # deliver errorlabel req.writeTALstr('<tal:block i18n:translate="edit_nopermission"/>', {}) return # create new container newnode_type = req.params.get("type") if newnode_type in ["bare_collection", "bare_directory"]: newnode_type = newnode_type.replace("bare_", "") translated_label = t(lang(req), "edit_add_" + newnode_type) if translated_label.startswith("edit_add_"): translated_label = t(lang(req), "edit_add_container_default") + newnode_type newnode = node.addChild(tree.Node(name=translated_label, type=newnode_type)) newnode.set("creator", user.getName()) newnode.set("creationtime", str(time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(time.time())))) clearFromCache(node) req.params["dest"] = newnode.id # try: # label = newnode.getLabel() # except: # label = newnode.getName() # # c = len(newnode.getContentChildren()) # if c>0: # label += ' <small>(%s)</small>' %(c) label = getTreeLabel(newnode, lang=language) fancytree_nodedata = { "title": label, "key": newnode.id, "isLazy": False, "isFolder": True, "icon": getEditorIconPath(newnode), "readonly": 0, "tooltip": "%s (%s)" % (label, newnode.id), "children": [], } req.write(json.dumps(fancytree_nodedata)) msg = "%s adding new container %r (%r) to %r (%r, %r)" % ( access.user.name, newnode.id, newnode.type, node.id, node.name, node.type, ) logging.getLogger("usertracing").info(msg) logger.info(msg) return try: destid = req.params.get("dest", None) dest = tree.getNode(destid) folderid = destid except: destid = None dest = None folderid = srcid idlist = getIDs(req) mysrc = None errorobj = None # try: if action == "clear_trash": for n in trashdir.getChildren(): # if trashdir is it's sole parent, remove file from disk # attn: this will not touch files from children of deleted # containers if len(n.getParents()) == 1: logger.info( "%s going to remove files from disk for node %r (%r, %r)" % (user.getName(), n.id, n.name, n.type) ) for f in n.getFiles(): # dangerous ??? check this f_path = f.retrieveFile() if os.path.exists(f_path): logger.info("%s going to remove file %r from disk" % (user.getName(), f_path)) os.remove(f_path) trashdir.removeChild(n) dest = trashdir clearFromCache(trashdir) changednodes[trashdir.id] = 1 _parent_descr = [(p.name, p.id, p.type) for p in trashdir_parents] msg = "%s cleared trash folder with id %s, child of %r" % (user.getName(), trashdir.id, _parent_descr) logger.info(msg) logging.getLogger("usertracing").info(msg) # return else: for id in idlist: obj = tree.getNode(id) mysrc = src if isDirectory(obj): mysrc = obj.getParents()[0] if action == "delete": if access.hasWriteAccess(mysrc) and access.hasWriteAccess(obj): if mysrc.id != trashdir.id: mysrc.removeChild(obj) changednodes[mysrc.id] = 1 trashdir.addChild(obj) changednodes[trashdir.id] = 1 clearFromCache(mysrc) logger.info( "%s moved to trash bin %s (%r, %r) from %s (%r, %r)" % (user.getName(), obj.id, obj.name, obj.type, mysrc.id, mysrc.name, mysrc.type) ) logging.getLogger("usertracing").info( "%s removed %s (%r, %r) from %s (%r, %r)" % (user.getName(), obj.id, obj.name, obj.type, mysrc.id, mysrc.name, mysrc.type) ) dest = mysrc else: logger.info("%s has no write access for node %s" % (user.getName(), mysrc.id)) req.writeTALstr('<tal:block i18n:translate="edit_nopermission"/>', {}) dest = mysrc elif action in ["move", "copy"]: if ( dest != mysrc and access.hasWriteAccess(mysrc) and access.hasWriteAccess(dest) and access.hasWriteAccess(obj) and isDirectory(dest) ): if not nodeIsChildOfNode(dest, obj): if action == "move": mysrc.removeChild(obj) changednodes[mysrc.id] = 1 # getLabel(mysrc) dest.addChild(obj) changednodes[dest.id] = 1 # getLabel(dest) clearFromCache(dest) _what = "%s %s %r (%r, %r) " % (access.user.name, action, obj.id, obj.name, obj.type) _from = "from %r (%r, %r) " % (mysrc.id, mysrc.name, mysrc.type) _to = "to %r (%r, %r)" % (dest.id, dest.name, dest.type) msg = _what + _from + _to logging.getLogger("usertracing").info(msg) logger.info(msg) else: logger.error( "%s could not %s %s from %s to %s" % (user.getName(), action, obj.id, mysrc.id, dest.id) ) else: return mysrc = None if not mysrc: mysrc = src if action in ["move", "copy", "delete", "clear_trash"]: for nid in changednodes: try: changednodes[nid] = getTreeLabel(tree.getNode(nid), lang=language) except: msg = "could not make fancytree label for node %r" % nid logger.error(msg) res_dict = {"changednodes": changednodes} req.write(json.dumps(res_dict, indent=4)) else: try: req.write(dest.id) except: req.write("no-node-id-specified (web.edit.edit.action)") logger.warning("no-node-id-specified (web.edit.edit.action)") return
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 action(req): global editModules access = AccessData(req) language = lang(req) user = users.getUserFromRequest(req) trashdir = users.getTrashDir(user) uploaddir = users.getUploadDir(user) faultydir = users.getFaultyDir(user) importdir = users.getImportDir(user) trashdir_parents = trashdir.getParents() action = req.params.get("action", "") changednodes = {} if not access.user.isEditor(): req.write("""permission denied""") req.setStatus(httpstatus.HTTP_FORBIDDEN) return if "tab" in req.params: tab = req.params.get("tab").split("_")[-1] return editModules[tab].getContent(req, [req.params.get("id")]) if action == "getlabels": nids = req.params.get('ids', []) nids = [nid.strip() for nid in nids.split(',') if nid.strip()] for nid in set(nids + [_n.id for _n in [trashdir, uploaddir, importdir, faultydir]]): try: changednodes[nid] = getTreeLabel( tree.getNode(nid), lang=language) except: msg = "could not make fancytree label for node %r" % nid logger.error(msg) res_dict = {'changednodes': changednodes} req.write(json.dumps(res_dict, indent=4)) return else: # all 'action's except 'getlabels' require a base dir (src) srcid = req.params.get("src") try: src = tree.getNode(srcid) except: req.writeTAL( "web/edit/edit.html", {"edit_action_error": srcid}, macro="edit_action_error") return if req.params.get('action') == 'addcontainer': node = tree.getNode(srcid) if not access.hasWriteAccess(node): # deliver errorlabel req.writeTALstr( '<tal:block i18n:translate="edit_nopermission"/>', {}) return # create new container newnode_type = req.params.get('type') if newnode_type in ['bare_collection', 'bare_directory']: newnode_type = newnode_type.replace('bare_', '') translated_label = t(lang(req), 'edit_add_' + newnode_type) if translated_label.startswith('edit_add_'): translated_label = t( lang(req), 'edit_add_container_default') + newnode_type newnode = node.addChild( tree.Node(name=translated_label, type=newnode_type)) newnode.set("creator", user.getName()) newnode.set("creationtime", str( time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time())))) clearFromCache(node) req.params["dest"] = newnode.id # try: # label = newnode.getLabel() # except: # label = newnode.getName() # # c = len(newnode.getContentChildren()) # if c>0: # label += ' <small>(%s)</small>' %(c) label = getTreeLabel(newnode, lang=language) fancytree_nodedata = { 'title': label, 'key': newnode.id, 'isLazy': False, 'isFolder': True, 'icon': getEditorIconPath(newnode), 'readonly': 0, 'tooltip': '%s (%s)' % (label, newnode.id), 'children': [], } req.write(json.dumps(fancytree_nodedata)) msg = "%s adding new container %r (%r) to %r (%r, %r)" % ( access.user.name, newnode.id, newnode.type, node.id, node.name, node.type) logging.getLogger('usertracing').info(msg) logger.info(msg) return try: destid = req.params.get("dest", None) dest = tree.getNode(destid) folderid = destid except: destid = None dest = None folderid = srcid idlist = getIDs(req) mysrc = None errorobj = None # try: if action == "clear_trash": for n in trashdir.getChildren(): # if trashdir is it's sole parent, remove file from disk # attn: this will not touch files from children of deleted # containers if len(n.getParents()) == 1: logger.info("%s going to remove files from disk for node %r (%r, %r)" % ( user.getName(), n.id, n.name, n.type)) for f in n.getFiles(): # dangerous ??? check this f_path = f.retrieveFile() if os.path.exists(f_path): logger.info( "%s going to remove file %r from disk" % (user.getName(), f_path)) os.remove(f_path) trashdir.removeChild(n) dest = trashdir clearFromCache(trashdir) changednodes[trashdir.id] = 1 _parent_descr = [(p.name, p.id, p.type) for p in trashdir_parents] msg = "%s cleared trash folder with id %s, child of %r" % ( user.getName(), trashdir.id, _parent_descr) logger.info(msg) logging.getLogger('usertracing').info(msg) # return else: for id in idlist: obj = tree.getNode(id) mysrc = src if isDirectory(obj): mysrc = obj.getParents()[0] if action == "delete": if access.hasWriteAccess(mysrc) and access.hasWriteAccess(obj): if mysrc.id != trashdir.id: mysrc.removeChild(obj) changednodes[mysrc.id] = 1 trashdir.addChild(obj) changednodes[trashdir.id] = 1 clearFromCache(mysrc) logger.info("%s moved to trash bin %s (%r, %r) from %s (%r, %r)" % ( user.getName(), obj.id, obj.name, obj.type, mysrc.id, mysrc.name, mysrc.type)) logging.getLogger('usertracing').info("%s removed %s (%r, %r) from %s (%r, %r)" % ( user.getName(), obj.id, obj.name, obj.type, mysrc.id, mysrc.name, mysrc.type)) dest = mysrc else: logger.info( "%s has no write access for node %s" % (user.getName(), mysrc.id)) req.writeTALstr( '<tal:block i18n:translate="edit_nopermission"/>', {}) dest = mysrc elif action in ["move", "copy"]: if dest != mysrc and \ access.hasWriteAccess(mysrc) and \ access.hasWriteAccess(dest) and \ access.hasWriteAccess(obj) and \ isDirectory(dest): if not nodeIsChildOfNode(dest, obj): if action == "move": mysrc.removeChild(obj) changednodes[mysrc.id] = 1 # getLabel(mysrc) dest.addChild(obj) changednodes[dest.id] = 1 # getLabel(dest) clearFromCache(dest) _what = "%s %s %r (%r, %r) " % ( access.user.name, action, obj.id, obj.name, obj.type) _from = "from %r (%r, %r) " % ( mysrc.id, mysrc.name, mysrc.type) _to = "to %r (%r, %r)" % ( dest.id, dest.name, dest.type) msg = _what + _from + _to logging.getLogger('usertracing').info(msg) logger.info(msg) else: logger.error("%s could not %s %s from %s to %s" % ( user.getName(), action, obj.id, mysrc.id, dest.id)) else: return mysrc = None if not mysrc: mysrc = src if action in ["move", "copy", "delete", "clear_trash"]: for nid in changednodes: try: changednodes[nid] = getTreeLabel( tree.getNode(nid), lang=language) except: msg = "could not make fancytree label for node %r" % nid logger.error(msg) res_dict = {'changednodes': changednodes} req.write(json.dumps(res_dict, indent=4)) else: try: req.write(dest.id) except: req.write('no-node-id-specified (web.edit.edit.action)') logger.warning('no-node-id-specified (web.edit.edit.action)') return
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")
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")