def getContent(req, ids): user = users.getUserFromRequest(req) access = AccessData(req) node = tree.getNode(ids[0]) if "sortfiles" in users.getHideMenusForUser(user) or not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") c = getCollection(node) if "globalsort" in req.params: c.set("sortfield", req.params["globalsort"]) collection_sortfield = c.get("sortfield") class SortChoice: def __init__(self, label, value): self.label = label self.value = value sortfields = [SortChoice(t(req, "off"), "")] for ntype, num in c.getAllOccurences(AccessData(req)).items(): if ntype.getSortFields(): for sortfield in ntype.getSortFields(): sortfields += [SortChoice(sortfield.getLabel(), sortfield.getName())] sortfields += [SortChoice(sortfield.getLabel() + t(req, "descending"), "-" + sortfield.getName())] break return req.getTAL("web/edit/modules/sortfiles.html", {"node": node, "collection_sortfield": collection_sortfield, "sortchoices": sortfields, "name": c.getName()}, macro="edit_sortfiles")
def update_node(req, path, params, data, id): # get the user and verify the signature if params.get('user'): user = users.getUser(params.get('user')) userAccess = AccessData(user=user) if userAccess.user: valid = userAccess.verify_request_signature(req.fullpath, params) if not valid: userAccess = None else: userAccess = None else: user = users.getUser('Gast') userAccess = AccessData(user=user) node = tree.getNode(id) # check user access if userAccess and userAccess.hasAccess(node, "write"): pass else: s = "No Access" req.write(s) d = { 'status': 'fail', 'html_response_code': '403', 'errormessage': 'no access' } return d['html_response_code'], len(s), d node.name = params.get('name') metadata = json.loads(params.get('metadata')) # set provided metadata for key, value in metadata.iteritems(): node.set(u(key), u(value)) # service flags node.set("updateuser", user.getName()) node.set("updatetime", format_date()) node.setDirty() d = { 'status': 'OK', 'html_response_code': '200', 'build_response_end': time.time() } s = "OK" # we need to write in case of POST request, send as buffer wil not work req.write(s) req.reply_headers['updatetime'] = node.get('updatetime') return d['html_response_code'], len(s), d
def html(self, req): paths = "" stylebig = self.getContentStyles() liststyle = req.session.get("style-" + self.node.getContentType(), "") if not self.node.isContainer(): plist = getPaths(self.node, AccessData(req)) paths = tal.getTAL(theme.getTemplate("content_nav.html"), {"paths": plist}, macro="paths", language=lang(req)) # render style of node for nodebig if len(stylebig) > 1: # more than on style found for item in stylebig: if liststyle: if item.getName() == liststyle.getName(): return getFormatedString( self.node.show_node_big( req, template=item.getTemplate())) + paths else: if item.isDefaultStyle(): return getFormatedString( self.node.show_node_big( req, template=item.getTemplate())) + paths elif len(stylebig) == 1: return getFormatedString( self.node.show_node_big( req, template=stylebig[0].getTemplate())) + paths return getFormatedString(self.node.show_node_big(req)) + paths
def getPopup(self, req): access = AccessData(req) try: name = req.params['name'] fieldname = req.params.get('fieldname', name) except: logg.exception("missing request parameter") return httpstatus.HTTP_NOT_FOUND index = tree.getRoot("collections").getAllAttributeValues( name, access, req.params.get('schema')).keys() index.sort(lambda x, y: cmp(x.lower(), y.lower())) if req.params.get("print", "") != "": req.reply_headers[ "Content-Disposition"] = "attachment; filename=index.txt" for word in index: if word.strip() != "": req.write(word.strip() + "\r\n") return req.writeTAL("metadata/ilist.html", { "index": index, "fieldname": fieldname }, macro="popup") return httpstatus.HTTP_OK
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 write(self, req, contentHTML, show_navbar=1): self.params["show_navbar"] = show_navbar self.params["content"] = contentHTML self.params["act_node"] = req.params.get("id", req.params.get("dir", "")) self.params["acl"] = AccessData(req) rootnode = tree.getRoot("collections") self.params["header_items"] = rootnode.getCustomItems("header") self.params["footer_left_items"] = rootnode.getCustomItems("footer_left") self.params["footer_right_items"] = rootnode.getCustomItems("footer_right") self.params["t"] = time.strftime("%d.%m.%Y %H:%M:%S") self.params["head_meta"] = req.params.get('head_meta', '') # header self.params["header"] = req.getTAL(theme.getTemplate("frame.html"), self.params, macro="frame_header") # footer self.params["footer"] = req.getTAL(theme.getTemplate("frame.html"), self.params, macro="frame_footer") self.params["tree"] = "" self.params["search"] = "" if show_navbar == 1: # search mask self.params["search"] = req.getTAL( theme.getTemplate("frame.html"), { "search": self.params["navigation"]["search"], "act_node": self.params["act_node"]}, macro="frame_search") # tree self.params["tree"] = req.getTAL( theme.getTemplate("frame.html"), { "collections": self.collection_portlet.getCollections(), "acl": self.params["acl"]}, macro="frame_tree") req.writeTAL(theme.getTemplate("frame.html"), self.params, macro="frame")
def popup_thumbbig(self, req): access = AccessData(req) if (not access.hasAccess(self, "data") and not dozoom(self)) or not access.hasAccess(self, "read"): req.write(t(req, "permission_denied")) return thumbbig = None for file in self.getFiles(): if file.getType() == "thumb2": thumbbig = file break if not thumbbig: self.popup_fullsize(req) else: im = PILImage.open(thumbbig.retrieveFile()) req.writeTAL( "contenttypes/image.html", { "filename": '/file/' + str(self.id) + '/' + thumbbig.getName(), "width": im.size[0], "height": im.size[1] }, macro="thumbbig")
def export(req): p = req.path[1:].split("/") access = AccessData(req) if len(p) != 2: req.error(404, "Object not found") return if p[0].isdigit(): try: node = tree.getNode(p[0]) except: return req.error(404, "Object not found") else: return req.error(404, "Object not found") if not access.hasAccess(node, "read"): req.write(t(req, "permission_denied")) return mask = getMetaType(node.getSchema()).getMask(p[1]) if mask: try: req.reply_headers['Content-Type'] = "text/plain; charset=utf-8" req.write(mask.getViewHTML([node], flags=8)) # flags =8 -> export type except tree.NoSuchNodeError: return req.error(404, "Object not found") else: req.error(404, "Object not found") return
def getContent(req, ids): user = users.getUserFromRequest(req) access = AccessData(req) language = lang(req) node = tree.getNode(ids[0]) if "sort" in users.getHideMenusForUser(user) or not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") msg_t = (user.getName(), node.id, node.name, node.type, req.params) msg = "%s sorting subfolders of node %r (%r, %r): %r" % msg_t logger.info(msg) if "order" in req.params: # do reorder ids = req.params.get('order').split(',') children = [] for n in ids: child = tree.getNode(n) child.setOrderPos(ids.index(n)) children.append(child) req.writeTAL('web/edit/modules/subfolder.html', {'nodelist': children, "language": language}, macro="ordered_list") return "" elif "sortdirection" in req.params: # do automatic re-order i = 0 sort_dir = "" if req.params.get("sortdirection", "up") == "up" else "-" sorted_children = node.getContainerChildren().sort_by_fields(sort_dir + req.params.get("sortattribute")) for child in sorted_children: child.setOrderPos(i) i += 1 req.writeTAL('web/edit/modules/subfolder.html', {'nodelist': sorted_children, "language": language}, macro="ordered_list") return "" nodelist = [] attributes = [] fields = {} i = 0 for child in list(node.getContainerChildren().sort_by_orderpos()): i += 1 # count container children nodelist.append(child) if getMetaType(child.getSchema()): for field in getMetaType(child.getSchema()).getMetaFields(): if not field in fields.keys(): fields[field] = 0 fields[field] += 1 for field in fields: if i == fields[field]: attributes.append(field) ctx = { "node": node, "nodelist": nodelist, "sortattributes": sorted(attributes, lambda x, y: cmp(x.getLabel().lower(), y.getLabel().lower())), "language": language, } return req.getTAL("web/edit/modules/subfolder.html", ctx, macro="edit_subfolder")
def search_results(req, id): access = AccessData(req) user = users.getUserFromRequest(req) if "search" in users.getHideMenusForUser(user): req.writeTAL("web/edit/edit.html", {}, macro="access_error") return "" if "Reset" in req.params: return search_form(req, id, "edit_search_reset_msg") try: searchvalues = req.session["esearchvals"] except: req.session["esearchvals"] = searchvalues = {} node = tree.getNode(id) objtype = req.params["objtype"] type = getMetaType(objtype) query = "" if "full" in req.params: value = req.params["full"] searchvalues[objtype + ".full"] = value for word in value.split(" "): if word: if query: query += " and " query += "full=" + protect(word) for field in type.getMetaFields(): if field.Searchfield(): name = field.getName() if name in req.params and req.params.get(name, "").replace( "'", '').replace('"', '').strip() != "": value = req.params[name].strip() if value: searchvalues[objtype + "." + field.getName()] = value if field.getFieldtype() == "list" or field.getFieldtype( ) == "ilist" or field.getFieldtype() == "mlist": if query: query += " and " query += name + "=" + protect(value) else: query += name + "=" + protect(value) query += ' and schema="' + req.params.get("objtype", "*") + '"' utrace.info(access.user.name + " search for " + query) nodes = node.search(query) req.session["nodelist"] = EditorNodeList(nodes) if len(nodes): return req.getTAL("web/edit/modules/search.html", {"id": id}, macro="start_new_search") + shownodelist(req, nodes) return search_form(req, id, "edit_search_noresult_msg")
def objlist(req): node = tree.getNode(req.params["id"]) access = AccessData(req) if node.id==tree.getRoot().id or not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") return req.getTAL("web/edit/modules/license.html", {"node":node}, macro="edit_license")
def getPrintChildren(req, node, ret): access = AccessData(req) for c in node.getChildren(): if access.hasAccess(c, "read"): ret.append(c) getPrintChildren(req, c, ret) return ret
def html(self, req): styles = [] nodeprint = "1" # show print icon styles = self.content.getContentStyles() if "raw" in req.params: path = "" else: items = req.params.get("itemsperpage") try: id = self.content.node.id node = self.content.node if not node.getContentType() in ['collection', 'directory']: nodeprint = 0 else: if node.get("system.print") != "": nodeprint = node.get("system.print") except: id = 0 printlink = '/print/' + str(id) if nodeprint == "1" and "sortfield0" in req.params.keys(): printlink += '?sortfield0=' + str( req.params.get("sortfield0")) + '&sortfield1=' + str( req.params.get("sortfield1")) if req.params.get("show_navbar") == 0 or req.session.get( "area") == "publish": breadscrubs = [] else: try: breadscrubs = self.getPath(lang(req), access=AccessData(req)) except AttributeError: log.exception("") return req.error(404, "Object cannot be shown") path = req.getTAL(theme.getTemplate("content_nav.html"), { "params": self.params, "path": breadscrubs, "styles": styles, "logo": self.collectionlogo, "searchmode": req.params.get("searchmode", ""), "items": items, "id": id, "nodeprint": nodeprint, "printlink": printlink, "area": req.session.get("area", "") }, macro="path") return path + '\n<!-- CONTENT START -->\n' + self.content.html( req) + '\n<!-- CONTENT END -->\n'
def getNodeListXMLForUser(node, readuser=None, exclude_filetypes=[], attribute_name_filter=None): if readuser: # only write child data if children_access_user has read access children_access = AccessData(user=users.getUser(readuser)) else: children_access = None wr = _StringWriter() wr.write('<nodelist exportversion="%s">\n' % getInformation()["version"]) node.writexml(wr, children_access=children_access, exclude_filetypes=exclude_filetypes, attribute_name_filter=attribute_name_filter) wr.write("</nodelist>\n") return wr.get()
def getSchemas(self): schemas = filter(lambda x: x.isActive(), loadTypesFromDB()) schemalist = {} for user in self.getChildren(): try: for schema in AccessData(user=user).filter(schemas): schemalist[schema.getName()] = "." except: pass schemalist = sorted(schemalist.keys()) return schemalist
def show_attachmentbrowser(req): id = req.params.get("id") node = getNode(id) access = AccessData(req) if not access.hasAccess(node, "data"): req.write(t(req, "permission_denied")) return # if node.getContentType().startswith("document") or node.getContentType().startswith("dissertation"): # node.getAttachmentBrowser(req) from core.attachment import getAttachmentBrowser getAttachmentBrowser(node, req)
def popup_fullsize(self, req): access = AccessData(req) if not access.hasAccess(self, "data") or not access.hasAccess( self, "read"): req.write(t(req, "permission_denied")) return for f in self.getFiles(): if f.getType() == "doc" or f.getType() == "document": req.sendFile(f.retrieveFile(), f.getMimeType()) return
def popup_fullsize(self, req): access = AccessData(req) if not access.hasAccess(self, "data") or not access.hasAccess(self, "read"): req.write(t(req, "permission_denied")) return f = "" for filenode in self.getFiles(): if filenode.getType() in ("original", "video"): f = "/file/" + str(self.id) + "/" + filenode.getName() break req.writeTAL("contenttypes/flash.html", {"path": f}, macro="fullsize")
def send_rawimage(req): access = AccessData(req) try: n = tree.getNode(splitpath(req.path)[0]) except tree.NoSuchNodeError: return 404 if not access.hasAccess(n, "data") and n.type != "directory": return 403 for f in n.getFiles(): if f.getType() == "original": incUsage(n) return req.sendFile(f.retrieveFile(), f.getMimeType()) return 404
def send_attachment(req): access = AccessData(req) id, filename = splitpath(req.path) try: node = tree.getNode(id) except tree.NoSuchNodeError: return 404 if not access.hasAccess(node, "data") and n.type != "directory": return 403 # filename is attachment.zip for file in node.getFiles(): if file.getType() == "attachment": sendZipFile(req, file.retrieveFile()) break
def writetree(req, node, f, key="", openednodes=None, sessionkey="unfoldedids", omitroot=0): ret = "" access = AccessData(req) try: unfoldedids = req.session[sessionkey] len(unfoldedids) except: req.session[sessionkey] = unfoldedids = {tree.getRoot().id: 1} if openednodes: # open all selected nodes and their parent nodes def o(u, n): u[n.id] = 1 for n in n.getParents(): o(u, n) for n in openednodes: o(unfoldedids, n) req.session[sessionkey] = unfoldedids try: unfold = req.params["tree_unfold"] unfoldedids[unfold] = 1 except KeyError: pass try: fold = req.params["tree_fold"] unfoldedids[fold] = 0 except KeyError: pass if omitroot: for c in node.getChildren().sort("name"): ret += writenode(req, c, unfoldedids, f, 0, key, access) else: ret += writenode(req, node, unfoldedids, f, 0, key, access) return ret
def popup_fullsize(self, req): def videowidth(): return int(self.get('vid-width') or 0) + 64 def videoheight(): int(self.get('vid-height') or 0) + 53 access = AccessData(req) if not access.hasAccess(self, "data") or not access.hasAccess( self, "read"): req.write(t(req, "permission_denied")) return f = None for filenode in self.getFiles(): if filenode.getType() in [ "original", "video" ] and filenode.retrieveFile().endswith('flv'): f = "/file/%s/%s" % (self.id, filenode.getName()) break script = "" if f: script = '<p href="%s" style="display:block;width:%spx;height:%spx;" id="player"/p>' % ( f, videowidth(), videoheight()) # use jw player captions_info = getCaptionInfoDict(self) if captions_info: logger.info( "video: '%s' (%s): captions: dictionary 'captions_info': %s" % (self.name, self.id, captions_info)) context = { "file": f, "script": script, "node": self, "width": videowidth(), "height": videoheight(), "captions_info": json.dumps(captions_info), } req.writeTAL("contenttypes/video.html", context, macro="fullsize_flv_jwplayer")
def getContent(req, ids): user = users.getUserFromRequest(req) access = AccessData(user=user) language = lang(req) node = tree.getNode(ids[0]) if not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") if req.params.get("upload")=="uploadfile": # try to import file return import_new(req) v = {"error":req.params.get("error")} class SortChoice: def __init__(self, label, value): self.label = label self.value = value col = node if "globalsort" in req.params: col.set("sortfield", req.params.get("globalsort")) v['collection_sortfield'] = col.get("sortfield") sortfields = [SortChoice(t(req,"off"),"")] if col.type not in ["root", "collections", "home"]: for ntype, num in col.getAllOccurences(acl.AccessData(req)).items(): if ntype.getSortFields(): for sortfield in ntype.getSortFields(): sortfields += [SortChoice(sortfield.getLabel(), sortfield.getName())] sortfields += [SortChoice(sortfield.getLabel()+t(req,"descending"), "-"+sortfield.getName())] break v['sortchoices'] = sortfields v['ids'] = ids v['count'] = len(node.getContentChildren()) v['nodelist'] = showdir(req, node) v['language'] = lang(req) v['t'] = t _html = req.getTAL("web/edit/modules/imports.html", v, macro="upload_form") return _html
def send_nodefile_tal(req): if "file" in req.params: return upload_for_html(req) id = req.params.get("id") node = tree.getNode(id) access = AccessData(req) if not (access.hasAccess(node, 'read') and access.hasAccess(node, 'write') and access.hasAccess(node, 'data') and node.type in ["directory", "collections", "collection"]): return "" def fit(imagefile, cn): # fits the image into a box with dimensions cn, returning new width and # height try: sz = PIL.Image.open(imagefile).size (x, y) = (sz[0], sz[1]) if x > cn[0]: y = (y * cn[0]) / x x = (x * cn[0]) / x if y > cn[1]: x = (x * cn[1]) / y y = (y * cn[1]) / y return (x, y) except: return cn # only pass images to the file browser files = [f for f in node.getFiles() if f.mimetype.startswith("image")] # this flag may switch the display of a "delete" button in the customs # file browser in web/edit/modules/startpages.html showdelbutton = True return req.getTAL("web/edit/modules/startpages.html", { "id": id, "node": node, "files": files, "fit": fit, "logoname": node.get("system.logo"), "delbutton": True }, macro="fckeditor_customs_filemanager")
def send_rawfile(req, n=None): access = AccessData(req) if not n: id, filename = splitpath(req.path) n = None try: n = tree.getNode(id) except tree.NoSuchNodeError: return 404 if not access.hasAccess(n, "data") and n.getContentType() not in [ "directory", "collections", "collection" ]: return 403 for f in n.getFiles(): if f.getType() == "original": incUsage(n) return req.sendFile(f.retrieveFile(n), f.getMimeType(n)) return 404
def getAccessRights(node): """ Get acccess rights for the public. The values returned descend from http://wiki.surffoundation.nl/display/standards/info-eu-repo/#info-eu-repo-AccessRights. This values are used by OpenAIRE portal. """ try: # if node.get('updatetime') is empty, the method parse_date would raise an exception l_date = parse_date(node.get('updatetime')) except: l_date = date.now() guestAccess = AccessData(user=users.getUser('Gast')) if date.now() < l_date: return "embargoedAccess" elif guestAccess.hasAccess(node, 'read'): if guestAccess.hasAccess(node, 'data'): return "openAccess" else: return "restrictedAccess" else: return "closedAccess"
def getPathTo(req): # returns path(s) to selected node, 'x' separated, with selected nodes in () # parameters: pathTo=selected Node access = AccessData(req) collectionsid = tree.getRoot('collections').id id = req.params.get("pathTo", collectionsid).split(",")[0] node = tree.getNode(id) items = [] checked = [] for path in getPaths(node, access): if node.id not in path and node.isContainer(): # add node if container path.append(node) checked.append(path[-1].id) # last item of path is checked if path[0].getParents()[0].id == collectionsid and collectionsid not in items: items.append(collectionsid) for item in path: if item.id not in items: items.append(item.id) items.append("x") # set devider for next path if req.params.get("multiselect", "false") == "false": # if not multiselect use only first path break if len(items) == 0 or collectionsid in tree.getNode(items[0]).getParents()[0].id: items = [collectionsid] + items items = (",").join(items) for check in checked: # set marked items items = items.replace(check, "(%s)" % (check)) req.write(items) return
def getContent(req, ids): ret = "" user = users.getUserFromRequest(req) access = AccessData(req) nodes = [] for id in ids: if not access.hasWriteAccess(tree.getNode(id)): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") nodes += [tree.getNode(id)] if "classes" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") v = {} v["basedirs"] = [tree.getRoot('home'), tree.getRoot('collections')] id = req.params.get("id", tree.getRoot().id) v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" % (id, id) v["idstr"] = ",".join(ids) v["nodes"] = nodes v["t"] = t v["language"] = lang(req) return req.getTAL("web/edit/modules/classes.html", v, macro="classtree")
def popup_fullsize(self, req): access = AccessData(req) d = {} svg = 0 if (not access.hasAccess(self, "data") and not dozoom(self)) or not access.hasAccess(self, "read"): req.write(t(req, "permission_denied")) return zoom_exists = 0 for file in self.getFiles(): if file.getType() == "zoom": zoom_exists = 1 if file.getName().lower().endswith( 'svg') and file.type == "original": svg = 1 d["svg"] = svg d["width"] = self.get("origwidth") d["height"] = self.get("origheight") d["key"] = req.params.get("id", "") # we assume that width==origwidth, height==origheight d['flash'] = dozoom(self) and zoom_exists d['tileurl'] = "/tile/" + self.id + "/" req.writeTAL("contenttypes/image.html", d, macro="imageviewer")
def send_attfile(req): access = AccessData(req) f = req.path[9:].split('/') try: node = getNode(f[0]) except tree.NoSuchNodeError: return 404 if not access.hasAccess(node, "data") and node.type != "directory": return 403 if len([ file for file in node.getFiles() if file._path in ["/".join(f[1:]), "/".join(f[1:-1])] ]) == 0: # check filepath return 403 filename = clean_path("/".join(f[1:])) path = join_paths(config.get("paths.datadir"), filename) mime, type = getMimeType(filename) if (get_filesize(filename) > 16 * 1048576): req.reply_headers[ "Content-Disposition"] = 'attachment; filename="{}"'.format( filename) return req.sendFile(path, mime)