def mkContentNode(req): access = AccessData(req) id = req.params.get("id", tree.getRoot("collections").id) try: node = tree.getNode(id) except tree.NoSuchNodeError: return ContentError("No such node", 404) if not access.hasReadAccess(node): return ContentError("Permission denied", 403) if node.type in ["directory", "collection"]: if "files" not in req.params and len( filter(None, node.getStartpageDict().values())) > 0: for f in node.getFiles(): if f.type == "content" and f.mimetype == "text/html" and os.path.isfile( f.retrieveFile()) and fileIsNotEmpty(f.retrieveFile()): return ContentNode(node) ids = access.filter( list(set(tree.getAllContainerChildrenAbs(node, [])))) node.ccount = len(ids) #ids = access.filter(node.getAllChildren()) c = ContentList(tree.NodeList(ids), getCollection(node)) c.feedback(req) c.node = node return c else: return ContentNode(node)
def mkContentNode(req): access = AccessData(req) id = req.params.get("id", tree.getRoot("collections").id) try: node = tree.getNode(id) except tree.NoSuchNodeError: return ContentError("No such node", 404) if not access.hasReadAccess(node): return ContentError("Permission denied", 403) if node.type in ["directory", "collection"]: if "files" not in req.params and len(filter(None, node.getStartpageDict().values())) > 0: for f in node.getFiles(): if f.type == "content" and f.mimetype == "text/html" and os.path.isfile( f.retrieveFile()) and fileIsNotEmpty(f.retrieveFile()): return ContentNode(node) ids = access.filter(list(set(tree.getAllContainerChildrenAbs(node, [])))) node.ccount = len(ids) #ids = access.filter(node.getAllChildren()) c = ContentList(tree.NodeList(ids), getCollection(node)) c.feedback(req) c.node = node return c else: return ContentNode(node)
def _get_child_collections(self): acl = AccessData(self.request) active_collection = self.active_collection nodes = tree.getChildNodesByFieldValue(active_collection.node.id, **{"repec.code": '__is_set__'}) if len(nodes) == 0: log.info("Collection with code %s does not have child collections" % active_collection['repec.code']) return [Node(self.request, self, node) for node in nodes if acl.hasReadAccess(node)]
def getData(req): access = AccessData(req) pid = req.params.get("parentId") style = req.params.get("style", "edittree") ret = [] for c in tree.getNode(pid).getChildren().sort_by_orderpos(): if not access.hasReadAccess(c): continue try: if c.isContainer(): cnum = len(c.getContainerChildren()) inum = len(c.getContentChildren()) label = c.getLabel() title = c.getLabel() + " (" + str(c.id) + ")" cls = "folder" itemcls = "" if not access.hasWriteAccess(c): itemcls = "read" if c.type == "collection": # or "collection" in c.type: cls = "collection" if hasattr(c, 'treeiconclass'): cls = c.treeiconclass() if c.getName().startswith(translate('user_trash', request=req)): cls = "trashicon" elif c.getName().startswith(translate('user_upload', request=req)): cls = "uploadicon" elif c.getName().startswith(translate('user_import', request=req)): cls = "importicon" elif c.getName().startswith(translate('user_faulty', request=req)): cls = "faultyicon" elif c.getName().startswith(translate('user_directory', request=req)): cls = "homeicon" if style == "edittree": # standard tree for edit area if inum > 0: label += " <small>(" + str(inum) + ")</small>" ret.append('<li class="' + cls + '.gif" id="Node' + c.id + '">') ret.append('<a href="#" title="' + title + '" id="' + c.id + '" class="' + itemcls + '">' + label + '</a>') if cnum > 0: ret.append('<ul><li parentId="' + c.id + '" class="spinner.gif"><a href="#"> </a></li></ul>') ret.append('</li>') elif style == "classification": # style for classification ret.append('<li class="' + cls + '.gif" id="Node' + c.id + '">') ret.append('<a href="#" title="' + title + '" id="' + c.id + '" class="' + itemcls + '">' + label + ' <input type="image" src="/img/ftree/uncheck.gif"/></a>') if cnum > 0: ret.append('<ul><li parentId="' + c.id + '" class="spinner.gif"><a href="#"> </a></li></ul>') ret.append('</li>') except: pass req.write("\n".join(ret)) return
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 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 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 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 _get_active_collection(self): """ Gets the active collection based on the request url. The RePEc code is used to choose the collection. Expects URL path in the format as follows: * `/repec/REPEC_CODE` * `/repec/REPEC_CODE/REPEC_CODEarch.rdf` * `/repec/REPEC_CODE/REPEC_CODEseri.rdf` * `/repec/REPEC_CODE/CHILD_REPEC_CODEjournl/...` * `/repec/REPEC_CODE/CHILD_REPEC_CODEwpaper/...` """ acl = AccessData(self.request) try: path_match = _MATCH_REPEC_CODE.match(self.request.fullpath) repec_code = path_match.group("code") repec_code_check = path_match.group("code_check") # if we have a check-code in the url, it must equal the code value if repec_code_check is not None and repec_code_check != repec_code: log.info("RePEc check code does not match") raise AttributeError except (IndexError, AttributeError): # path does not contain a repec code log.info("RePEc collection not found") self.status_code = httpstatus.HTTP_NOT_FOUND return None # try to load the node try: nodes = tree.getNodesByFieldValue(**{"repec.code": repec_code}) if len(nodes) != 1: if len(nodes) > 1: log.info("More than one collection with code %s" % repec_code) else: log.info("No collection with code %s" % repec_code) raise tree.NoSuchNodeError node = nodes[0] except tree.NoSuchNodeError: # requested node not in DB, so set status to 404 self.status_code = httpstatus.HTTP_NOT_FOUND return None # assert that the found node is not an child collection of another RePEc collection for parent in node.getParents(): try: self._get_inherited_attribute_value(parent, 'repec.code') raise ValueError except KeyError: pass except ValueError: # requested node is a child collection, so set status to 404 self.status_code = httpstatus.HTTP_NOT_FOUND return None # check for read permissions on requested node if not acl.hasReadAccess(node): log.info("No access to collection with code %s" % repec_code) # requested node in DB but no access, so set status to 403 self.status_code = httpstatus.HTTP_FORBIDDEN return None # assert the found node is a directory or collection if node.type not in ("directory", "collection"): log.error("Node with code %s is not a collection" % repec_code) # requested node in DB and accessible, but not a collection type self.status_code = httpstatus.HTTP_INTERNAL_SERVER_ERROR return None # everything went fine, we can continue self.status_code = httpstatus.HTTP_OK return Node(self.request, self, node)
def _get_active_child_collection(self): """ Gets the active child collection based on the request url. The child RePEc code is used to choose the collection. Expects URL path in the format as follows: * `/repec/REPEC_CODE/CHILD_REPEC_CODEjournl/...` * `/repec/REPEC_CODE/CHILD_REPEC_CODEwpaper/...` """ acl = AccessData(self.request) # when we request for an child collection, we need to assert there was a parent collection if not self.active_collection: log.info("RePEc parent collection not found") self.status_code = httpstatus.HTTP_NOT_FOUND return None try: path_match = _MATCH_CHILD_REPEC_CODE.match(self.request.fullpath) repec_child_code = path_match.group("child_code") # if we have a check-code in the url, it must equal the code value if repec_child_code is None: log.info("RePEc child collection code not found") raise AttributeError except (IndexError, AttributeError): # path does not contain a repec code log.info("RePEc child collection not found") self.status_code = httpstatus.HTTP_NOT_FOUND return None # try to load the node try: nodes = tree.getChildNodesByFieldValue(self.active_collection.node.id, **{"repec.code": repec_child_code}) if len(nodes) != 1: if len(nodes) > 1: log.info("More than one child collection with code %s" % repec_child_code) else: log.info("No collection with code %s" % repec_child_code) raise tree.NoSuchNodeError node = nodes[0] except tree.NoSuchNodeError: # requested node not in DB, so set status to 404 self.status_code = httpstatus.HTTP_NOT_FOUND return None if not acl.hasReadAccess(node): log.info("No access to child collection with code %s" % repec_child_code) # requested node in DB but no access, so set status to 403 self.status_code = httpstatus.HTTP_FORBIDDEN return None if node.type not in ("directory", "collection"): log.error("Node with code %s is not a collection" % repec_child_code) # requested node in DB and accessible, but not a collection type self.status_code = httpstatus.HTTP_INTERNAL_SERVER_ERROR return None # node exists and accessible self.status_code = httpstatus.HTTP_OK return Node(self.request, self, node)
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