def showdir(req, node, publishwarn="auto", markunpublished=0, nodes=[], sortfield_from_req=None): if publishwarn == "auto": user = users.getUserFromRequest(req) homedir = getHomeDir(user) homedirs = getAllSubDirs(homedir) publishwarn = node in homedirs if not nodes: nodes = node.getChildren() if sortfield_from_req and sortfield_from_req is not None: msg = "%r, %r, sorted by sortfield_from_req=%r" % ( __name__, funcname(), sortfield_from_req) logger.debug(msg) elif sortfield_from_req is None: collection_sortfield = node.get("sortfield") if collection_sortfield: nodes = tree.NodeList([n.id for n in nodes ]).sort_by_fields([collection_sortfield]) msg = "%r, %r, sorted by collection_sortfield=%r" % ( __name__, funcname(), collection_sortfield) logger.debug(msg) else: msg = "%r, %r, *not* sorted" % (__name__, funcname()) logger.debug(msg) nodes = tree.NodeList([n.id for n in nodes if not n.type == 'shoppingbag']) return shownodelist(req, nodes, publishwarn=publishwarn, markunpublished=markunpublished, dir=node)
def showdir(req, node, publishwarn="auto", markunpublished=0, nodes=[], sortfield_from_req=None): if publishwarn == "auto": user = users.getUserFromRequest(req) homedir = getHomeDir(user) homedirs = getAllSubDirs(homedir) publishwarn = node in homedirs if not nodes: nodes = node.getChildren() if sortfield_from_req and sortfield_from_req is not None: msg = "%r, %r, sorted by sortfield_from_req=%r" % ( __name__, funcname(), sortfield_from_req) logger.debug(msg) elif sortfield_from_req is None: collection_sortfield = node.get("sortfield") if collection_sortfield: nodes = tree.NodeList([n.id for n in nodes]).sort_by_fields( [collection_sortfield]) msg = "%r, %r, sorted by collection_sortfield=%r" % ( __name__, funcname(), collection_sortfield) logger.debug(msg) else: msg = "%r, %r, *not* sorted" % (__name__, funcname()) logger.debug(msg) nodes = tree.NodeList([n.id for n in nodes if not n.type == 'shoppingbag']) return shownodelist(req, nodes, publishwarn=publishwarn, markunpublished=markunpublished, dir=node)
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 setUserDetails(self, user, detail_dict, req=None, **kwargs): targetnode = users.getHomeDir(user) for key in detail_dict: target_key = "system.%s.%s" % (self.name, key) target_value = str(detail_dict[key]) targetnode.set(target_key, target_value) msg = "setting user detail: %r = %r" % (target_key, target_value) log.info(msg)
def getUserDetails(self, user, req=None, **kwargs): targetnode = users.getHomeDir(user) res = dict(targetnode.items()) if DEBUG: msg = "retrieving user details:" log.info(msg) _d = pf(res) log.debug(res) return res
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 show_user_data(req): error = "" # XXX: dead code? if USE_EXAMPLES and 'examples' in req.params: try: import userdata_examples reload(userdata_examples) except Exception as e: log.error("Error loading examples:" + str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]), exc_info=True) if "jsonrequest" in req.params: python_callback_key = req.params.get("python_callback_key", "") if python_callback_key and python_callback_key in aclasses: req.write(aclasses[python_callback_key].callback(req=req)) return user = users.getUserFromRequest(req) user_homedir = {} if not user.isGuest(): user_homedir = users.getHomeDir(user) navframe = getNavigationFrame(req) navframe.feedback(req) udclasses = sorted([(uc.orderpos, uc) for uc in aclasses.values()]) udclasses = [t[1] for t in udclasses] ctx = { "error": error, "user": user, "user_homedir": user_homedir, "pf": pf, "udclasses": udclasses, "req": req, } navframe.write( req, req.getTAL("web/frontend/userdata.html", ctx, macro="show_user_data")) return httpstatus.HTTP_OK
def show_user_data(req): error = "" # XXX: dead code? if USE_EXAMPLES and 'examples' in req.params: try: import userdata_examples reload(userdata_examples) except Exception as e: log.error("Error loading examples:" + str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]), exc_info=True) if "jsonrequest" in req.params: python_callback_key = req.params.get("python_callback_key", "") if python_callback_key and python_callback_key in aclasses: req.write(aclasses[python_callback_key].callback(req=req)) return user = users.getUserFromRequest(req) user_homedir = {} if not user.isGuest(): user_homedir = users.getHomeDir(user) navframe = getNavigationFrame(req) navframe.feedback(req) udclasses = sorted([(uc.orderpos, uc) for uc in aclasses.values()]) udclasses = [t[1] for t in udclasses] ctx = { "error": error, "user": user, "user_homedir": user_homedir, "pf": pf, "udclasses": udclasses, "req": req, } navframe.write(req, req.getTAL("web/frontend/userdata.html", ctx, macro="show_user_data")) return httpstatus.HTTP_OK
def frameset(req): id = req.params.get("id", tree.getRoot("collections").id) tab = req.params.get("tab", None) language = lang(req) access = AccessData(req) if not access.getUser().isEditor(): req.writeTAL("web/edit/edit.html", {}, macro="error") req.writeTAL( "web/edit/edit.html", {"id": id, "tab": (tab and "&tab=" + tab) or ""}, macro="edit_notree_permission" ) req.setStatus(httpstatus.HTTP_FORBIDDEN) return try: currentdir = tree.getNode(id) except tree.NoSuchNodeError: currentdir = tree.getRoot("collections") req.params["id"] = currentdir.id id = req.params.get("id") nodepath = [] n = currentdir while n: nodepath = [n] + nodepath p = n.getParents() if p: n = p[0] else: n = None path = nidpath = ["%s" % p.id for p in nodepath] containerpath = [("%s" % p.id) for p in nodepath if p.isContainer()] user = users.getUserFromRequest(req) menu = filterMenu(getEditMenuString(currentdir.getContentType()), user) spc = [Menu("sub_header_frontend", "../", target="_parent")] if user.isAdmin(): spc.append(Menu("sub_header_administration", "../admin", target="_parent")) if user.isWorkflowEditor(): spc.append(Menu("sub_header_workflow", "../publish", target="_parent")) spc.append(Menu("sub_header_logout", "../logout", target="_parent")) def getPathToFolder(node): n = node path = [] while n: path = ["/%s" % (n.id)] + path p = n.getParents() if p: n = p[0] else: n = None return (node, "".join(path[2:])) def _getIDPath(nid, sep="/", containers_only=True): res = getIDPaths(nid, access, sep=sep, containers_only=containers_only) return res folders = { "homedir": getPathToFolder(users.getHomeDir(user)), "trashdir": getPathToFolder(users.getSpecialDir(user, "trash")), "uploaddir": getPathToFolder(users.getSpecialDir(user, "upload")), "importdir": getPathToFolder(users.getSpecialDir(user, "import")), } cmenu = sorted(getContainerTreeTypes(req), key=lambda x: x.getName()) cmenu_iconpaths = [] for ct in cmenu: ct_name = ct.getName() _n = tree.Node("", type=ct_name) # translations of ct_name will be offered in editor tree context menu cmenu_iconpaths.append([ct, getEditorIconPath(_n), ct_name, translation_t(language, ct_name)]) # a html snippet may be inserted in the editor header header_insert = tree.getRoot("collections").get("system.editor.header.insert." + language).strip() help_link = tree.getRoot("collections").get("system.editor.help.link." + language).strip() homenodefilter = req.params.get("homenodefilter", "") v = { "id": id, "tab": (tab and "&tab=" + tab) or "", "user": user, "spc": spc, "folders": folders, "collectionsid": tree.getRoot("collections").id, "basedirs": [tree.getRoot("home"), tree.getRoot("collections")], "cmenu": cmenu, "cmenu_iconpaths": cmenu_iconpaths, "path": path, "containerpath": containerpath, "language": lang(req), "t": translation_t, "_getIDPath": _getIDPath, "system_editor_header_insert": header_insert, "system_editor_help_link": help_link, "homenodefilter": homenodefilter, } req.writeTAL("web/edit/edit.html", v, macro="edit_main")
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) access = acl.AccessData(req) for id in ids: if not access.hasWriteAccess(tree.getNode(id)) or "acls" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") idstr = ",".join(ids) if "save" in req.params: # save acl level userdir = users.getHomeDir(user) logging.getLogger('usertracing').info(access.user.name + " change access " + idstr) if req.params.get("type") == "acl": for type in acl_types: rights = req.params.get("left" + type, "").replace(";", ",") for id in ids: node = tree.getNode(id) error = 0 if access.hasWriteAccess(node) and userdir.id != node.id: node.setAccess(type, rights) else: error = 1 if error: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") # save userlevel elif req.params.get("type") == "user": for type in acl_types: for id in ids: node = tree.getNode(id) error = 0 if access.hasWriteAccess(node) and userdir.id != node.id: r = [] r_acls = [] if req.params.get("leftuser" + type, "") != "": for right in req.params.get("leftuser" + type, "").split(";"): if len(right.split(": ")) == 2: r.append("(user " + right.split(": ")[1] + ")") else: r_acls.append(right) if len(r) > 0: rstr = "{" + " OR ".join(r) + "}" else: rstr = req.params.get("leftuser" + type, "") if len(rstr) > 0: rstr += "," for x in r_acls: rstr += x + "," rstr = rstr[:-1] else: rstr = "" node.setAccess(type, rstr) else: error = 1 if error: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") runsubmit = "\nfunction runsubmit(){\n" retacl = "" rights = {} parent_rights = {} overload = {} for type in acl_types: s = None parent_rights[type] = {} overload[type] = 0 runsubmit += "\tmark(document.myform.left" + type + ");\n" runsubmit += "\tmark(document.myform.leftuser" + type + ");\n" if type in ("read", "data"): overload[type] = 1 for id in ids: node = tree.getNode(id) r = node.getAccess(type) if r is None: r = "" log.debug(node.name + " " + type + " " + r) if not s or r == s: s = r else: s = "" def addNode(node): for p in node.getParents(): aclright = p.getAccess(type) for right in removeEmptyStrings((aclright or "").split(",")): parent_rights[type][right] = None if aclright and overload[type]: return else: addNode(p) addNode(node) rights[type] = removeEmptyStrings(s.split(",")) for type in acl_types: retacl += req.getTAL("web/edit/modules/acls.html", makeList(req, type, rights[type], parent_rights[type].keys(), overload[type], type=type), macro="edit_acls_selectbox") if "action" in req.params.keys(): # load additional rights by ajax retuser = "" for type in acl_types: retuser += req.getTAL("web/edit/modules/acls.html", makeUserList(req, type, rights[type], parent_rights[type].keys(), overload[type], type=type), macro="edit_acls_userselectbox") req.write(retuser) return "" runsubmit += "\tdocument.myform.submit();\n}\n" return req.getTAL("web/edit/modules/acls.html", {"runsubmit": runsubmit, "idstr": idstr, "contentacl": retacl, "adminuser": access.getUser().isAdmin()}, macro="edit_acls")
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) access = acl.AccessData(req) for id in ids: if not access.hasWriteAccess( tree.getNode(id)) or "acls" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") idstr = ",".join(ids) if "save" in req.params: # save acl level userdir = users.getHomeDir(user) logging.getLogger('usertracing').info(access.user.name + " change access " + idstr) if req.params.get("type") == "acl": for type in acl_types: rights = req.params.get("left" + type, "").replace(";", ",") for id in ids: node = tree.getNode(id) error = 0 if access.hasWriteAccess(node) and userdir.id != node.id: node.setAccess(type, rights) else: error = 1 if error: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") # save userlevel elif req.params.get("type") == "user": for type in acl_types: for id in ids: node = tree.getNode(id) error = 0 if access.hasWriteAccess(node) and userdir.id != node.id: r = [] r_acls = [] if req.params.get("leftuser" + type, "") != "": for right in req.params.get("leftuser" + type, "").split(";"): if len(right.split(": ")) == 2: r.append("(user " + right.split(": ")[1] + ")") else: r_acls.append(right) if len(r) > 0: rstr = "{" + " OR ".join(r) + "}" else: rstr = req.params.get( "leftuser" + type, "") if len(rstr) > 0: rstr += "," for x in r_acls: rstr += x + "," rstr = rstr[:-1] else: rstr = "" node.setAccess(type, rstr) else: error = 1 if error: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") runsubmit = "\nfunction runsubmit(){\n" retacl = "" rights = {} parent_rights = {} overload = {} for type in acl_types: s = None parent_rights[type] = {} overload[type] = 0 runsubmit += "\tmark(document.myform.left" + type + ");\n" runsubmit += "\tmark(document.myform.leftuser" + type + ");\n" if type in ("read", "data"): overload[type] = 1 for id in ids: node = tree.getNode(id) r = node.getAccess(type) if r is None: r = "" log.debug(node.name + " " + type + " " + r) if not s or r == s: s = r else: s = "" def addNode(node): for p in node.getParents(): aclright = p.getAccess(type) for right in removeEmptyStrings((aclright or "").split(",")): parent_rights[type][right] = None if aclright and overload[type]: return else: addNode(p) addNode(node) rights[type] = removeEmptyStrings(s.split(",")) for type in acl_types: retacl += req.getTAL("web/edit/modules/acls.html", makeList(req, type, rights[type], parent_rights[type].keys(), overload[type], type=type), macro="edit_acls_selectbox") if "action" in req.params.keys(): # load additional rights by ajax retuser = "" for type in acl_types: retuser += req.getTAL("web/edit/modules/acls.html", makeUserList(req, type, rights[type], parent_rights[type].keys(), overload[type], type=type), macro="edit_acls_userselectbox") req.write(retuser) return "" runsubmit += "\tdocument.myform.submit();\n}\n" return req.getTAL("web/edit/modules/acls.html", { "runsubmit": runsubmit, "idstr": idstr, "contentacl": retacl, "adminuser": access.getUser().isAdmin() }, macro="edit_acls")
def getContent(req, ids): user = users.getUserFromRequest(req) publishdir = tree.getNode(ids[0]) explicit = tree.getNodesByAttribute("writeaccess", user.getName()) ret = "" actionerror = [] changes = [] if "dopublish" in req.params.keys(): access = AccessData(req) objlist = [] for key in req.params.keys(): if key.isdigit(): objlist.append(key) src = tree.getNode(req.params.get("id")) for obj_id in objlist: faultylist = [] obj = tree.getNode(obj_id) for mask in obj.getType().getMasks( type="edit"): # check required fields if access.hasReadAccess(mask) and mask.getName() == obj.get( "edit.lastmask"): for f in mask.validateNodelist([obj]): faultylist.append(f) if len(faultylist) > 0: # object faulty actionerror.append(obj_id) continue for dest_id in req.params.get("destination", "").split(","): if dest_id == "": # no destination given continue dest = tree.getNode(dest_id) if dest != src and access.hasReadAccess( src) and access.hasWriteAccess( dest) and access.hasWriteAccess( obj) and isDirectory(dest): if not nodeIsChildOfNode(dest, obj): dest.addChild(obj) src.removeChild(obj) if dest.id not in changes: changes.append(dest.id) if src.id not in changes: changes.append(src.id) log.info( "%s published %s (%r, %r) from src %s (%r, %r) to dest %s (%r, %r)" % ( user.getName(), obj.id, obj.name, obj.type, src.id, src.name, src.type, dest.id, dest.name, dest.type, )) else: actionerror.append(obj.id) log.error( "Error in publishing of node %r: Destination node %r is child of node." % (obj_id, dest.id)) if not access.hasReadAccess(src): log.error( "Error in publishing of node %r: source position %r has no read access." % (obj.id, src.id)) if not access.hasWriteAccess(dest): log.error( "Error in publishing of node %r: destination %r has no write access." % (obj.id, dest.id)) if not access.hasWriteAccess(obj): log.error( "Error in publishing of node %r: object has no write access." % obj.id) if not isDirectory(dest): log.error( "Error in publishing of node %r: destination %r is not a directory." % (obj.id, dest.id)) v = {} v["id"] = publishdir.id v["change"] = changes ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload") # build normal window stddir = "" stdname = "" l = [] for n in explicit: if str(getHomeDir(user).id) != str(n): l.append(n) if len(l) == 1: stddir = str(l[0]) + "," stdname = "- " + tree.getNode(l[0]).getName() #v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=0, markunpublished=1, nodes=[])} v = { "id": publishdir.id, "stddir": stddir, "stdname": stdname, "showdir": showdir(req, publishdir, publishwarn=None, markunpublished=1, nodes=[]) } v["basedir"] = tree.getRoot('collections') v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" % ( publishdir.id, publishdir.id) v["idstr"] = ids v["faultylist"] = actionerror ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form") return ret
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) if "metadata" in users.getHideMenusForUser(user): print "error 1" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") access = AccessData(req) faultydir = users.getFaultyDir(user) metatypes = [] nodes = [] masklist = [] err = 0 # flag indicating change of node.name (fancytree node may have to be updated) # keep as integer # negative -> no change # else -> id of changed node flag_nodename_changed = -1 for id in ids: node = tree.getNode(id) if not access.hasWriteAccess(node): print "error 2" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") schema = node.getSchema() if schema not in metatypes: metatypes.append(schema) if len(nodes) == 0 or nodes[0].getSchema() == schema: nodes += [node] idstr = ",".join(ids) action = req.params.get('action', '').strip() logger.info("%s in editor metadata (action=%r): %r" % (user.getName(), action, [[n.id, n.name, n.type]for n in nodes])) for m in node.getType().getMasks(type="edit"): if access.hasReadAccess(m): masklist.append(m) if hasattr(node, "metaFields"): class SystemMask: def __init__(self, name, description, fields): self.name, self.description, self.fields = name, description, fields def getName(self): return self.name def getDescription(self): return self.description def getDefaultMask(self): return False def metaFields(self, lang=None): return self.fields def i_am_not_a_mask(): pass masklist = [SystemMask( "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist default = None for m in masklist: if m.getDefaultMask(): default = m break if not default and len(masklist): default = masklist[0] maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask") if maskname == "": maskname = default.getName() mask = None for m in masklist: if maskname == m.getName(): mask = m break if not mask and default: mask = default maskname = default.getName() for n in nodes: n.set("edit.lastmask", maskname) if not mask: return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask") # context default for TAL interpreter ctx = {} ctx["user"] = user ctx["access"] = access ctx["metatypes"] = metatypes ctx["idstr"] = idstr ctx["node"] = nodes[0] # ? ctx["flag_nodename_changed"] = flag_nodename_changed ctx["nodes"] = nodes ctx["masklist"] = masklist ctx["maskname"] = maskname ctx["language"] = lang(req) ctx["t"] = t if action == 'restore': vid = req.params.get('vid', '0') node = nodes[0].getActiveVersion() if (vid != '0' and vid != node.id): n = tree.getNode(vid) # Not active version if n.next_nid != '0': next = tree.getNode(n.next_nid) if next.prev_nid != '0': next.removeChild(tree.getNode(next.prev_nid)) next.setPrevID(n.prev_nid) if n.prev_nid != '0': prev = tree.getNode(n.prev_nid) prev.setNextID(n.next_nid) n.removeChild(prev) next.addChild(prev) node.setNextID(n.id) n.setPrevID(node.id) n.setNextID('0') for pid in db.getParents(node.id): parentNode = tree.getNode(pid) parentNode.addChild(n) parentNode.removeChild(node) n.addChild(node) nodes = [n] ids = [n.id] node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + n.id + '&tab=metadata', 'pid': None, 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields(nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") if action == 'delete': vid = req.params.get('vid', '0') if (vid != '0'): node = nodes[0].getActiveVersion() n = tree.getNode(vid) if (vid != node.id): n.set("deleted", "true") for pid in db.getParents(n.id): parentNode = tree.getNode(pid) parentNode.removeChild(n) for cid in db.getChildren(n.id): n.removeChild(tree.getNode(cid)) if n.next_nid != '0' and n.prev_nid != '0': _next = tree.getNode(n.next_nid) _next.addChild(tree.getNode(n.prev_nid)) if n.next_nid != '0': _next = tree.getNode(n.next_nid) if n.prev_nid != '0': _next.setPrevID(n.prev_nid) if n.prev_nid != '0': _prev = tree.getNode(n.prev_nid) if n.next_nid != '0': _prev.setNextID(n.next_nid) else: pids = db.getParents(n.id) # Active version prev = None if n.prev_nid != '0': prev = tree.getNode(n.prev_nid) while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true": prev = tree.getNode(prev.prev_nid) if prev != None and prev.get("deleted") != "true": prev.setNextID('0') for pid in pids: parentNode = tree.getNode(pid) parentNode.addChild(prev) nodes = [prev] ids = [prev.id] n.set("deleted", "true") for pid in pids: parentNode = tree.getNode(pid) parentNode.removeChild(n) for cid in db.getChildren(n.id): n.removeChild(tree.getNode(cid)) if n.next_nid != '0' and n.prev_nid != '0': _next = tree.getNode(n.next_nid) _next.addChild(tree.getNode(n.prev_nid)) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid': None, 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") else: # Version 0 # Move node to trash trashdir = users.getTrashDir(user) trashdir.addChild(n) for pid in pids: parentNode = tree.getNode(pid) parentNode.removeChild(n) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[ 0], 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") if "edit_metadata" in req.params: # check and save items userdir = users.getHomeDir(users.getUserFromRequest(req)) for node in nodes: if not access.hasWriteAccess(node) or node.id == userdir.id: print "error 3" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") logging.getLogger('usertracing').info( access.user.name + " change metadata " + idstr) logging.getLogger('editor').info( access.user.name + " change metadata " + idstr) logging.getLogger('editor').debug(pf(req.params)) for node in nodes: node.set("updateuser", user.getName()) if node.get('updatetime') < str(now()): node.set("updatetime", str(format_date())) if not hasattr(mask, "i_am_not_a_mask"): if (req.params.get('generate_new_version')): # Create new node version _ids = [] _nodes = [] for node in nodes: n = node.createNewVersion(user) n.set("system.version.comment", '(' + t(req, "document_new_version_comment") + ')\n' + req.params.get('version_comment', '')) # add all existing attributes to the new version node for attr, value in node.items(): # do not overwrite existing attributes # do not copy system attributes if n.get(attr) != "" or attr.startswith("system."): pass else: n.set(attr, value) _nodes.append(n) _ids.append(n.id) ids = _ids idstr = ",".join(ids) nodes = _nodes nodes = mask.updateNode(nodes, req) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = { 'url': '?id=' + nodes[0].id + '&tab=metadata', 'pid': None, } data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) ret += req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") else: if nodes: old_nodename = nodes[0].name nodes = mask.updateNode(nodes, req) if nodes: new_nodename = nodes[0].name if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer(): # for updates of node label in editor tree flag_nodename_changed = str(node.id) else: for field in mask.metaFields(): msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % ( __name__, funcname(), field, field.id, field.getName(), mask, maskname) logger.debug(msg) field_name = field.getName() if field_name == 'nodename' and maskname == 'settings': if '__nodename' in req.params: field_name = '__nodename' # no multilang here ! elif getDefaultLanguage() + '__nodename' in req.params: # no multilang here ! field_name = getDefaultLanguage() + '__nodename' value = req.params.get(field_name, None) if value: if value != node.name: flag_nodename_changed = str(node.id) for node in nodes: node.setName(value) value = req.params.get(field_name, None) if value is not None: for node in nodes: node.set(field.getName(), value) else: node.set(field.getName(), "") if "edit_metadata" in req.params or node.get("faulty") == "true": if not hasattr(mask, "i_am_not_a_mask"): req.params["errorlist"] = mask.validate(nodes) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date data["err"] = err _maskform, _fields = get_maskform_and_fields(nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) data["flag_nodename_changed"] = flag_nodename_changed ret += req.getTAL("web/edit/modules/metadata.html", data, macro="edit_metadata") return ret
def getContent(req, ids): user = users.getUserFromRequest(req) publishdir = tree.getNode(ids[0]) explicit = tree.getNodesByAttribute("writeaccess", user.getName()) ret = "" actionerror = [] changes = [] if "dopublish" in req.params.keys(): access = AccessData(req) objlist = [] for key in req.params.keys(): if key.isdigit(): objlist.append(key) src = tree.getNode(req.params.get("id")) for obj_id in objlist: faultylist = [] obj = tree.getNode(obj_id) for mask in obj.getType().getMasks(type="edit"): # check required fields if access.hasReadAccess(mask) and mask.getName()==obj.get("edit.lastmask"): for f in mask.validateNodelist([obj]): faultylist.append(f) if len(faultylist)>0: # object faulty actionerror.append(obj_id) continue for dest_id in req.params.get("destination", "").split(","): if dest_id=="": # no destination given continue dest = tree.getNode(dest_id) if dest != src and access.hasReadAccess(src) and access.hasWriteAccess(dest) and access.hasWriteAccess(obj) and isDirectory(dest): if not nodeIsChildOfNode(dest,obj): dest.addChild(obj) src.removeChild(obj) if dest.id not in changes: changes.append(dest.id) if src.id not in changes: changes.append(src.id) log.info("%s published %s (%r, %r) from src %s (%r, %r) to dest %s (%r, %r)" % ( user.getName(), obj.id, obj.name, obj.type, src.id, src.name, src.type, dest.id, dest.name, dest.type,)) else: actionerror.append(obj.id) log.error("Error in publishing of node %r: Destination node %r is child of node." % (obj_id, dest.id)) if not access.hasReadAccess(src): log.error("Error in publishing of node %r: source position %r has no read access." % (obj.id, src.id)) if not access.hasWriteAccess(dest): log.error("Error in publishing of node %r: destination %r has no write access." % (obj.id, dest.id)) if not access.hasWriteAccess(obj): log.error("Error in publishing of node %r: object has no write access." % obj.id) if not isDirectory(dest): log.error("Error in publishing of node %r: destination %r is not a directory." % (obj.id, dest.id)) v = {} v["id"] = publishdir.id v["change"] = changes ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload") # build normal window stddir = "" stdname = "" l = [] for n in explicit: if str(getHomeDir(user).id)!=str(n): l.append(n) if len(l)==1: stddir = str(l[0])+"," stdname = "- " + tree.getNode(l[0]).getName() #v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=0, markunpublished=1, nodes=[])} v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=None, markunpublished=1, nodes=[])} v["basedir"] = tree.getRoot('collections') v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" %(publishdir.id, publishdir.id) v["idstr"] = ids v["faultylist"] = actionerror ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form") return ret
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) if "metadata" in users.getHideMenusForUser(user): print "error 1" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") access = AccessData(req) faultydir = users.getFaultyDir(user) metatypes = [] nodes = [] masklist = [] err = 0 # flag indicating change of node.name (fancytree node may have to be updated) # keep as integer # negative -> no change # else -> id of changed node flag_nodename_changed = -1 for id in ids: node = tree.getNode(id) if not access.hasWriteAccess(node): print "error 2" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") schema = node.getSchema() if schema not in metatypes: metatypes.append(schema) if len(nodes) == 0 or nodes[0].getSchema() == schema: nodes += [node] idstr = ",".join(ids) action = req.params.get('action', '').strip() logger.info("%s in editor metadata (action=%r): %r" % (user.getName(), action, [[n.id, n.name, n.type]for n in nodes])) for m in node.getType().getMasks(type="edit"): if access.hasReadAccess(m): masklist.append(m) if hasattr(node, "metaFields"): class SystemMask: def __init__(self, name, description, fields): self.name, self.description, self.fields = name, description, fields def getName(self): return self.name def getDescription(self): return self.description def getDefaultMask(self): return False def metaFields(self, lang=None): return self.fields def i_am_not_a_mask(): pass masklist = [SystemMask( "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist default = None for m in masklist: if m.getDefaultMask(): default = m break if not default and len(masklist): default = masklist[0] maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask") if maskname == "": maskname = default.getName() mask = None for m in masklist: if maskname == m.getName(): mask = m break if not mask and default: mask = default maskname = default.getName() for n in nodes: n.set("edit.lastmask", maskname) if not mask: return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask") # context default for TAL interpreter ctx = {} ctx["user"] = user ctx["access"] = access ctx["metatypes"] = metatypes ctx["idstr"] = idstr ctx["node"] = nodes[0] # ? ctx["flag_nodename_changed"] = flag_nodename_changed ctx["nodes"] = nodes ctx["masklist"] = masklist ctx["maskname"] = maskname ctx["language"] = lang(req) ctx["t"] = t if action == 'restore': vid = req.params.get('vid', '0') node = nodes[0].getActiveVersion() if (vid != '0' and vid != node.id): n = tree.getNode(vid) # Not active version if n.next_nid != '0': next = tree.getNode(n.next_nid) if next.prev_nid != '0': next.removeChild(tree.getNode(next.prev_nid)) next.setPrevID(n.prev_nid) if n.prev_nid != '0': prev = tree.getNode(n.prev_nid) prev.setNextID(n.next_nid) n.removeChild(prev) next.addChild(prev) node.setNextID(n.id) n.setPrevID(node.id) n.setNextID('0') for pid in db.getParents(node.id): parentNode = tree.getNode(pid) parentNode.addChild(n) parentNode.removeChild(node) n.addChild(node) nodes = [n] ids = [n.id] node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + n.id + '&tab=metadata', 'pid': None, 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields(nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") if action == 'delete': vid = req.params.get('vid', '0') if (vid != '0'): node = nodes[0].getActiveVersion() n = tree.getNode(vid) if (vid != node.id): n.set("deleted", "true") for pid in db.getParents(n.id): parentNode = tree.getNode(pid) parentNode.removeChild(n) for cid in db.getChildren(n.id): n.removeChild(tree.getNode(cid)) if n.next_nid != '0' and n.prev_nid != '0': _next = tree.getNode(n.next_nid) _next.addChild(tree.getNode(n.prev_nid)) if n.next_nid != '0': _next = tree.getNode(n.next_nid) if n.prev_nid != '0': _next.setPrevID(n.prev_nid) if n.prev_nid != '0': _prev = tree.getNode(n.prev_nid) if n.next_nid != '0': _prev.setNextID(n.next_nid) else: pids = db.getParents(n.id) # Active version prev = None if n.prev_nid != '0': prev = tree.getNode(n.prev_nid) while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true": prev = tree.getNode(prev.prev_nid) if prev != None and prev.get("deleted") != "true": prev.setNextID('0') for pid in pids: parentNode = tree.getNode(pid) parentNode.addChild(prev) nodes = [prev] ids = [prev.id] n.set("deleted", "true") for pid in pids: parentNode = tree.getNode(pid) parentNode.removeChild(n) for cid in db.getChildren(n.id): n.removeChild(tree.getNode(cid)) if n.next_nid != '0' and n.prev_nid != '0': _next = tree.getNode(n.next_nid) _next.addChild(tree.getNode(n.prev_nid)) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid': None, 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") else: # Version 0 # Move node to trash trashdir = users.getTrashDir(user) trashdir.addChild(n) for pid in pids: parentNode = tree.getNode(pid) parentNode.removeChild(n) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[ 0], 'flag_nodename_changed': flag_nodename_changed} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") if "edit_metadata" in req.params: # check and save items userdir = users.getHomeDir(users.getUserFromRequest(req)) for node in nodes: if not access.hasWriteAccess(node) or node.id == userdir.id: print "error 3" req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") logging.getLogger('usertracing').info( access.user.name + " change metadata " + idstr) logging.getLogger('editor').info( access.user.name + " change metadata " + idstr) logging.getLogger('editor').debug(pf(req.params)) for node in nodes: node.set("updateuser", user.getName()) if node.get('updatetime') < str(now()): node.set("updatetime", str(format_date())) if not hasattr(mask, "i_am_not_a_mask"): if (req.params.get('generate_new_version')): # Create new node version _ids = [] _nodes = [] for node in nodes: n = node.createNewVersion(user) n.set("system.version.comment", '(' + t(req, "document_new_version_comment") + ')\n' + req.params.get('version_comment', '')) # add all existing attributes to the new version node for attr, value in node.items(): # do not overwrite existing attributes # do not copy system attributes if n.get(attr) != "" or attr.startswith("system."): pass else: n.set(attr, value) _nodes.append(n) _ids.append(n.id) ids = _ids idstr = ",".join(ids) nodes = _nodes nodes = mask.updateNode(nodes, req) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = { 'url': '?id=' + nodes[0].id + '&tab=metadata', 'pid': None, } data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date _maskform, _fields = get_maskform_and_fields( nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) ret += req.getTAL("web/edit/modules/metadata.html", data, macro="redirect") else: if nodes: old_nodename = nodes[0].name nodes = mask.updateNode(nodes, req) if nodes: new_nodename = nodes[0].name if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer(): # for updates of node label in editor tree flag_nodename_changed = str(node.id) else: for field in mask.metaFields(): msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % ( __name__, funcname(), field, field.id, field.getName(), mask, maskname) logger.debug(msg) field_name = field.getName() if field_name == 'nodename' and maskname == 'settings': if '__nodename' in req.params: field_name = '__nodename' # no multilang here ! elif getDefaultLanguage() + '__nodename' in req.params: # no multilang here ! field_name = getDefaultLanguage() + '__nodename' value = req.params.get(field_name, None) if value: if value != node.name: flag_nodename_changed = str(node.id) for node in nodes: node.setName(value) elif field_name in ('repec.code', 'repec.provider') and maskname == 'settings': if '__' + field_name in req.params: field_name = '__' + field_name # no multilang here! elif getDefaultLanguage() + '__' + field_name in req.params: field_name = getDefaultLanguage() + '__' + field_name # no multilang here! value = req.params.get(field_name, None) if value is not None: for node in nodes: node.set(field.getName(), value) else: node.set(field.getName(), "") if "edit_metadata" in req.params or node.get("faulty") == "true": if not hasattr(mask, "i_am_not_a_mask"): req.params["errorlist"] = mask.validate(nodes) node_versions = nodes[0].getVersionList() update_date, creation_date = get_datelists(nodes) data = {} data["versions"] = node_versions data["creation_date"] = creation_date data["update_date"] = update_date data["err"] = err _maskform, _fields = get_maskform_and_fields(nodes, mask, req) data["maskform"] = _maskform data["fields"] = _fields data.update(ctx) data["flag_nodename_changed"] = flag_nodename_changed ret += req.getTAL("web/edit/modules/metadata.html", data, macro="edit_metadata") return ret
def edit_tree(req): access = AccessData(req) language = lang(req) user = users.getUserFromRequest(req) home_dir = users.getHomeDir(user) match_result = '' match_error = False if req.params.get('key') == 'root': nodes = core.tree.getRoot( 'collections').getContainerChildren().sort_by_orderpos() elif req.params.get('key') == 'home': if not user.isAdmin(): nodes = [home_dir] else: homenodefilter = req.params.get('homenodefilter', '') if homenodefilter: nodes = [] try: pattern = re.compile(homenodefilter) nodes = tree.getRoot('home').getContainerChildren().sort_by_orderpos() # filter out shoppingbags etc. nodes = [n for n in nodes if n.isContainer()] # filter user name - after first "(" nodes = filter(lambda n: re.match(homenodefilter, n.getLabel(language).split('(', 1)[-1]), nodes) match_result = '#=%d' % len(nodes) except Exception as e: logger.warning('pattern matching for home nodes: %r' % e) match_result = '<span style="color:red">Error: %r</span>' % str(e) match_error = True if home_dir not in nodes: if not match_error: match_result = '#=%d+1' % len(nodes) nodes.append(home_dir) nodes = tree.NodeList(nodes).sort_by_orderpos() else: nodes = [home_dir] else: nodes = core.tree.getNode( req.params.get('key')).getContainerChildren().sort_by_orderpos() # filter out shoppingbags etc. nodes = [n for n in nodes if n.isContainer()] data = [] # wn 2014-03-14 # special directories may be handled in a special way by the editor special_dir_ids = {} special_dir_ids[home_dir.id] = 'userhomedir' for dir_type in ['upload', 'import', 'faulty', 'trash']: special_dir_ids[users.getSpecialDir(user, dir_type).id] = dir_type spec_dirs = ['userhomedir', 'upload', 'import', 'faulty', 'trash'] spec_dir_icons = ["homeicon.gif", "uploadicon.gif", "importicon.gif", "faultyicon.gif", "trashicon.gif"] for node in nodes: if not access.hasReadAccess(node): continue # try: # label = node.getLabel() # except: # label = node.getName() # # c = len(node.getContentChildren()) # if c>0: # label += ' <small>(%s)</small>' %(c) label = getTreeLabel(node, lang=language) nodedata = {'title': label, 'key': node.id, 'lazy': True, 'folder': True, 'readonly': 0, 'tooltip': '%s (%s)' % (node.getLabel(lang=language), node.id)} nodedata['icon'] = getEditorIconPath(node, req) if len(node.getContainerChildren()) == 0: nodedata['lazy'] = False nodedata['children'] = [] if not access.hasWriteAccess(node): if req.params.get('key') == 'home': continue nodedata['readonly'] = 1 nodedata['noLink'] = True nodedata['extraClasses'] = 'readonly' # fancytree else: nodedata['readonly'] = 0 nodedata['this_node_is_special'] = [] if node.id in special_dir_ids: nodedata['this_node_is_special'] = nodedata[ 'this_node_is_special'] + [special_dir_ids[node.id]] if node.id == home_dir.id: nodedata['match_result'] = match_result data.append(nodedata) return req.write(json.dumps(data, indent=4))
def frameset(req): id = req.params.get("id", tree.getRoot("collections").id) tab = req.params.get("tab", None) language = lang(req) access = AccessData(req) if not access.getUser().isEditor(): req.writeTAL("web/edit/edit.html", {}, macro="error") req.writeTAL("web/edit/edit.html", {"id": id, "tab": (tab and "&tab=" + tab) or ""}, macro="edit_notree_permission") req.setStatus(httpstatus.HTTP_FORBIDDEN) return try: currentdir = tree.getNode(id) except tree.NoSuchNodeError: currentdir = tree.getRoot("collections") req.params["id"] = currentdir.id id = req.params.get("id") nodepath = [] n = currentdir while n: nodepath = [n] + nodepath p = n.getParents() if p: n = p[0] else: n = None path = nidpath = ['%s' % p.id for p in nodepath] containerpath = [('%s' % p.id) for p in nodepath if p.isContainer()] user = users.getUserFromRequest(req) menu = filterMenu(getEditMenuString(currentdir.getContentType()), user) spc = [Menu("sub_header_frontend", "../", target="_parent")] if user.isAdmin(): spc.append( Menu("sub_header_administration", "../admin", target="_parent")) if user.isWorkflowEditor(): spc.append(Menu("sub_header_workflow", "../publish", target="_parent")) spc.append(Menu("sub_header_logout", "../logout", target="_parent")) def getPathToFolder(node): n = node path = [] while n: path = ['/%s' % (n.id)] + path p = n.getParents() if p: n = p[0] else: n = None return (node, "".join(path[2:])) def _getIDPath(nid, sep="/", containers_only=True): res = getIDPaths(nid, access, sep=sep, containers_only=containers_only) return res folders = {'homedir': getPathToFolder(users.getHomeDir(user)), 'trashdir': getPathToFolder(users.getSpecialDir( user, 'trash')), 'uploaddir': getPathToFolder(users.getSpecialDir(user, 'upload')), 'importdir': getPathToFolder(users.getSpecialDir(user, 'import'))} cmenu = sorted(getContainerTreeTypes(req), key=lambda x: x.getName()) cmenu_iconpaths = [] for ct in cmenu: ct_name = ct.getName() _n = tree.Node("", type=ct_name) # translations of ct_name will be offered in editor tree context menu cmenu_iconpaths.append( [ct, getEditorIconPath(_n), ct_name, translation_t(language, ct_name)]) # a html snippet may be inserted in the editor header header_insert = tree.getRoot('collections').get('system.editor.header.insert.' + language).strip() help_link = tree.getRoot('collections').get('system.editor.help.link.' + language).strip() homenodefilter = req.params.get('homenodefilter', '') v = { "id": id, "tab": (tab and "&tab=" + tab) or "", 'user': user, 'spc': spc, 'folders': folders, 'collectionsid': tree.getRoot('collections').id, "basedirs": [tree.getRoot('home'), tree.getRoot('collections')], 'cmenu': cmenu, 'cmenu_iconpaths': cmenu_iconpaths, 'path': path, 'containerpath': containerpath, 'language': lang(req), 't': translation_t, '_getIDPath': _getIDPath, 'system_editor_header_insert': header_insert, 'system_editor_help_link': help_link, 'homenodefilter': homenodefilter, } req.writeTAL("web/edit/edit.html", v, macro="edit_main")
def renameHomeDir(user, newusername): if (existsHomeDir(user)): getHomeDir(user).setName( translate("user_directory", getDefaultLanguage()) + " (" + newusername + ")")
def edit_tree(req): access = AccessData(req) language = lang(req) user = users.getUserFromRequest(req) home_dir = users.getHomeDir(user) match_result = "" match_error = False if req.params.get("key") == "root": nodes = core.tree.getRoot("collections").getContainerChildren().sort_by_orderpos() elif req.params.get("key") == "home": if not user.isAdmin(): nodes = [home_dir] else: homenodefilter = req.params.get("homenodefilter", "") if homenodefilter: nodes = [] try: pattern = re.compile(homenodefilter) nodes = tree.getRoot("home").getContainerChildren().sort_by_orderpos() # filter out shoppingbags etc. nodes = [n for n in nodes if n.isContainer()] # filter user name - after first "(" nodes = filter(lambda n: re.match(homenodefilter, n.getLabel(language).split("(", 1)[-1]), nodes) match_result = "#=%d" % len(nodes) except Exception as e: logger.warning("pattern matching for home nodes: %r" % e) match_result = '<span style="color:red">Error: %r</span>' % str(e) match_error = True if home_dir not in nodes: if not match_error: match_result = "#=%d+1" % len(nodes) nodes.append(home_dir) nodes = tree.NodeList(nodes).sort_by_orderpos() else: nodes = [home_dir] else: nodes = core.tree.getNode(req.params.get("key")).getContainerChildren().sort_by_orderpos() # filter out shoppingbags etc. nodes = [n for n in nodes if n.isContainer()] data = [] # wn 2014-03-14 # special directories may be handled in a special way by the editor special_dir_ids = {} special_dir_ids[home_dir.id] = "userhomedir" for dir_type in ["upload", "import", "faulty", "trash"]: special_dir_ids[users.getSpecialDir(user, dir_type).id] = dir_type spec_dirs = ["userhomedir", "upload", "import", "faulty", "trash"] spec_dir_icons = ["homeicon.gif", "uploadicon.gif", "importicon.gif", "faultyicon.gif", "trashicon.gif"] for node in nodes: if not access.hasReadAccess(node): continue # try: # label = node.getLabel() # except: # label = node.getName() # # c = len(node.getContentChildren()) # if c>0: # label += ' <small>(%s)</small>' %(c) label = getTreeLabel(node, lang=language) nodedata = { "title": label, "key": node.id, "lazy": True, "folder": True, "readonly": 0, "tooltip": "%s (%s)" % (node.getLabel(lang=language), node.id), } nodedata["icon"] = getEditorIconPath(node, req) if len(node.getContainerChildren()) == 0: nodedata["lazy"] = False nodedata["children"] = [] if not access.hasWriteAccess(node): if req.params.get("key") == "home": continue nodedata["readonly"] = 1 nodedata["noLink"] = True nodedata["extraClasses"] = "readonly" # fancytree else: nodedata["readonly"] = 0 nodedata["this_node_is_special"] = [] if node.id in special_dir_ids: nodedata["this_node_is_special"] = nodedata["this_node_is_special"] + [special_dir_ids[node.id]] if node.id == home_dir.id: nodedata["match_result"] = match_result data.append(nodedata) return req.write(json.dumps(data, indent=4))