def getPath(self, language=None, access=None): path = [] if hasattr(self.content, "node"): cd = self.content.node if cd is not None: if isinstance(cd, Directory): path.append(Link('', cd.getLabel(language), '')) else: path.append(Link('', cd.getLabel(), '')) while True: parents = cd.getParents() if access: parents = access.filter(parents) if len(parents) == 0: break cd = parents[0] if cd is tree.getRoot("collections") or cd is tree.getRoot(): break if isinstance(cd, Directory): path.append(Link('/?id=' + cd.id + '&dir=' + cd.id, cd.getLabel(language), cd.getLabel(language))) else: path.append(Link('/?id=' + cd.id + '&dir=' + cd.id, cd.getLabel(), cd.getLabel())) elif hasattr(self.content, "linkname") and hasattr(self.content, "linktarget"): path.append(Link(self.content.linktarget, self.content.linkname, self.content.linkname)) path.reverse() return path
def pwdchange(req, error=0): if len(req.params) > 2 and "password_old" not in req.params: # user changed to browsing return buildURL(req) user = users.getUserFromRequest(req) if not user.canChangePWD() and not user.isAdmin(): error = 4 # no rights elif "ChangeSubmit" in req.params: if user.getName() == config.get("user.guestuser"): req.request["Location"] = req.makeLink("node", {"id": tree.getRoot("collections").id}) return httpstatus.HTTP_MOVED_TEMPORARILY else: if not users.checkLogin(user.getName(), req.params.get("password_old")): error = 1 # old pwd does not match elif req.params.get("password_new1") != req.params.get("password_new2"): error = 2 # new pwds do not match else: user.setPassword(req.params.get("password_new2")) req.request["Location"] = req.makeLink("node", {"id": tree.getRoot("collections").id}) return httpstatus.HTTP_MOVED_TEMPORARILY navframe = frame.getNavigationFrame(req) navframe.feedback(req) contentHTML = req.getTAL(theme.getTemplate("login.html"), {"error": error, "user": user}, macro="change_pwd") navframe.write(req, contentHTML) return httpstatus.HTTP_OK
def handletabs(req, ids, tabs): user = users.getUserFromRequest(req) language = lang(req) n = tree.getNode(ids[0]) if n.type.startswith("workflow"): n = tree.getRoot() menu = filterMenu(getEditMenuString(n.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")) # a html snippet may be inserted in the editor header help_link = tree.getRoot("collections").get("system.editor.help.link." + language).strip() ctx = { "user": user, "ids": ids, "idstr": ",".join(ids), "menu": menu, "hashelp": help.getHelpPath(["edit", "modules", req.params.get("tab") or tabs]), "breadcrumbs": getBreadcrumbs(menu, req.params.get("tab", tabs)), "spc": spc, "system_editor_help_link": help_link, } return req.getTAL("web/edit/edit.html", ctx, macro="edit_tabs")
def getPath(self, language=None, access=None): path = [] if hasattr(self.content, "node"): cd = self.content.node if cd is not None: if isinstance(cd, Directory): path.append(Link('', cd.getLabel(language), '')) else: path.append(Link('', cd.getLabel(), '')) while True: parents = cd.getParents() if access: parents = access.filter(parents) if len(parents) == 0: break cd = parents[0] if cd is tree.getRoot( "collections") or cd is tree.getRoot(): break if isinstance(cd, Directory): path.append( Link('/?id=' + cd.id + '&dir=' + cd.id, cd.getLabel(language), cd.getLabel(language))) else: path.append( Link('/?id=' + cd.id + '&dir=' + cd.id, cd.getLabel(), cd.getLabel())) elif hasattr(self.content, "linkname") and hasattr( self.content, "linktarget"): path.append( Link(self.content.linktarget, self.content.linkname, self.content.linkname)) path.reverse() return path
def getHomeDir(user): username = user.getName() userdir = None for c in tree.getRoot("home").getChildren(): if (c.getAccess("read") or "").find("{user " + username + "}") >= 0 and ( c.getAccess("write") or "").find("{user " + username + "}") >= 0: return c # create new userdir userdir = tree.getRoot("home").addChild( tree.Node(name=buildHomeDirName(username), type="directory")) userdir.setAccess("read", "{user " + username + "}") userdir.setAccess("write", "{user " + username + "}") userdir.setAccess("data", "{user " + username + "}") log.debug("created new home directory %r (%r) for user %r" % (userdir.name, userdir.id, username)) # re-sort home dirs alphabetically i = 0 for child in tree.getRoot("home").getChildren().sort_by_name(): child.setOrderPos(i) i += 1 return userdir
def getUser(id): """ returns user object from db """ users = tree.getRoot("users") if id.isdigit(): try: user = tree.getNode(id) if user.type == "user": return user return None except tree.NoSuchNodeError as e: return None else: try: user = users.getChild(id) return user except tree.NoSuchNodeError as e: for key in getExternalAuthentificators(): u = getExternalUser(id, type=key) if u: # u.setUserType(key) return u for u in tree.getRoot("users").getChildren(): if u.get('service.userkey') == id: return u return None
def getUser(id): """ returns user object from db """ users = tree.getRoot("users") if id.isdigit(): try: user = tree.getNode(id) if user.type == "user": return user return None except tree.NoSuchNodeError as e: return None else: try: user = users.getChild(id) return user except tree.NoSuchNodeError as e: for key in getExternalAuthentificators(): u = getExternalUser(id, type=key) if u: # u.setUserType(key) return u for u in tree.getRoot("users").getChildren(): if u.get('service.userkey') == id: return u return None
def handletabs(req, ids, tabs): user = users.getUserFromRequest(req) language = lang(req) n = tree.getNode(ids[0]) if n.type.startswith("workflow"): n = tree.getRoot() menu = filterMenu(getEditMenuString(n.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")) # a html snippet may be inserted in the editor header help_link = tree.getRoot('collections').get('system.editor.help.link.' + language).strip() ctx = { "user": user, "ids": ids, "idstr": ",".join(ids), "menu": menu, "hashelp": help.getHelpPath(['edit', 'modules', req.params.get('tab') or tabs]), "breadcrumbs": getBreadcrumbs(menu, req.params.get("tab", tabs)), "spc": spc, "system_editor_help_link": help_link, } return req.getTAL("web/edit/edit.html", ctx, macro="edit_tabs")
def r(node, path): if node is tree.getRoot(): return for p in node.getParents(): path.append(p) if p is not tree.getRoot("collections"): r(p, path) return path
def r(node, path): if node is tree.getRoot(): return for p in node.getParents(): path.append(p) if p is not tree.getRoot("collections"): r(p, path) return path
def update_user(id, name, email, groups, lastname="", firstname="", telephone="", comment="", option="", organisation="", identificator="", type="intern"): try: # internal user user = getUser(id) except: # external user user = getExternalUser(id) if user: for p in user.getParents(): if p.type != "usergroup": p.removeChild(user) if type == "intern": tree.getRoot("users").addChild(user) else: getExternalUserFolder(type).addChild(user) if user.getName() != name: # username changed -> update home directory hd = getHomeDir(user) hd.setAccess("read", "{user %s}" % (user.getName())) hd.setAccess("write", "{user %s}" % (user.getName())) if user: user.setName(name) user.setEmail(email) user.setLastName(lastname) user.setFirstName(firstname) user.setTelephone(telephone) user.setComment(comment) user.setOption(option) user.setOrganisation(organisation) if identificator != "": user.set('identificator', identificator) # remove user from all groups for p in user.getParents(): if p.type == "usergroup": p.removeChild(user) # add user to the "new" groups for group in groups.split(","): g = usergroups.getGroup(group) g.addChild(user) else: print "user not found" return user
def retrieveNodes(req, access, setspec, date_from=None, date_to=None, metadataformat=None): schemata = [] if metadataformat == 'mediatum': metadatatypes = tree.getRoot('metadatatypes').getChildren() schemata = [m.name for m in metadatatypes if m.type == 'metadatatype' and m.name not in ['directory', 'collection']] elif metadataformat: mdt_masks_list = getExportMasks("oai_" + metadataformat.lower() + "$") # check exact name schemata = [x[0][1] for x in mdt_masks_list if x[1]] if DEBUG: timetable_update(req, "in retrieveNodes: find schemata with export mask for metadata type %s (%d found: '%s')" % (metadataformat.lower(), len(schemata), str([x for x in schemata]))) if setspec: res = oaisets.getNodes(setspec, schemata) else: osp = OAISearchParser() query = " or ".join(["schema=%s" % schema for schema in schemata]) res = osp.parse(query).execute() res = tree.NodeList(res) if DEBUG: timetable_update(req, "in retrieveNodes: after building NodeList for %d nodes" % (len(res))) if date_from: res = [n for n in res if n.get(DATEFIELD) >= str(date_from)] if DEBUG: timetable_update(req, "in retrieveNodes: after filtering date_from --> %d nodes" % (len(res))) if date_to: res = [n for n in res if n.get(DATEFIELD) <= str(date_to)] if DEBUG: timetable_update(req, "in retrieveNodes: after filtering date_to --> %d nodes" % (len(res))) if access: res = access.filter(res) if DEBUG: timetable_update(req, "in retrieveNodes: after access filter --> %d nodes" % (len(res))) collections = tree.getRoot('collections') res = [n for n in res if isDescendantOf(n, collections)] if DEBUG: timetable_update(req, "in retrieveNodes: after checking descendance from basenode --> %d nodes" % (len(res))) if schemata: res = [n for n in res if n.getSchema() in schemata] if DEBUG: timetable_update(req, "in retrieveNodes: after schemata (%s) filter --> %d nodes" % (str(schemata), len(res))) if metadataformat and metadataformat.lower() in FORMAT_FILTERS.keys(): format_string = metadataformat.lower() res = [n for n in res if filterFormat(n, format_string)] if DEBUG: timetable_update(req, "in retrieveNodes: after format (%s) filter --> %d nodes" % (format_string, len(res))) return res
def indexer_thread(timewait): if timewait < 10: timewait = 10 while True: time.sleep(timewait - 10) log.info("Re-indexing Database") time.sleep(10) makeSearchIndex() log.info("Re-indexing Database: done") tree.getRoot().set("lastindexerrun", date.format_date())
def indexer_thread(timewait): if timewait < 10: timewait = 10 while True: time.sleep(timewait - 10) log.info("Re-indexing Database") time.sleep(10) makeSearchIndex() log.info("Re-indexing Database: done") tree.getRoot().set("lastindexerrun", date.format_date())
def updateWorkflow(name, description, origname="", writeaccess=""): if origname == "": node = tree.getRoot("workflows") if not node.hasChild(name): addWorkflow(name, description) w = tree.getRoot("workflows").getChild(name) else: w = tree.getRoot("workflows").getChild(origname) w.setName(name) w.set("description", description) w.setAccess("write", writeaccess)
def updateWorkflow(name, description, origname="", writeaccess=""): if origname == "": node = tree.getRoot("workflows") if not node.hasChild(name): addWorkflow(name, description) w = tree.getRoot("workflows").getChild(name) else: w = tree.getRoot("workflows").getChild(origname) w.setName(name) w.set("description", description) w.setAccess("write", writeaccess)
def getMappings(): try: mappings = tree.getRoot("mappings") except tree.NoSuchNodeError as e: root = tree.getRoot() root.addChild(tree.Node("mappings", "mappings")) mappings = tree.getRoot("mappings") try: return mappings.getChildren() except tree.NoSuchNodeError as e: return []
def getMappings(): try: mappings = tree.getRoot("mappings") except tree.NoSuchNodeError as e: root = tree.getRoot() root.addChild(tree.Node("mappings", "mappings")) mappings = tree.getRoot("mappings") try: return mappings.getChildren() except tree.NoSuchNodeError as e: return []
def ensureSchedulesRoot(): try: schedules = tree.getRoot('schedules') msg = "scheduler: root node 'schedules' (id=%s) found" % str(schedules.id) OUT(msg) except tree.NoSuchNodeError as e: schedules = tree.Node(name='schedules', type='schedules') root = tree.getRoot() root.addChild(schedules) msg = "scheduler: created root node 'schedules' (id=%s)" % str(schedules.id) OUT(msg)
def deleteUser(user, usertype="intern"): """ delete user from db """ if usertype in getDynamicUserAuthenticators(): a = getExternalAuthentificator(usertype) for u in a.LOGGED_IN_DYNUSERS.values(): if user == u.id: a.log_user_out(u.dirid, u.session_id) # logging of this procedure in function log_user_out return return log.info( "request to delete user %r (%r), usertype=%r, lastname=%r, firstname=%r" % (user.getName(), user.id, usertype, user.get('lastname'), user.get('firstname'))) for group in tree.getRoot("usergroups").getChildren(): for guser in group.getChildren(): if guser.getName() == user.getName(): group.removeChild(guser) log.info( "removed user %r (%r) from group %r (%r)" % (guser.getName(), guser.id, group.getName(), group.id)) if usertype != "intern": users = getExternalUserFolder(usertype) else: users = tree.getRoot("users") if users.id in [p.id for p in user.getParents()]: users.removeChild(user) log.info("removed user %r (%r) from node %r (%r)" % (user.getName(), user.id, users.name, users.id)) else: log.error( "could not remove user %r (%r) from node %r (%r): no such parent for this node" % (user.getName(), user.id, users.name, users.id)) home_root = tree.getRoot("home") home_dir_found = False for c in home_root.getChildren(): try: if c and c.getAccess("read").find( "{user " + user.getName() + "}") >= 0 and c.getAccess( "write").find("{user " + user.getName() + "}") >= 0: home_root.removeChild(c) home_dir_found = True log.info("removed home directory %r (%r) from %r (%r)" % (c.name, c.id, home_root.name, home_root.id)) break except: pass if not home_dir_found: log.info("no home directory found for user %r (%r)" % (user.getName(), user.id))
def init_db_compat(): """only for compatibility with older databases""" if config.get("database.compat_mode", "").lower() == "true": from contenttypes.directory import Directory # make all subnodes of collections collections for n in tree.getRoot("collections").getChildren(): if "directory" in n.type: n.setContentType("collection") n.setSchema(None) if not tree.getRoot().hasChild("searchmasks"): tree.getRoot().addChild(tree.Node(name="searchmasks", type="searchmasks"))
def init_db_compat(): """only for compatibility with older databases""" if config.get("database.compat_mode", "").lower() == "true": from contenttypes.directory import Directory # make all subnodes of collections collections for n in tree.getRoot("collections").getChildren(): if "directory" in n.type: n.setContentType("collection") n.setSchema(None) if not tree.getRoot().hasChild("searchmasks"): tree.getRoot().addChild( tree.Node(name="searchmasks", type="searchmasks"))
def filter_old(self, nodelist, accesstype="read"): if self.user.isAdmin(): return nodelist # optimized version of # newlist = [];for node in nodelist: if self.hasReadAccess(node): newlist += [node] newlist = [] lastparent = None if type == "read": lastaccess = self.hasReadAccess(tree.getRoot()) elif type == "write": lastaccess = self.hasWriteAccess(tree.getRoot()) for node in nodelist: newnode = node if isinstance(node, type("")): # id try: node = tree.getNode(node) except tree.NoSuchNodeError: continue newnode = node.id #rights = node.getAccess("read") rights = node.getAccess(accesstype) if rights: if not self._checkRights(rights, node): continue else: newlist += [newnode] continue p = node.getParents() if p != lastparent: access = 0 for p in node.getParents(): if accesstype == "read" and self.hasReadAccess(p, node): access = 1 break elif accesstype == "write" and self.hasWriteAccess(p, node): access = 1 break lastaccess = access else: access = lastaccess lastparent = p if access: newlist += [newnode] #logb.info("Filtering "+str(len(nodelist))+" nodes for read-access: "+str(len(newlist))+" nodes") logb.info("Filtering " + str(len(nodelist)) + " nodes for " + accesstype + "-access: " + str(len(newlist)) + " nodes") return newlist
def ensureSchedulesRoot(): try: schedules = tree.getRoot('schedules') msg = "scheduler: root node 'schedules' (id=%s) found" % str( schedules.id) OUT(msg) except tree.NoSuchNodeError as e: schedules = tree.Node(name='schedules', type='schedules') root = tree.getRoot() root.addChild(schedules) msg = "scheduler: created root node 'schedules' (id=%s)" % str( schedules.id) OUT(msg)
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 getPaths(node, access): list = [] def r(node, path): if node is tree.getRoot(): return for p in node.getParents(): path.append(p) if p is not tree.getRoot("collections"): r(p, path) return path paths = [] p = r(node, []) omit = 0 if p: for node in p: if access.hasReadAccess(node): if node.type in ("directory", "home", "collection" ) or node.type.startswith("directory"): paths.append(node) if node is tree.getRoot("collections") or node.type == "root": paths.reverse() if len(paths) > 0 and not omit: list.append(paths) omit = 0 paths = [] else: omit = 1 if len(list) > 0: return list else: return []
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 getPaths(node, access): list = [] def r(node, path): if node is tree.getRoot(): return for p in node.getParents(): path.append(p) if p is not tree.getRoot("collections"): r(p, path) return path paths = [] p = r(node, []) omit = 0 if p: for node in p: if access.hasReadAccess(node): if node.type in ("directory", "home", "collection") or node.type.startswith("directory"): paths.append(node) if node is tree.getRoot("collections") or node.type == "root": paths.reverse() if len(paths) > 0 and not omit: list.append(paths) omit = 0 paths = [] else: omit = 1 if len(list) > 0: return list else: return []
def deleteSchedule(schedule_id, access=None): errors = [] if schedule_id: try: schedule = tree.getNode(schedule_id) if access and not access.hasWriteAccess(schedule): errors.append("edit_schedule_no_write_access_to_schedule") except: errors.append("edit_schedule_unexpected_no_such_schedule_node") else: errors.append("edit_schedule_unexpected_no_such_schedule_node") if schedule.type not in ['schedule']: errors.append("edit_schedule_unexpected_no_such_schedule_node") if errors: return errors schedule_locked = schedule.get('system.lock') if schedule_locked.lower() in ['true', '1']: errors.append("edit_schedule_locked_schedule") try: schedules_root = tree.getRoot("schedules") schedules_root.removeChild(schedule) except: errors.append("edit_schedule_error_removing_schedule_node") return errors
def _makeMetadataNumbers(): print "Making Metadatafield-Index" import schema.schema as schema m = schema.loadTypesFromDB() for metatype in m: for field in metatype.getMetaFields(): if field.getFieldtype() in ["list", "mlist"] and field.Searchfield(): # print metatype.getName(),"->",field.getName() nstr = "" for v in field.getValueList(): v = UTF8ToLatin(v) num = 0 for collection in tree.getRoot("collections").getChildren(): if collection.type == "collection": try: query = "%s=%s and schema=%s" % (field.getName(), v, metatype.getName()) n = len(collection.search(query)) except: n = 0 num += n # print "\t", collection.name, field.getName(), v,"->",n if len(nstr): nstr += ";" nstr += str(num) field.setFieldValueNum(nstr)
def updateRule(rule, oldrule="", newname="", oldname=""): """ rule is the new rule oldrule is the name of the old and previous rule""" if oldrule == "": oldrule = rule else: oldrule = getRule(oldrule) conn.updateRule(rule, oldrule.getName()) rules[oldrule.getName()] = rule rules[rule.getName()] = rule if (oldrule.getName() != rule.getName()): for n in tree.getRoot().getAllChildren(): n.overwriteAccess(rule, oldrule) if (newname != oldname and newname != ""): tempoldname = " " + oldname + " " tempnewname = " " + newname + " " for aclrule in getRuleList(): if (tempoldname in aclrule.getRuleStr()): newrulestr = aclrule.getRuleStr().replace(tempoldname, tempnewname) newrule = AccessRule(aclrule.getName(), newrulestr, aclrule.getDescription()) conn.updateRule(newrule, newrule.getName()) rules[aclrule.getName()] = newrule
def getMask(node): root = tree.getRoot("searchmasks") maskname = node.get("searchmaskname") if not maskname or not root.hasChild(maskname): return newMask(node) else: return root.getChild(maskname)
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 sendmailUser_mask(req, id, err=0): v = getAdminStdVars(req) v["path"] = req.path[1:] if id in["execute", "execu"]: userid = req.params.get("userid") user = getUser(userid) if not user: path = req.path[1:].split("/") user = getExternalUser(userid, path[-1]) password = makeRandomPassword() user.resetPassword(password) text = req.params.get("text") text = text.replace("[wird eingesetzt]", password) try: mail.sendmail(req.params.get("from"), req.params.get("email"), req.params.get("subject"), text) except mail.SocketError: print "Socket error while sending mail" req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR) return req.getTAL("web/admin/modules/user.html", v, macro="sendmailerror") return req.getTAL("web/admin/modules/user.html", v, macro="sendmaildone") user = getUser(id) if not user: path = req.path[1:].split("/") user = getExternalUser(id, path[-1]) collections = [] seen = {} access = acl.AccessData(user=user) for node in getAllCollections(): if access.hasReadAccess(node): if access.hasWriteAccess(node): collections.append(node.name + " (lesen/schreiben)") seen[node.id] = None for node in tree.getRoot("collections").getChildren(): if access.hasReadAccess(node) and node.id not in seen: collections.append(node.name + " (nur lesen)") x = {} x["name"] = "%s %s" % (user.getFirstName(), user.getLastName()) if(x["name"] == ""): x["name"] = user.getName() x["host"] = config.get("host.name") x["login"] = user.getName() x["isEditor"] = user.isEditor() x["collections"] = list() x["groups"] = user.getGroups() x["groups"].sort() x["language"] = lang(req) x["collections"] = collections x["collections"].sort() v["mailtext"] = req.getTAL("web/admin/modules/user.html", x, macro="emailtext").strip() v["email"] = user.getEmail() v["userid"] = user.getName() return req.getTAL("web/admin/modules/user.html", v, macro="sendmail")
def getExternalUserFolder(type=""): try: extusers = tree.getRoot("external_users") except tree.NoSuchNodeError: extusers = tree.Node("external_users", "users") tree.getRoot().addChild(extusers) if type != "": try: users = extusers.getChild(type) except tree.NoSuchNodeError: users = tree.Node(type, "directory") extusers.addChild(users) return users else: return extusers
def getMask(node): root = tree.getRoot("searchmasks") maskname = node.get("searchmaskname") if not maskname or not root.hasChild(maskname): return newMask(node) else: return root.getChild(maskname)
def getBrowsingPathList(node): list = [] def r(node, path): if node is tree.getRoot(): return for p in node.getParents(): path.append(p) if p is not tree.getRoot("collections"): r(p, path) return path paths = [] p = r(node, []) omit = 0 if p: for node in p: if True: if node.type in ("directory", "home", "collection"): paths.append(node) if node is tree.getRoot("collections") or node.type == "root": paths.reverse() if len(paths) > 1 and not omit: list.append(paths) omit = 0 paths = [] else: omit = 1 if len(list) > 0: return list else: return []
def Identify(req): if not checkParams(req, ["verb"]): return writeError(req, "badArgument") if config.get("config.oaibasename") == "": root = tree.getRoot() name = root.getName() else: name = config.get("config.oaibasename") req.write(""" <Identify> <repositoryName>%s</repositoryName> <baseURL>%s</baseURL> <protocolVersion>2.0</protocolVersion> <adminEmail>%s</adminEmail> <earliestDatestamp>%s-01-01T12:00:00Z</earliestDatestamp> <deletedRecord>no</deletedRecord> <granularity>YYYY-MM-DDThh:mm:ssZ</granularity> <description> <oai-identifier xmlns="http://www.openarchives.org/OAI/2.0/oai-identifier" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai-identifier http://www.openarchives.org/OAI/2.0/oai-identifier.xsd"> <scheme>oai</scheme> <repositoryIdentifier>%s</repositoryIdentifier> <delimiter>:</delimiter> <sampleIdentifier>%s</sampleIdentifier> </oai-identifier> </description> </Identify>""" % (name, mklink(req), config.get("email.admin"), str(EARLIEST_YEAR - 1), config.get("host.name", socket.gethostname()), SAMPLE_IDENTIFIER)) if DEBUG: timetable_update(req, "leaving Identify")
def genmasks(masktype): if masktype not in ["nodebig", "nodesmall", "editmask"]: print "Unknown mask type %s" % masktype return for metatype in tree.getRoot( "metadatatypes").getChildren().sort_by_orderpos(): metadatatypes.generateMask(metatype, masktype, 0)
def getGroups(self): return [ g.name for g in tree.getRoot('usergroups').getChildren() if g.get('allow_dynamic') == '1' and params.get('user') in g.get('dynamic_users') ]
def getLabelForAttributename(mdt_name, attr_name, maskname_list): res = attr_name try: mdt = tree.getRoot('metadatatypes').getChild(mdt_name) field = [x for x in getFieldsForMeta(mdt_name) if x.name == attr_name][0] masks = [] for maskname in maskname_list: mask = mdt.getChild(maskname) if mask.type == 'mask': masks.append(mask) set_maskitems_for_field = set( [x for x in field.getParents() if x.type == 'maskitem']) for mask in masks: maskitems = list( set_maskitems_for_field.intersection(set(mask.getChildren()))) if maskitems: return maskitems[0].name except: pass return res
def _makeMetadataNumbers(): print "Making Metadatafield-Index" import schema.schema as schema m = schema.loadTypesFromDB() for metatype in m: for field in metatype.getMetaFields(): if field.getFieldtype() in ["list", "mlist" ] and field.Searchfield(): # print metatype.getName(),"->",field.getName() nstr = "" for v in field.getValueList(): v = UTF8ToLatin(v) num = 0 for collection in tree.getRoot( "collections").getChildren(): if collection.type == "collection": try: query = "%s=%s and schema=%s" % ( field.getName(), v, metatype.getName()) n = len(collection.search(query)) except: n = 0 num += n # print "\t", collection.name, field.getName(), v,"->",n if len(nstr): nstr += ";" nstr += str(num) field.setFieldValueNum(nstr)
def getExternalUserFolder(type=""): try: extusers = tree.getRoot("external_users") except tree.NoSuchNodeError: extusers = tree.Node("external_users", "users") tree.getRoot().addChild(extusers) if type != "": try: users = extusers.getChild(type) except tree.NoSuchNodeError: users = tree.Node(type, "directory") extusers.addChild(users) return users else: return extusers
def updateMapping(name, namespace="", namespaceurl="", description="", header="", footer="", separator="", standardformat="", id=0, mappingtype="", active=""): if id != "" and int(id) > 0: mapping = tree.getNode(id) else: mappings = tree.getRoot("mappings") mapping = tree.Node(name=name, type="mapping") mappings.addChild(mapping) mapping.setName(name) mapping.setDescription(description) mapping.setNamespace(namespace) mapping.setNamespaceUrl(namespaceurl) mapping.setHeader(header) mapping.setFooter(footer) mapping.setSeparator(separator) mapping.setStandardFormat(standardformat) mapping.setMappingType(mappingtype) mapping.setActive(active)
def existsHomeDir(user): username = user.getName() userdir = None for c in tree.getRoot("home").getChildren(): if (c.getAccess("read") or "").find("{user " + username + "}") >= 0 and (c.getAccess("write") or "").find("{user " + username + "}") >= 0: userdir = c return (userdir is not None)
def create_user(name, email, groups, pwd="", lastname="", firstname="", telephone="", comment="", option="", organisation="", identificator="", type="intern"): if not pwd: pwd = config.get("user.passwd") if (type == "intern"): users = tree.getRoot("users") else: users = getExternalUserFolder(type) user = tree.Node(name=name, type="user") user.set("email", email) user.set("password", hashlib.md5(pwd).hexdigest()) user.set("opts", option) user.set("lastname", lastname) user.set("firstname", firstname) user.set("telephone", telephone) user.set("comment", comment) user.set("organisation", organisation) if identificator != "": user.set("identificator", identificator) for group in groups.split(","): g = usergroups.getGroup(group) g.addChild(user) users.addChild(user) return user
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 Identify(req): if not checkParams(req, ["verb"]): return writeError(req, "badArgument") if config.get("config.oaibasename") == "": root = tree.getRoot() name = root.getName() else: name = config.get("config.oaibasename") req.write( """ <Identify> <repositoryName>%s</repositoryName> <baseURL>%s</baseURL> <protocolVersion>2.0</protocolVersion> <adminEmail>%s</adminEmail> <earliestDatestamp>%s-01-01T12:00:00Z</earliestDatestamp> <deletedRecord>no</deletedRecord> <granularity>YYYY-MM-DDThh:mm:ssZ</granularity> <description> <oai-identifier xmlns="http://www.openarchives.org/OAI/2.0/oai-identifier" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai-identifier http://www.openarchives.org/OAI/2.0/oai-identifier.xsd"> <scheme>oai</scheme> <repositoryIdentifier>%s</repositoryIdentifier> <delimiter>:</delimiter> <sampleIdentifier>%s</sampleIdentifier> </oai-identifier> </description> </Identify>""" % (name, mklink(req), config.get("email.admin"), str(EARLIEST_YEAR - 1), config.get("host.name", socket.gethostname()), SAMPLE_IDENTIFIER)) if DEBUG: timetable_update(req, "leaving Identify")
def moveUserToIntern(id): user = getUser(id) for p in user.getParents(): if p.type == "users" and p.getName() == "external_users": p.removeChild(user) users = tree.getRoot("users") users.addChild(user)
def moveUserToIntern(id): user = getUser(id) for p in user.getParents(): if p.type == "users" and p.getName() == "external_users": p.removeChild(user) users = tree.getRoot("users") users.addChild(user)
def update_user(id, name, email, groups, lastname="", firstname="", telephone="", comment="", option="", organisation="", identificator="", type="intern"): try: # internal user user = getUser(id) except: # external user user = getExternalUser(id) if user: for p in user.getParents(): if p.type != "usergroup": p.removeChild(user) if type == "intern": tree.getRoot("users").addChild(user) else: getExternalUserFolder(type).addChild(user) if user.getName() != name: # username changed -> update home directory hd = getHomeDir(user) hd.setAccess("read", "{user %s}" % (user.getName())) hd.setAccess("write", "{user %s}" % (user.getName())) if user: user.setName(name) user.setEmail(email) user.setLastName(lastname) user.setFirstName(firstname) user.setTelephone(telephone) user.setComment(comment) user.setOption(option) user.setOrganisation(organisation) if identificator != "": user.set('identificator', identificator) # remove user from all groups for p in user.getParents(): if p.type == "usergroup": p.removeChild(user) # add user to the "new" groups for group in groups.split(","): g = usergroups.getGroup(group) g.addChild(user) else: print "user not found" return user
def getOAIExportFormatsForSchema(schema_name): try: schema_node = [x for x in tree.getRoot('metadatatypes').getChildren() if x.name == schema_name][0] res = [x.name for x in schema_node.getChildren() if (x.type == 'mask' and x.get('masktype') == 'export')] return [x.replace('oai_', '', 1) for x in res if x.startswith('oai_')] except: OUT("ERROR in getOAIExportMasksForSchema('%s'):\n%s %s" % (schema_name, str(sys.exc_info()[0]), str(sys.exc_info()[1])), 'error') return []
def checkmasks(): for metatype in tree.getRoot( "metadatatypes").getChildren().sort_by_orderpos(): for mask in metatype.getMasks(): errornum = metadatatypes.checkMask(mask, fix=0, verbose=0) if errornum: print "Mask %s/%s %s %s has %s errors" % ( metatype.name, mask.name, mask.name, mask.id, errornum)
def simple_search(req): from web.frontend.content import ContentList res = [] words = [] collections = [] collection_ids = {} access = AccessData(req) q = u(req.params.get("query", "")) # test whether this query is restricted to a number of collections for key, value in req.params.items(): if key.startswith("c_"): collection_ids[key[2:]] = 1 # no collection means: all collections if len(collection_ids) == 0 or 1 in collection_ids.keys(): for collection in access.filter(tree.getRoot("collections").getChildren()): collection_ids[collection.id] = 1 # now retrieve all results in all collections for collection in getAllCollections(): if collection.id in collection_ids: collections.append(collection) num = 0 logging.getLogger('usertracing').info(access.user.name + " search for '" + q + "', " + str(num) + " results") try: if req.params.get("act_node", None) and tree.getNode(req.params.get("act_node")).getContentType() != "collections": # actual node is a collection or directory result = tree.getNode(req.params.get("act_node")).search('full=' + q) result = access.filter(result) num += len(result) if len(result) > 0: cl = ContentList(result, collection, words) cl.feedback(req) cl.linkname = "Suchergebnis" cl.linktarget = "" res.append(cl) else: # actual node is collections-node for collection in collections: result = collection.search('full=' + q) result = access.filter(result) num += len(result) if len(result) > 0: cl = ContentList(result, collection, words) cl.feedback(req) cl.linkname = "Suchergebnis" cl.linktarget = "" res.append(cl) if len(res) == 1: return res[0] else: return SearchResult(res, q, collections) except: return SearchResult(None, q, collections)
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 __init__(self): Portlet.__init__(self) self.name = "collectionlet" self.collection = tree.getRoot("collections") self.directory = self.collection self.folded = 0 self.col_data = None self.hassubdir = 0 self.hide_empty = False