def migrate_special_dirs(): """Special dirs are found by special system attribute used_as, not the directory name as before. """ home_root = q(Home).one() for home_dir in home_root.children: logg.info("fixing special dirs in home dir %s (%s)", home_dir.name, home_dir.id) lang = getDefaultLanguage() special_dirs = [(translate(u"user_trash", lang), u"trash"), (translate(u"user_upload", lang), u"upload")] for old, new in special_dirs: new_dir = home_dir.children.filter_by(name=new).scalar() if not new_dir: old_dirrs = home_dir.children.filter_by(name=old).order_by( Node.id).all() if not old_dirrs: logg.info("creating missing special dir %s", new) dirr = Directory(new) home_dir.children.append(dirr) else: if len(old_dirrs) > 1: logg.warn( "%s special dirs found for %s, using oldest dir", len(old_dirrs), home_dir.name) dirr = old_dirrs[0] dirr.name = new dirr.system_attrs[u"used_as"] = new
def makeList(req, name, rights, readonlyrights, overload=0, type=""): rightsmap = {} rorightsmap = {} for r in rights: rightsmap[r] = None rulelist = acl.getRuleList() val_left = "" val_right = "" if not (len(rightsmap) > 0 and overload): # inherited standard rules for rule in rulelist: if rule.getName() in readonlyrights: if rule.getDescription().startswith("{"): val_left += """<optgroup label="%s"></optgroup>""" % ( translate("edit_acl_special_rule", lang(req))) else: val_left += """<optgroup label="%s"></optgroup>""" % ( rule.getDescription()) rorightsmap[rule.getName()] = 1 # inherited implicit rules for rule in readonlyrights: if rule not in rorightsmap: if rule.startswith("{"): val_left += """<optgroup label="%s"></optgroup>""" % ( translate("edit_acl_special_rule", lang(req))) else: val_left += """<optgroup label="%s"></optgroup>""" % (rule) # node-level standard rules for rule in rulelist: if rule.getName() in rightsmap: val_left += """<option value="%s">%s</option>""" % ( rule.getName(), rule.getDescription()) rightsmap[rule.getName()] = 1 # node-level implicit rules for r in rightsmap.keys(): if not rightsmap[r] and r not in rorightsmap: if r.startswith( "{"): # special rights not changeable in normal ACL area val_left += """<option value="%s">%s</option>""" % ( r, translate("edit_acl_special_rule", lang(req))) else: val_left += """<option value="%s">%s</option>""" % (r, r) for rule in rulelist: if rule.getName() not in rightsmap and rule.getName( ) not in rorightsmap: val_right += """<option value="%s">%s</option>""" % ( rule.getName(), rule.getDescription()) return { "name": name, "val_left": val_left, "val_right": val_right, "type": type }
def migrate_special_dirs(): """Special dirs are found by special system attribute used_as, not the directory name as before. """ home_root = q(Home).one() for home_dir in home_root.children: logg.info("fixing special dirs in home dir %s (%s)", home_dir.name, home_dir.id) lang = getDefaultLanguage() special_dirs = [ (translate(u"user_trash", lang), u"trash"), (translate(u"user_upload", lang), u"upload") ] for old, new in special_dirs: new_dir = home_dir.children.filter_by(name=new).scalar() if not new_dir: old_dirrs = home_dir.children.filter_by(name=old).order_by(Node.id).all() if not old_dirrs: logg.info("creating missing special dir %s", new) dirr = Directory(new) home_dir.children.append(dirr) else: if len(old_dirrs) > 1: logg.warn("%s special dirs found for %s, using oldest dir", len(old_dirrs), home_dir.name) dirr = old_dirrs[0] dirr.name = new dirr.system_attrs[u"used_as"] = new
def getDatatypes(_req, _schemes): _dtypes = [] datatypes = Data.get_all_datatypes() for scheme in _schemes: for dtype in scheme.getDatatypes(): if dtype not in _dtypes: for _t in datatypes: # if _t.getName() == dtype and not elemInList(dtypes, _t.getName()): dtypes.append(_t) _dtypes.sort(lambda x, y: cmp( translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower())) return _dtypes
def getDatatypes(req, schemes): dtypes = [] datatypes = loadAllDatatypes() for scheme in schemes: for dtype in scheme.getDatatypes(): if dtype not in dtypes: for t in datatypes: if t.getName() == dtype and not elemInList(dtypes, t.getName()): dtypes.append(t) dtypes.sort(lambda x, y: cmp(translate(x.getLongName(), request=req).lower( ), translate(y.getLongName(), request=req).lower())) return dtypes
def getDatatypes(req, schemes): dtypes = [] datatypes = Data.get_all_datatypes() for scheme in schemes: for dtype in scheme.getDatatypes(): if dtype not in dtypes: for t in datatypes: if t.__name__.lower() == dtype and not elemInList(dtypes, t.__name__.lower()): dtypes.append(t) dtypes.sort(lambda x, y: cmp(translate(x.__name__.lower(), request=req).lower(), translate(y.__name__.lower(), request=req).lower())) return dtypes
def getDatatypes(req, schemes): dtypes = [] datatypes = Data.get_all_datatypes() for scheme in schemes: for dtype in scheme.getDatatypes(): if dtype not in dtypes: for t in datatypes: if t.__name__.lower() == dtype and not elemInList( dtypes, t.__name__.lower()): dtypes.append(t) dtypes.sort(lambda x, y: cmp( translate(x.__name__.lower(), request=req).lower(), translate(y.__name__.lower(), request=req).lower())) return dtypes
def makeList(req, name, rights, readonlyrights, overload=0, type=""): rightsmap = {} rorightsmap = {} for r in rights: rightsmap[r] = None # ignore private rulesets starting with _ rulelist = q(AccessRuleset).filter(~AccessRuleset.name.like("\_%")).order_by(AccessRuleset.name).all() val_left = "" val_right = "" if not (len(rightsmap) > 0 and overload): # inherited standard rules for rule in rulelist: if rule.name in readonlyrights: if rule.description.startswith("{"): val_left += """<optgroup label="%s"></optgroup>""" % (translate("edit_acl_special_rule", lang(req))) else: val_left += """<optgroup label="%s"></optgroup>""" % rule.description rorightsmap[rule.name] = 1 # inherited implicit rules for rule in readonlyrights: if rule not in rorightsmap: if rule.startswith("{"): val_left += """<optgroup label="%s"></optgroup>""" % (translate("edit_acl_special_rule", lang(req))) else: val_left += """<optgroup label="%s"></optgroup>""" % rule # node-level standard rules for rule in rulelist: if rule.name in rightsmap: val_left += """<option value="%s">%s</option>""" % (rule.name, rule.description) rightsmap[rule.name] = 1 # node-level implicit rules for r in rightsmap.keys(): if not rightsmap[r] and r not in rorightsmap: if r.startswith("{"): # special rights not changeable in normal ACL area val_left += """<option value="%s">%s</option>""" % (r, translate("edit_acl_special_rule", lang(req))) else: val_left += """<option value="%s">%s</option>""" % (r, r) for rule in rulelist: if rule.name not in rightsmap and rule.name not in rorightsmap: val_right += """<option value="%s">%s</option>""" % (rule.name, rule.description) return {"name": name, "val_left": val_left, "val_right": val_right, "type": type}
def getSpecialDir(user, type): nodename = "" if type == "upload": nodename = translate("user_upload", getDefaultLanguage()) elif type == "import": nodename = translate("user_import", getDefaultLanguage()) elif type == "faulty": nodename = translate("user_faulty", getDefaultLanguage()) elif type == "trash": nodename = translate("user_trash", getDefaultLanguage()) else: return None userdir = getHomeDir(user) for c in userdir.getChildren(): if c.name == nodename: return c # create new directory return userdir.addChild(tree.Node(name=nodename, type="directory"))
def getDatatypes(_req, _schemes): _dtypes = [] datatypes = Data.get_all_datatypes() for scheme in _schemes: for dtype in scheme.getDatatypes(): if dtype not in _dtypes: for _t in datatypes: # if _t.getName() == dtype and not elemInList(dtypes, _t.getName()): dtypes.append(_t) _dtypes.sort(lambda x, y: cmp(translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower())) return _dtypes
def makeUserList(req, name, rights, readonlyrights, overload=0, type=""): val_left = "" val_right = "" rulelist = acl.getRuleList() userlist = {} userlist['intern'] = users.loadUsersFromDB() for usertype in list(users.getExternalUsers()): userlist[usertype.getName()] = users.getExternalUsers(usertype.getName()) rightsmap = {} rorightsmap = {} for r in rights: for u in getRuleUsers(r, userlist): if translate(u[0], lang(req)) != "": rightsmap[translate(u[0], lang(req)) + ": " + u[1]] = None else: rightsmap[u[1]] = None rrights = [] for r in readonlyrights: if r[0] == "{": for part in getRuleUsers(r, userlist): rrights.append(translate(part[0], lang(req)) + ": " + part[1]) else: rrights.append(r) readonlyrights = rrights if not (len(rightsmap) > 0 and overload): # inherited standard rules for rule in rulelist: if rule.getName() in readonlyrights: val_left += """<optgroup label="%s"></optgroup>""" % (rule.getDescription()) rorightsmap[rule.getName()] = 1 # inherited implicit rules for rule in readonlyrights: if rule not in rorightsmap: val_left += """<optgroup label="%s"></optgroup>""" % (rule) # node-level implicit rules for r in rightsmap.keys(): if not rightsmap[r] and r not in rorightsmap: val_left += """<option value="%s">%s</option>""" % (r, r) for usertype in userlist.keys(): susers = list(userlist[usertype]) susers.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) for user in susers: if translate(usertype, lang(req)) + ": " + user.getName() not in rightsmap and user.getName() not in rorightsmap and translate( usertype, lang(req)) + ": " + user.getName() not in readonlyrights: val_right += """<option value="%s">%s</option>""" % ( translate(usertype, lang(req)) + ": " + user.getName(), translate(usertype, lang(req)) + ": " + user.getName()) return {"name": name, "val_left": val_left, "val_right": val_right, "type": type}
def makeList(req, own_ruleset_assocs, inherited_ruleset_assocs, special_ruleset, special_rule_assocs, rulesetnamelist, private_ruleset_names, rule_type=''): already_shown_left = {} # ruleset names in left handside lists will not be shown on the right side val_left = [] val_right = [] # inherited rulesets inherited_ruleset_names = [r.ruleset_name for r in inherited_ruleset_assocs] for rulesetname in inherited_ruleset_names: if rulesetname in private_ruleset_names: val_left.append( """<optgroup label="%s"></optgroup>""" % (translate("edit_acl_special_rule", lang(req)))) else: val_left.append("""<optgroup label="%s"></optgroup>""" % rulesetname) already_shown_left[rulesetname] = 1 # node level rulesets (not inherited) own_ruleset_names = [r.ruleset_name for r in own_ruleset_assocs] for rulesetname in own_ruleset_names: if rulesetname in private_ruleset_names: entry_text = translate("edit_acl_special_rule", lang(req)) val_left.append( """<option value="__special_rule__">%s</optgroup>""" % (entry_text, )) else: val_left.append("""<option value="%s">%s</option>""" % (rulesetname, rulesetname)) already_shown_left[rulesetname] = 1 for rulesetname in rulesetnamelist: if rulesetname not in already_shown_left: val_right.append("""<option value="%s">%s</option>""" % (rulesetname, rulesetname)) res = {"name": rule_type, "val_left": "".join(val_left), "val_right": "".join(val_right), "type": rule_type} return res
def getContent(req, ids): user = users.getUserFromRequest(req) if "ftp" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") ids = ids[0] # use only first selected node node = tree.getNode(ids) error = "" def processFile(node, file, ftype): nname = file.retrieveFile().split("/") nname = "/".join(nname[:-1]) + "/" + nname[-1][4:] try: os.rename(file.retrieveFile(), nname) except: nname = file.retrieveFile() fnode = tree.Node(nname.split("/")[-1], ftype) node.removeFile(file) file._path = file._path.replace(config.get("paths.datadir"), "") file._path = "/".join( file._path.split("/")[:-1]) + "/" + fnode.getName() fnode.addFile(file) fnode.event_files_changed() node.addChild(fnode) return fnode for key in req.params.keys(): if key.startswith("process|"): # process selected file (single) fname = key[:-2].split("|")[-1] ftype = req.params.get("schema").replace(";", "") if ftype != "": for f in node.getFiles(): if f.getName() == fname: processFile(node, f, ftype) break break else: error = "edit_ftp_error1" elif key.startswith("del|"): for f in node.getFiles(): if f.getName() == key[4:-2]: node.removeFile(f) break break elif key.startswith("delall"): # delete all selected files delfiles = [ f.split("|")[-1] for f in req.params.get("selfiles").split(";") ] for f in node.getFiles(): if f.getName() in delfiles: node.removeFile(f) break elif key.startswith("processall"): # process all selected files for file in req.params.get("selfiles", "").split(";"): if file: ftype, fname = file.split("|") if "multschema|" + ftype in req.params and req.params.get( "multschema|" + ftype) != "": for f in node.getFiles(): if f.getName() == fname: print "use", ftype + "/" + req.params.get( "multschema|" + ftype) processFile( node, f, ftype + "/" + req.params.get("multschema|" + ftype)) break else: error = "edit_ftp_error2" break break files = filter(lambda x: x.getName().startswith("ftp_"), node.getFiles()) types = [] for f in files: if f.getType() not in types: if f.getType() != "other": types.append(f.getType()) dtypes = {} for scheme in filter(lambda x: x.isActive(), acl.AccessData(req).filter(loadTypesFromDB())): for dtype in scheme.getDatatypes(): if dtype not in dtypes.keys(): dtypes[dtype] = [] if scheme not in dtypes[dtype]: dtypes[dtype].append(scheme) for t in dtypes: dtypes[t].sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) access = acl.AccessData(req) if not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") v = {} v['error'] = error v['files'] = files v['node'] = node v['schemes'] = dtypes # schemes v['usedtypes'] = types v['tab'] = req.params.get("tab", "") v['ids'] = ids v["script"] = "<script> parent.reloadTree('" + req.params.get( "id") + "');</script>" return req.getTAL("web/edit/modules/ftp.html", v, macro="edit_ftp")
def getContent(req, ids): user = current_user node = q(Node).get(ids[0]) if not node.has_write_access( ) or "changeschema" in current_user.hidden_edit_functions: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") # nobody should be able to change the type/schema of his home directory if node.id == user.home_dir_id: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") error = req.params.get("error") schemes = get_permitted_schemas() long_scheme_names = { scheme.name: scheme.getLongName() for scheme in schemes } if isinstance(node, Container): admissible_containers = [ s.__name__.lower() for s in Container.get_all_subclasses( filter_classnames=["container", "collections", "home", "root"]) ] else: admissible_content_types = [ s.__name__.lower() for s in Content.get_all_subclasses(filter_classnames=["content"]) ] # filter schemes for special datatypes if req.params.get("objtype", "") != "": new_type = req.params.get('objtype', '') new_schema = req.params.get('schema', '') if not new_schema: return _redirect_to_view(req) if new_type != node.type or new_schema != node.schema: if isinstance(node, Container): if not new_type in admissible_containers: logg.warn(u"changeschema: illegal container type %s", new_type) return httpstatus.HTTP_BAD_REQUEST else: if not new_type in admissible_content_types: logg.warn(u"changeschema: illegal content type %s", new_type) return httpstatus.HTTP_BAD_REQUEST available_schema_names = [ s.name for s in schemes if new_type in s.getDatatypes() ] if not new_schema in available_schema_names: logg.warn(u"changeschema: illegal schema %s", new_schema) return httpstatus.HTTP_BAD_REQUEST logg.info( u"{} changed node schema for node {} '{}' from '{}' to '{}'". format(user.login_name, node.id, node.name, node.type, new_type)) node.type = new_type node.schema = new_schema db.session.commit() return _redirect_to_view(req) elif "action" in req.params.keys(): available_schemes = [ s for s in schemes if node.type in s.getDatatypes() ] if req.params.get("action").startswith("get_schemes_for_"): new_type = req.params.get("action").replace( "get_schemes_for_", "").lower() available_schemes = [ s for s in schemes if new_type in s.getDatatypes() ] req.writeTAL("web/edit/modules/changeschema.html", { 'schemes': available_schemes, 'current_schema': node.schema }, macro="changeschema_selectscheme") return "" else: d = { 'id': req.params.get('id'), 'error': error, 'node': node, 'current_type': node.type, 'current_schema': node.schema, # XXX: this is the only line that uses getTypeAlias. What is the real meaning? 'type_alias': node.getTypeAlias(), 'is_container': int(node.isContainer()), 'nodes': [node] } d['long_current_schema'] = long_scheme_names.get(node.schema) available_schemes = [ s for s in schemes if node.type in s.getDatatypes() ] if isinstance(node, Container): admissible_containers.sort( key=lambda x: translate(x, request=req).lower()) d['schemes'] = available_schemes d['datatypes'] = admissible_containers else: admissible_content_types.sort( key=lambda x: translate(x, request=req).lower()) d['schemes'] = available_schemes d['datatypes'] = admissible_content_types d["csrf"] = req.csrf_token.current_token return req.getTAL("web/edit/modules/changeschema.html", d, macro="changeschema_popup")
def getMetaEditor(self, item, req): """ editor mask for field definition """ attr = {} fields = [] pidnode = None if "pid" not in req.params.keys(): for p in item.getParents(): try: if p.getMasktype() == "export": pidnode = p break except: continue metadatatype = req.params.get("metadatatype") for t in metadatatype.getDatatypes(): content_class = Node.get_class_for_typestring(t) node = content_class(name=u'') attr.update(node.getTechnAttributes()) if req.params.get("op", "") == "new": pidnode = q(Node).get(req.params.get("pid")) if hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() in ("vgroup", "hgroup"): # XXX: getAllChildren does not exist anymore, is this dead code? for field in pidnode.getAllChildren(): if field.getType().getName() == "maskitem" and field.id != pidnode.id: fields.append(field) else: for m in metadatatype.getMasks(): if ustr(m.id) == ustr(req.params.get("pid")): for field in m.getChildren(): fields.append(field) fields.sort(lambda x, y: cmp(x.getOrderPos(), y.getOrderPos())) add_values = [] val = u"" if item.getField(): val = item.getField().getValues() db.session.commit() for t in getMetaFieldTypeNames(): f = getMetadataType(t) add_values.append(f.getMaskEditorHTML(val, metadatatype=metadatatype, language=lang(req))) metafields = metadatatype.getMetaFields() metafields.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) metafieldtypes = getMetaFieldTypes().values() metafieldtypes.sort(lambda x, y: cmp(translate(x.getName(), request=req).lower(), translate(y.getName(), request=req).lower())) add_descriptions = [] for metafield in metafields: add_descriptions.append('<div style="display:none" id="div_%d" name="%s" description="%s"/>' % (metafield.id, metafield.name, metafield.getDescription())) v = {} v["op"] = req.params.get("op", "") v["pid"] = req.params.get("pid", "") v["item"] = item v["metafields"] = metafields v["fields"] = fields v["fieldtypes"] = metafieldtypes v["dateoption"] = dateoption v["t_attrs"] = attr v["icons"] = {"externer Link": "/img/extlink.png", "Email": "/img/email.png"} v["add_values"] = add_values v["add_descriptions"] = add_descriptions v["translate"] = translate v["language"] = lang(req) if pidnode and hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() == "export": v["mappings"] = [] for m in pidnode.getExportMapping(): v["mappings"].append(q(Node).get(m)) return req.getTAL("schema/mask/field.html", v, macro="metaeditor_" + pidnode.getMasktype()) else: return req.getTAL("schema/mask/field.html", v, macro="metaeditor")
def display_name(self): return translate("guest")
def extended_search(req): from web.frontend.content import ContentList max = 3 if req.params.get("searchmode") == "extendedsuper": max = 10 sfields = [] access = AccessData(req) metatype = None collectionid = req.params.get("collection", tree.getRoot().id) try: collection = tree.getNode(collectionid) except: for coll in tree.getRoot("collections").getChildren(): collection = tree.getNode(coll.id) break q_str = '' q_user = '' first2 = 1 for i in range(1, max + 1): f = u(req.params.get("field" + str(i), "").strip()) q = u(req.params.get("query" + str(i), "").strip()) if not q and "query" + str(i) + "-from" not in req.params: continue if not first2: q_str += " and " q_user += " %s " % (translate("search_and", request=req)) first2 = 0 if not f.isdigit(): q = u(req.params.get("query" + str(i), "").strip()) q_str += f + '=' + protect(q) q_user += f + '=' + protect(q) else: masknode = tree.getNode(f) assert masknode.type == "searchmaskitem" first = 1 q_str += "(" for metatype in masknode.getChildren(): if not first: q_str += " or " q_user += " %s " % (translate("search_or", request=req)) first = 0 if "query" + str( i) + "-from" in req.params and metatype.getFieldtype( ) == "date": date_from = "0000-00-00T00:00:00" date_to = "0000-00-00T00:00:00" fld = metatype if str(req.params["query" + str(i) + "-from"]) != "": date_from = date.format_date( date.parse_date( str(req.params["query" + str(i) + "-from"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S") if str(req.params["query" + str(i) + "-to"]) != "": date_to = date.format_date( date.parse_date( str(req.params["query" + str(i) + "-to"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S") if date_from == "0000-00-00T00:00:00" and date_to != date_from: # from value q_str += metatype.getName() + ' <= ' + date_to q_user += "%s ≤ \"%s\"" % ( metatype.getName(), str(req.params["query" + str(i) + "-to"])) elif date_to == "0000-00-00T00:00:00" and date_to != date_from: # to value q_str += metatype.getName() + ' >= ' + date_from q_user += "%s ≥ \"%s\"" % ( metatype.getName(), str(req.params["query" + str(i) + "-from"])) else: q_str += '({} >= {} and {} <= {})'.format( metatype.getName(), date_from, metatype.getName(), date_to) q_user += "(%s %s \"%s\" %s \"%s\")" % ( metatype.getName(), translate("search_between", request=req), str(req.params["query" + str(i) + "-from"]), translate("search_and", request=req), str(req.params["query" + str(i) + "-to"])) else: q = u(req.params.get("query" + str(i), "").strip()) q_str += metatype.getName() + '=' + protect(q) if metatype.getLabel() != "": q_user += "%s = %s" % (metatype.getLabel(), protect(q)) else: q_user += "%s = %s" % (metatype.getName(), protect(q)) q_str += ")" try: if req.params.get( "act_node", "") and req.params.get("act_node") != str(collection.id): result = tree.getNode(req.params.get("act_node")).search(q_str) else: result = collection.search(q_str) result = access.filter(result) logging.getLogger('usertracing').info(access.user.name + " xsearch for '" + q_user + "', " + str(len(result)) + " results") if len(result) > 0: cl = ContentList(result, collection, q_user.strip()) cl.feedback(req) cl.linkname = "" cl.linktarget = "" return cl return SearchResult([], q_user.strip()) except: return SearchResult(None, q_user.strip())
def makeUserList(req, own_ruleset_assocs, inherited_ruleset_assocs, special_ruleset, special_rule_assocs, rulesetnamelist, private_ruleset_names, rule_type=''): val_left = "" val_right = "" userlist = q(User).order_by(User.display_name).all() authenticator_id2user_prefix = {} for ai in q(AuthenticatorInfo).all(): authenticator_id2user_prefix[ai.id] = translate( u"%s:%s: " % (ai.auth_type, ai.name), lang(req)) user_not_inherited_in_left_list = [] own_ruleset_names = [r.ruleset_name for r in own_ruleset_assocs] for ruleset_name in own_ruleset_names: if ruleset_name in private_ruleset_names: ruleset = q(AccessRuleset).filter_by(name=ruleset_name).scalar() for rule_assoc in ruleset.rule_assocs: rule = rule_assoc.rule test_result = decider_is_private_user_group_access_rule(rule) if type(test_result) in [unicode, str]: if len(test_result) > 50: val_left += """<option value="" title="%s">%s</option>""" % ( test_result, test_result) else: val_left += """<option value="">%s</option>""" % ( test_result, ) elif type(test_result) == User: long_val = get_list_representation_for_user( test_result, prefix=authenticator_id2user_prefix[ test_result.authenticator_id]) if len(long_val) > 50: val_left += """<option value="%s" title="%s">%s</option>""" % ( test_result.id, long_val, long_val) else: val_left += """<option value="%s">%s</option>""" % ( test_result.id, long_val, ) user_not_inherited_in_left_list.append(test_result.id) else: param_value = 'rule_id:%r' % rule.id text_content = "rule: %r" % rule.to_dict() val_left += """<option value="%s" title="%s">%s</option>""" % ( param_value, text_content, text_content) else: if len(ruleset_name) > 50: val_left += """<option value="" title="%s">%s</option>""" % ( ruleset_name, ruleset_name) else: val_left += """<option>%s</option>""" % (ruleset_name, ) inherited_ruleset_names = [ r.ruleset_name for r in inherited_ruleset_assocs ] for ruleset_name in inherited_ruleset_names: if ruleset_name in private_ruleset_names: ruleset = q(AccessRuleset).filter_by(name=ruleset_name).scalar() for rule_assoc in ruleset.rule_assocs: rule = rule_assoc.rule test_result = decider_is_private_user_group_access_rule(rule) if type(test_result) in [unicode, str]: if len(test_result) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % ( test_result, test_result) else: val_left += """<optgroup label="%s"></optgroup>""" % ( test_result, ) elif type(test_result) == User: long_val = get_list_representation_for_user( test_result, prefix=authenticator_id2user_prefix[ test_result.authenticator_id]) if len(long_val) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % ( long_val, long_val) else: val_left += """<optgroup label="%s"></optgroup>""" % ( long_val, ) else: param_value = 'rule_id:%r' % rule.id text_content = "rule: %r" % rule.to_dict() val_left += """<option value="%s" title="%s">%s</option>""" % ( param_value, text_content, text_content) else: if len(ruleset_name) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % ( ruleset_name, ruleset_name) else: val_left += """<optgroup label="%s"></optgroup>""" % ( ruleset_name, ) sorted_decorated_userlist = sorted([ (authenticator_id2user_prefix[u.authenticator_id], u.getName().lower(), u) for u in userlist ]) for u_prefix, u_name, u in sorted_decorated_userlist: if u.id in user_not_inherited_in_left_list: continue long_val = get_list_representation_for_user(u, prefix=u_prefix) if len(long_val) > 50: val_right += """<option value="%s" title="%s">%s</option>""" % ( u.id, long_val, long_val) else: val_right += """<option value="%s">%s</option>""" % (u.id, long_val) return { "name": rule_type, "val_left": val_left, "val_right": val_right, "type": rule_type }
def translate(self, key): return translation.translate(key=key, user=self)
def getMetaHTML(self, parent, index, sub=False, language=None, itemlist=[], ptype="", fieldlist={}): """ return formated row for metaeditor """ if len(itemlist) > 0: # parent still not existing item = getNode(itemlist[index]) pitems = len(itemlist) else: item = parent.getChildren().sort_by_orderpos()[index] ptype = parent.get("type") pitems = len(parent.getChildren()) field = item.getField() ret = '' label = '' description = '' if field: f = getMetadataType(field.get("type")) fieldstring = f.getEditorHTML( field, width=item.getWidth(), value=item.getDefault(), language=language) + ' ' + item.getUnit() else: # node for export mask attribute = tree.getNode(item.get("attribute")) field = item fieldstring = getMetadataType("mappingfield").getEditorHTML( field, width=item.getWidth(), value=attribute.getName(), language=language) + ' ' + item.getUnit() if item.getDescription() != "": description = '<div id="div_description"><a href="#" onclick="openPopup(\'/popup_help?id=%s&maskid=%s\', \'\', 400, 250)"> <img src="/img/tooltip.png" border="0"/></a></div>' % ( field.id, item.id) if len(item.getLabel()) > 0 and item.getLabel() != "mapping": label = item.getLabel() + ': ' required = "" if item.getRequired(): required = '<span class="required">*</span>' if ptype in ("vgroup", "hgroup") or not sub: label = '<div class="label">%s %s</div>%s' % (label, required, description) else: label += required else: label = '<div class="label"> </div>' if not sub: ret += '<div id="%s" class="row" onmouseover="pick(this)" onmouseout="unpick(this)" onclick="select(this)" style="position:relative;min-height:30px">' % ( item.id) if len(label) > 0: ret += '%s<div id="editor_content">%s</div>' % (label, fieldstring) else: ret += fieldstring if not sub: # <small style="color:silver">('+(item.get("type"))+')</small>' ret += '<div align="right" id="%s_sub" style="display:none; position:absolute; right:1px; top:3px" class="edit_tools">' % ( item.id) if index > 0: ret += '<input type="image" src="/img/uparrow.png" name="up_%s" i18n:attributes="title mask_edit_up_title"/>' % ( item.id) else: ret += ' ' if index < pitems - 1: ret += '<input type="image" src="/img/downarrow.png" name="down_%s" i18n:attributes="title mask_edit_down_title"/>' % ( item.id) else: ret += ' ' if field.getName() in fieldlist.keys(): if len(fieldlist[field.getName()]) > 1: ret += ' <img src="/img/attention.gif" title="%s ' % ( translate("mask_edit_multi_label", language)) ret += ", ".join([ schema.getName() for schema in fieldlist[field.getName()] ]) + '"/>' ret += ' <input type="image" src="/img/edit.png" name="edit_%s" i18n:attributes="title mask_edit_edit_row"/> <input type="image" src="/img/delete.png" name="delete_%s" i18n:attributes="title mask_edit_delete_row" onClick="return questionDel()"/></div></div>' % ( item.id, item.id) return ret
# add new object, only metadata if req.params.get('action') == "addmeta": ret = [] schemes = get_permitted_schemas() dtypes = getDatatypes(req, schemes) dtypenames = {t.__name__.lower(): t.__name__ for t in dtypes} for scheme in get_permitted_schemas(): datatypes = scheme.getDatatypes() for datatype in datatypes: if datatype in dtypenames.keys(): ret.append({ 'id': scheme.name, 'name': scheme.getLongName() + ' / ' + translate(dtypenames[datatype], request=req), 'description': scheme.getDescription(), 'datatype': datatype }) if len(dtypes) == 1: # load schemes for type schemes = get_permitted_schemas_for_datatype( dtypes[0].__name__.lower()) content = req.getTAL('web/edit/modules/upload.html', { "datatypes": dtypes, "schemes": ret, "language": lang(req) }, macro="addmeta")
def getContent(req, ids): user = users.getUserFromRequest(req) language = lang(req) def get_ids_from_query(): ids = get_ids_from_req(req) return ",".join(ids) if "action" in req.params: state = 'ok' if req.params.get('action') == "removefiles": basenode = q(Node).get(req.params.get('id')) for f in basenode.files: try: os.remove(f.abspath) pass except: state = "error" basenode.files = [] db.session.commit() req.write(json.dumps({'state': state}, ensure_ascii=False)) return None if req.params.get('action') == "buildnode": # create nodes basenode = q(Node).get(req.params.get('id')) newnodes = [] errornodes = [] basenodefiles_processed = [] if req.params.get('uploader', '') == 'plupload': filename2scheme = {} for k in req.params: if k.startswith("scheme_"): filename2scheme[k.replace('scheme_', '', 1)] = req.params.get(k) for f in basenode.files: filename = f.name if filename in filename2scheme: mimetype = getMimeType(filename) if mimetype[1] == "bibtex": # bibtex import handler try: new_node = importBibTeX(f.abspath, basenode, req=req) newnodes.append(new_node.id) basenodefiles_processed.append(f) except ValueError, e: errornodes.append((filename, translate(unicode(e), request=req), unicode(hash(f.getName())))) logg.debug("filename: %s, mimetype: %s", filename, mimetype) logg.debug("__name__=%s, func=%s; _m=%s, _m[1]=%s", __name__, funcname(), mimetype, mimetype[1]) content_class = Node.get_class_for_typestring( mimetype[1]) node = content_class(name=filename, schema=filename2scheme[filename]) basenode.children.append(node) node.set("creator", user.login_name) node.set( "creationtime", unicode( time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time())))) # set filetype for uploaded file as requested by the content class f.filetype = content_class.get_upload_filetype() node.files.append(f) node.event_files_changed() newnodes.append(node.id) basenodefiles_processed.append(f) basenode.files.remove(f) db.session.commit() logg.info( "%s created new node id=%s (name=%s, type=%s) by uploading file %s, " "node is child of base node id=%s (name=%s, type=%s)", user.login_name, node.id, node.name, node.type, filename, basenode.id, basenode.name, basenode.type) else: for filename in req.params.get('files').split('|'): mimetype = getMimeType(filename) logg.debug("... in %s.%s: getMimeType(filename=%s)=%s", __name__, funcname(), filename, mimetype) if mimetype[1] == req.params.get('type') or req.params.get( 'type') == 'file': for f in basenode.files: # ambiguity here ? if f.abspath.endswith(filename): # bibtex import handler if mimetype[ 1] == "bibtex" and not req.params.get( 'type') == 'file': try: new_node = importBibTeX(f.abspath, basenode, req=req) newnodes.append(new_node.id) basenodefiles_processed.append(f) except ValueError, e: errornodes.append( (filename, translate(unicode(e), request=req), unicode(hash(f.getName())))) db.session.commit() else: logg.debug( "creating new node: filename: %s", filename) logg.debug("files at basenode: %s", [(x.getName(), x.abspath) for x in basenode.files]) content_class = Node.get_class_for_typestring( req.params.get('type')) node = content_class( name=filename, schema=req.params.get('value')) basenode.children.append(node) node.set("creator", user.login_name) node.set( "creationtime", unicode( time.strftime( '%Y-%m-%dT%H:%M:%S', time.localtime(time.time())))) # clones to a file with random name cloned_file = importFileRandom(f.abspath) # set filetype for uploaded file as requested by the content class cloned_file.filetype = content_class.get_upload_filetype( ) node.files.append(cloned_file) try: node.event_files_changed() except Exception as e: errornodes.append( (filename, translate(unicode(e), request=req), unicode(hash(f.getName())))) db.session.rollback() continue newnodes.append(node.id) basenodefiles_processed.append(f) logg.info( "%s created new node id=%s (name=%s, type=%s) by uploading file %s, " "node is child of base node id=%s (name=%s, type=%s)", user.login_name, node.id, node.name, node.type, filename, basenode.id, basenode.name, basenode.type) break # filename may not be unique new_tree_labels = [{ 'id': basenode.id, 'label': getTreeLabel(basenode, lang=language) }] for f in basenodefiles_processed: basenode.files.remove(f) f_path = f.abspath if os.path.exists(f_path): logg.debug("%s going to remove file %s from disk", user.login_name, f_path) os.remove(f_path) mime = getMimeType(filename) scheme_type = {mime[1]: []} for scheme in get_permitted_schemas(): if mime[1] in scheme.getDatatypes(): scheme_type[mime[1]].append(scheme) # break db.session.commit() # standard file content = req.getTAL('web/edit/modules/upload.html', { 'files': [filename], 'schemes': scheme_type }, macro="uploadfileok") res = { 'state': state, 'newnodes': newnodes, 'errornodes': errornodes, 'new_tree_labels': new_tree_labels, 'ret': content } res = json.dumps(res, ensure_ascii=False) req.write(res) return None
def renameHomeDir(user, newusername): if (existsHomeDir(user)): getHomeDir(user).setName( translate("user_directory", getDefaultLanguage()) + " (" + newusername + ")")
def getContent(req, ids): class SortChoice: def __init__(self, label, value): self.label = label self.value = value def getSchemes(_req): return filter(lambda x: x.isActive(), acl.AccessData(_req).filter(loadTypesFromDB())) def getDatatypes(_req, _schemes): _dtypes = [] datatypes = loadAllDatatypes() for scheme in _schemes: for dtype in scheme.getDatatypes(): if dtype not in _dtypes: for _t in datatypes: if _t.getName() == dtype and not elemInList( dtypes, _t.getName()): dtypes.append(_t) _dtypes.sort(lambda x, y: cmp( translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower())) return _dtypes node = tree.getNode(ids[0]) if "action" in req.params: if req.params.get('action') == "resort": _dir = "up" field = req.params.get('value', '').strip() nl = list(node.getChildren()) if field: if field[0] == "-": field = field[1:] _dir = "down" nl.sort(lambda x, y: cmp( x.get(field).lower(), y.get(field).lower())) if _dir == "down": nl.reverse() req.write( json.dumps({ 'state': 'ok', 'values': showdir(req, node, nodes=nl, sortfield_from_req=field) })) return None elif req.params.get( 'action') == "save": # save selection for collection field = req.params.get('value') if field.strip() == "": node.removeAttribute('sortfield') else: node.set('sortfield', field) req.write( json.dumps({ 'state': 'ok', 'message': translate('edit_content_save_order', request=req) })) return None if node.isContainer(): schemes = [] dtypes = [] v = { "operations": showoperations(req, node), "items": showdir(req, node) } access = acl.AccessData(req) if access.hasWriteAccess(node): schemes = getSchemes(req) dtypes = getDatatypes(req, schemes) 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"]: try: 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 except TypeError: pass v['sortchoices'] = sortfields v['types'] = dtypes v['schemes'] = schemes v['id'] = ids[0] v['count'] = len(node.getContentChildren()) v['language'] = lang(req) v['t'] = t return req.getTAL("web/edit/modules/content.html", v, macro="edit_content") if hasattr(node, "editContentDefault"): return node.editContentDefault(req) return ""
def buildHomeDirName(username): """ make a string for naming the home directory in the browsing tree in the editor """ return translate("user_directory", getDefaultLanguage()) + " (" + username + ")"
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 makeUserList(req, own_ruleset_assocs, inherited_ruleset_assocs, special_ruleset, special_rule_assocs, rulesetnamelist, private_ruleset_names, rule_type=''): val_left = "" val_right = "" userlist = q(User).order_by(User.display_name).all() authenticator_id2user_prefix = {} for ai in q(AuthenticatorInfo).all(): authenticator_id2user_prefix[ai.id] = translate(u"%s:%s: " % (ai.auth_type, ai.name), lang(req)) user_not_inherited_in_left_list = [] own_ruleset_names = [r.ruleset_name for r in own_ruleset_assocs] for ruleset_name in own_ruleset_names: if ruleset_name in private_ruleset_names: ruleset = q(AccessRuleset).filter_by(name=ruleset_name).scalar() for rule_assoc in ruleset.rule_assocs: rule = rule_assoc.rule test_result = decider_is_private_user_group_access_rule(rule) if type(test_result) in [unicode, str]: if len(test_result) > 50: val_left += """<option value="" title="%s">%s</option>""" % (test_result, test_result) else: val_left += """<option value="">%s</option>""" % (test_result,) elif type(test_result) == User: long_val = get_list_representation_for_user(test_result, prefix=authenticator_id2user_prefix[test_result.authenticator_id]) if len(long_val) > 50: val_left += """<option value="%s" title="%s">%s</option>""" % (test_result.id, long_val, long_val) else: val_left += """<option value="%s">%s</option>""" % (test_result.id, long_val,) user_not_inherited_in_left_list.append(test_result.id) else: param_value = 'rule_id:%r' % rule.id text_content = "rule: %r" % rule.to_dict() val_left += """<option value="%s" title="%s">%s</option>""" % (param_value, text_content, text_content) else: if len(ruleset_name) > 50: val_left += """<option value="" title="%s">%s</option>""" % (ruleset_name, ruleset_name) else: val_left += """<option>%s</option>""" % (ruleset_name,) inherited_ruleset_names = [r.ruleset_name for r in inherited_ruleset_assocs] for ruleset_name in inherited_ruleset_names: if ruleset_name in private_ruleset_names: ruleset = q(AccessRuleset).filter_by(name=ruleset_name).scalar() for rule_assoc in ruleset.rule_assocs: rule = rule_assoc.rule test_result = decider_is_private_user_group_access_rule(rule) if type(test_result) in [unicode, str]: if len(test_result) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % (test_result, test_result) else: val_left += """<optgroup label="%s"></optgroup>""" % (test_result,) elif type(test_result) == User: long_val = get_list_representation_for_user(test_result, prefix=authenticator_id2user_prefix[test_result.authenticator_id]) if len(long_val) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % (long_val, long_val) else: val_left += """<optgroup label="%s"></optgroup>""" % (long_val, ) else: param_value = 'rule_id:%r' % rule.id text_content = "rule: %r" % rule.to_dict() val_left += """<option value="%s" title="%s">%s</option>""" % ( param_value, text_content, text_content) else: if len(ruleset_name) > 50: val_left += """<optgroup label="%s" title="%s"></optgroup>""" % (ruleset_name, ruleset_name) else: val_left += """<optgroup label="%s"></optgroup>""" % (ruleset_name,) sorted_decorated_userlist = sorted([(authenticator_id2user_prefix[u.authenticator_id], u.getName().lower(), u) for u in userlist]) for u_prefix, u_name, u in sorted_decorated_userlist: if u.id in user_not_inherited_in_left_list: continue long_val = get_list_representation_for_user(u, prefix=u_prefix) if len(long_val) > 50: val_right += """<option value="%s" title="%s">%s</option>""" % (u.id, long_val, long_val) else: val_right += """<option value="%s">%s</option>""" % (u.id, long_val) return {"name": rule_type, "val_left": val_left, "val_right": val_right, "type": rule_type}
def getContent(req, ids): user = users.getUserFromRequest(req) if "ftp" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") ids = ids[0] # use only first selected node node = tree.getNode(ids) error = "" def processFile(node, file, ftype): nname = file.retrieveFile().split("/") nname = "/".join(nname[:-1]) + "/" + nname[-1][4:] try: os.rename(file.retrieveFile(), nname) except: nname = file.retrieveFile() fnode = tree.Node(nname.split("/")[-1], ftype) node.removeFile(file) file._path = file._path.replace(config.get("paths.datadir"), "") file._path = "/".join(file._path.split("/")[:-1]) + "/" + fnode.getName() fnode.addFile(file) fnode.event_files_changed() node.addChild(fnode) return fnode for key in req.params.keys(): if key.startswith("process|"): # process selected file (single) fname = key[:-2].split("|")[-1] ftype = req.params.get("schema").replace(";", "") if ftype != "": for f in node.getFiles(): if f.getName() == fname: processFile(node, f, ftype) break break else: error = "edit_ftp_error1" elif key.startswith("del|"): for f in node.getFiles(): if f.getName() == key[4:-2]: node.removeFile(f) break break elif key.startswith("delall"): # delete all selected files delfiles = [f.split("|")[-1] for f in req.params.get("selfiles").split(";")] for f in node.getFiles(): if f.getName() in delfiles: node.removeFile(f) break elif key.startswith("processall"): # process all selected files for file in req.params.get("selfiles", "").split(";"): if file: ftype, fname = file.split("|") if "multschema|" + ftype in req.params and req.params.get("multschema|" + ftype) != "": for f in node.getFiles(): if f.getName() == fname: print "use", ftype + "/" + req.params.get("multschema|" + ftype) processFile(node, f, ftype + "/" + req.params.get("multschema|" + ftype)) break else: error = "edit_ftp_error2" break break files = filter(lambda x: x.getName().startswith("ftp_"), node.getFiles()) types = [] for f in files: if f.getType() not in types: if f.getType() != "other": types.append(f.getType()) dtypes = {} for scheme in filter(lambda x: x.isActive(), acl.AccessData(req).filter(loadTypesFromDB())): for dtype in scheme.getDatatypes(): if dtype not in dtypes.keys(): dtypes[dtype] = [] if scheme not in dtypes[dtype]: dtypes[dtype].append(scheme) for t in dtypes: dtypes[t].sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) access = acl.AccessData(req) if not access.hasWriteAccess(node): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") v = {} v["error"] = error v["files"] = files v["node"] = node v["schemes"] = dtypes # schemes v["usedtypes"] = types v["tab"] = req.params.get("tab", "") v["ids"] = ids v["script"] = "<script> parent.reloadTree('" + req.params.get("id") + "');</script>" return req.getTAL("web/edit/modules/ftp.html", v, macro="edit_ftp")
def getMetaEditor(self, item, req): """ editor mask for field definition """ attr = {} fields = [] pidnode = None if "pid" not in req.params.keys(): for p in item.getParents(): try: if p.getMasktype() == "export": pidnode = p break except: continue metadatatype = req.params.get("metadatatype") for t in metadatatype.getDatatypes(): node = tree.Node(type=t) attr.update(node.getTechnAttributes()) if req.params.get("op", "") == "new": pidnode = tree.getNode(req.params.get("pid")) if hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() in ("vgroup", "hgroup"): for field in pidnode.getAllChildren(): if field.getType().getName() == "maskitem" and field.id != pidnode.id: fields.append(field) else: for m in metadatatype.getMasks(): if str(m.id) == str(req.params.get("pid")): for field in m.getChildren(): fields.append(field) fields.sort(lambda x, y: cmp(x.getOrderPos(), y.getOrderPos())) add_values = [] val = "" if item.getField(): val = item.getField().getValues() for t in getMetaFieldTypeNames(): f = getMetadataType(t) add_values.append(f.getMaskEditorHTML(val, metadatatype=metadatatype, language=lang(req))) metafields = metadatatype.getMetaFields() metafields.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) metafieldtypes = getMetaFieldTypes().values() metafieldtypes.sort(lambda x, y: cmp(translate(x.getName(), request=req).lower(), translate(y.getName(), request=req).lower())) v = {} v["op"] = req.params.get("op", "") v["pid"] = req.params.get("pid", "") v["item"] = item v["metafields"] = metafields v["fields"] = fields v["fieldtypes"] = metafieldtypes v["dateoption"] = dateoption v["t_attrs"] = attr v["icons"] = {"externer Link": "/img/extlink.png", "Email": "/img/email.png"} v["add_values"] = add_values v["translate"] = translate v["language"] = lang(req) if pidnode and hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() == "export": v["mappings"] = [] for m in pidnode.getExportMapping(): v["mappings"].append(tree.getNode(m)) return req.getTAL("schema/mask/field.html", v, macro="metaeditor_" + pidnode.getMasktype()) else: return req.getTAL("schema/mask/field.html", v, macro="metaeditor")
def makeUserList(req, name, rights, readonlyrights, overload=0, type=""): val_left = "" val_right = "" rulelist = acl.getRuleList() userlist = {} userlist['intern'] = users.loadUsersFromDB() for usertype in list(users.getExternalUsers()): userlist[usertype.getName()] = users.getExternalUsers( usertype.getName()) rightsmap = {} rorightsmap = {} for r in rights: for u in getRuleUsers(r, userlist): if translate(u[0], lang(req)) != "": rightsmap[translate(u[0], lang(req)) + ": " + u[1]] = None else: rightsmap[u[1]] = None rrights = [] for r in readonlyrights: if r[0] == "{": for part in getRuleUsers(r, userlist): rrights.append(translate(part[0], lang(req)) + ": " + part[1]) else: rrights.append(r) readonlyrights = rrights if not (len(rightsmap) > 0 and overload): # inherited standard rules for rule in rulelist: if rule.getName() in readonlyrights: val_left += """<optgroup label="%s"></optgroup>""" % ( rule.getDescription()) rorightsmap[rule.getName()] = 1 # inherited implicit rules for rule in readonlyrights: if rule not in rorightsmap: val_left += """<optgroup label="%s"></optgroup>""" % (rule) # node-level implicit rules for r in rightsmap.keys(): if not rightsmap[r] and r not in rorightsmap: val_left += """<option value="%s">%s</option>""" % (r, r) for usertype in userlist.keys(): susers = list(userlist[usertype]) susers.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) for user in susers: if translate(usertype, lang(req)) + ": " + user.getName( ) not in rightsmap and user.getName( ) not in rorightsmap and translate(usertype, lang( req)) + ": " + user.getName() not in readonlyrights: val_right += """<option value="%s">%s</option>""" % ( translate(usertype, lang(req)) + ": " + user.getName(), translate(usertype, lang(req)) + ": " + user.getName()) return { "name": name, "val_left": val_left, "val_right": val_right, "type": type }
def _extended_searchquery_from_req(req): max_fields = 3 if req.args.get("searchmode") == "extendedsuper": max_fields = 10 q_str = u'' q_user = u'' first2 = 1 for i in range(1, max_fields + 1): query_key = "query" + unicode(i) # for range queries query_to_key = "query" + unicode(i) + "-to" query_from_key = "query" + unicode(i) + "-from" field_id_or_name = req.args.get("field" + unicode(i), "").strip() element_query = req.args.get(query_key, "").strip() if not element_query and query_from_key not in req.args: # no query found, do nothing continue if not first2: q_str += " and " q_user += translate("search_and", request=req) + " " first2 = 0 if not field_id_or_name.isdigit(): q_str += field_id_or_name + '=' + protect(element_query) q_user += field_id_or_name + '=' + protect(element_query) else: searchmaskitem = q(SearchMaskItem).get(field_id_or_name) first = 1 q_str += "(" for field in searchmaskitem.children: if not first: q_str += " or " q_user += " %s " % (translate("search_or", request=req)) first = 0 field_type = field.getFieldtype() if query_to_key in req.args and field_type == "date": date_from = "0000-00-00T00:00:00" date_to = "0000-00-00T00:00:00" from_value = req.args.get(query_from_key) if from_value: try: date_from = date.format_date( date.parse_date(from_value, field.getValues()), "%Y-%m-%dT%H:%M:%S") except ValueError: date_from = "9999-00-00T00:00:00" to_value = req.args.get(query_to_key) if to_value: try: date_to = date.format_date( date.parse_date(to_value, field.getValues()), "%Y-%m-%dT%H:%M:%S") except ValueError: date_from = "0000-00-00T00:00:00" if date_from == "0000-00-00T00:00:00" and date_to != date_from: q_str += field.name + ' <= ' + date_to q_user += "%s ≤ \"%s\"" % (field.name, to_value) elif date_to == "0000-00-00T00:00:00" and date_to != date_from: q_str += field.name + ' >= ' + date_from q_user += "%s ≥ \"%s\"" % (field.name, from_value) else: q_str += u'({} >= {} and {} <= {})'.format( field.name, date_from, field.name, date_to) q_user += "(%s %s \"%s\" %s \"%s\")" % ( field.name, translate("search_between", request=req), from_value, translate("search_and", request=req), to_value) else: # XXX: what about dates? if field_type == "number": # exact match q_str += field.name + " eq " + protect(element_query) else: # fulltext match q_str += field.name + " = " + protect(element_query) if field.label: q_user += field.label + " = " + protect(element_query) else: q_user += field.name + " = " + protect(element_query) q_str += ")" return q_str, q_user.strip()
def getMetaEditor(self, item, req): """ editor mask for field definition """ attr = {} fields = [] pidnode = None if "pid" not in req.params.keys(): for p in item.getParents(): try: if p.getMasktype() == "export": pidnode = p break except: continue metadatatype = req.params.get("metadatatype") for t in metadatatype.getDatatypes(): content_class = Node.get_class_for_typestring(t) node = content_class(name=u'') attr.update(node.getTechnAttributes()) if req.params.get("op", "") == "new": pidnode = q(Node).get(req.params.get("pid")) if hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() in ("vgroup", "hgroup"): # XXX: getAllChildren does not exist anymore, is this dead code? for field in pidnode.getAllChildren(): if field.getType().getName( ) == "maskitem" and field.id != pidnode.id: fields.append(field) else: for m in metadatatype.getMasks(): if ustr(m.id) == ustr(req.params.get("pid")): for field in m.getChildren(): fields.append(field) fields.sort(lambda x, y: cmp(x.getOrderPos(), y.getOrderPos())) add_values = [] val = u"" if item.getField(): val = item.getField().getValues() db.session.commit() for t in getMetaFieldTypeNames(): f = getMetadataType(t) add_values.append( f.getMaskEditorHTML(val, metadatatype=metadatatype, language=lang(req))) metafields = metadatatype.getMetaFields() metafields.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) metafieldtypes = getMetaFieldTypes().values() metafieldtypes.sort(lambda x, y: cmp( translate(x.getName(), request=req).lower(), translate(y.getName(), request=req).lower())) add_descriptions = [] for metafield in metafields: add_descriptions.append( '<div style="display:none" id="div_%d" name="%s" description="%s"/>' % (metafield.id, metafield.name, metafield.getDescription())) v = {} v["op"] = req.params.get("op", "") v["pid"] = req.params.get("pid", "") v["item"] = item v["metafields"] = metafields v["fields"] = fields v["fieldtypes"] = metafieldtypes v["dateoption"] = dateoption v["t_attrs"] = attr v["icons"] = { "externer Link": "/img/extlink.png", "Email": "/img/email.png" } v["add_values"] = add_values v["add_descriptions"] = add_descriptions v["translate"] = translate v["language"] = lang(req) if pidnode and hasattr( pidnode, 'getMasktype') and pidnode.getMasktype() == "export": v["mappings"] = [] for m in pidnode.getExportMapping(): v["mappings"].append(q(Node).get(m)) return req.getTAL("schema/mask/field.html", v, macro="metaeditor_" + pidnode.getMasktype()) else: return req.getTAL("schema/mask/field.html", v, macro="metaeditor")
def search(searchtype, searchquery, readable_query, paths, req, container_id=None): from web.frontend.content import ContentList if not container_id: container_id = req.args.get("id", type=int) container = q(Container).get(container_id) if container_id else None # if the current node is not a Container or not accessible by the user, use the collections root instead if container is None or not container.has_read_access(): # XXX: The collections root is always searchable. Could there be situations in which we don't want to allow this? # XXX: We could check the read permission for Collections to decide if search is allowed. container = get_collections_node() try: result = container.search(searchquery).filter_read_access() except SearchQueryException as e: # query parsing went wrong or the search backend complained about something return NoSearchResult(readable_query, container, readable_query, error=True) content_list = ContentList(result, container, paths, words=readable_query, show_sidebar=False) try: content_list.feedback(req) except Exception as e: # that should not happen, but is somewhat likely (db failures, illegal search queries that slipped through...), # just show 0 result view and don't confuse the user with unhelpful error messages ;) logg.exception( "exception executing %(searchtype)s search for query %(readable_query)s", dict(searchtype=searchtype, readable_query=readable_query, error=True)) db.session.rollback() return NoSearchResult(readable_query, container, searchtype, error=True) language = lang(req) content_list.linkname = u"{}: {} \"{}\"".format( container.getLabel(language), translate("search_for", language=language), readable_query) content_list.linktarget = "" if content_list.has_elements: logg.info("%s search with query '%s' on container %s produced results", searchtype, readable_query, container_id) return content_list else: logg.info( "%s search with query '%s' on container %s produced no results", searchtype, readable_query, container_id) return NoSearchResult(readable_query, container, searchtype)
def getContent(req, ids): user = users.getUserFromRequest(req) node = tree.getNode(ids[0]) access = acl.AccessData(req) if not access.hasWriteAccess( node) or "changeschema" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") error = req.params.get("error") currentContentType = node.getContentType() try: currentSchema = node.type.split('/')[1] # string except: currentSchema = '' currentCategoryName = node.getCategoryName() currentTypeAlias = node.getTypeAlias() schemes = AccessData(req).filter(loadTypesFromDB()) _schemes = [] for scheme in schemes: if scheme.isActive(): _schemes.append(scheme) schemes = _schemes schemeNames2LongNames = {'': ''} for s in schemes: schemeNames2LongNames[s.getName()] = s.getLongName() try: currentSchemaLongName = schemeNames2LongNames[currentSchema] except KeyError: currentSchemaLongName = '' # find out which schema allows which datatype, and hence, # which overall data types we should display dtypes = [] datatypes = loadAllDatatypes() for scheme in schemes: for dtype in scheme.getDatatypes(): if dtype not in dtypes: for t in datatypes: if t.getName() == dtype and not elemInList( dtypes, t.getName()): dtypes.append(t) dtypes.sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) admissible_objtypes = getTypes(datatypes) admissible_datatypes = [ n for n in admissible_objtypes if tree.Node('', n.name).getCategoryName() in ['document', 'image', 'video', 'audio'] ] admissible_containers = [ n for n in admissible_objtypes if tree.Node('', n.name).getCategoryName() in ['container'] ] admissible_objtypes.sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) admissible_datatypes.sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) admissible_containers.sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) available_schemes = [ s for s in schemes if currentContentType in s.getDatatypes() ] # filter schemes for special datatypes if req.params.get("objtype", "") != "": _schemes = [] for scheme in schemes: if req.params.get("objtype", "") in scheme.getDatatypes(): _schemes.append(scheme) schemes = _schemes schemes.sort(lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower())) newObjectType = req.params.get("objtype") newSchema = req.params.get("schema") if not newSchema: newSchema = '' newType = newObjectType if newSchema: newType += '/' + newSchema oldType = currentContentType if currentSchema: oldType = oldType + '/' + currentSchema if newType != oldType: node.setTypeName(newType) msg = "%s changed node schema for node %s '%s' from '%s' to '%s'" % ( user.name, node.id, node.name, oldType, newType) logger.info(msg) logging.getLogger('usertracing').info(msg) node.setDirty() # cache clean / reload because object type changed tree.remove_from_nodecaches(node) node = tree.getNode(node.id) currentContentType = node.getContentType() currentSchema = newSchema currentSchemaLongName = schemeNames2LongNames[currentSchema] currentCategoryName = node.getCategoryName() currentTypeAlias = node.getTypeAlias() available_schemes = [ s for s in schemes if newObjectType in s.getDatatypes() ] isContainer = False if hasattr(node, "isContainer"): isContainer = node.isContainer() if "action" in req.params.keys(): if req.params.get("action").startswith("get_schemes_for_"): newObjectType = req.params.get("action").replace( "get_schemes_for_", "") available_schemes = [ s for s in schemes if newObjectType in s.getDatatypes() ] req.writeTAL("web/edit/modules/changeschema.html", { 'schemes': available_schemes, 'currentSchema': currentSchema }, macro="changeschema_selectscheme") return "" containers = getContainers(datatypes) d = {"id": req.params.get("id"), "error": error, "node": node} d['currentContentType'] = currentContentType d['currentSchema'] = currentSchema d['currentSchemaLongName'] = currentSchemaLongName d['currentCategoryName'] = currentCategoryName d['currentTypeAlias'] = currentTypeAlias d['isContainer'] = int(isContainer) d['nodes'] = [node] if currentContentType in [dtype.name for dtype in containers]: d['schemes'] = [] d['datatypes'] = admissible_containers # containers else: d['schemes'] = available_schemes d['datatypes'] = admissible_datatypes # dtypes return req.getTAL("web/edit/modules/changeschema.html", d, macro="changeschema_popup")
def getMetaHTML(self, parent, index, sub=False, language=None, itemlist=[], ptype="", fieldlist={}): """ return formated row for metaeditor """ if len(itemlist) > 0: # parent still not existing item = q(Node).get(itemlist[index]) pitems = len(itemlist) else: item = parent.getChildren().sort_by_orderpos()[index] ptype = parent.get("type") pitems = len(parent.getChildren()) field = item.getField() ret = '' label = '' description = '' if field: f = getMetadataType(field.get("type")) fieldstring = f.getEditorHTML(field, width=item.getWidth(), value=item.getDefault(), language=language) + ' ' + item.getUnit() else: # node for export mask attribute = q(Node).get(item.get("attribute")) field = item fieldstring = getMetadataType("mappingfield").getEditorHTML( field, width=item.getWidth(), value=attribute.getName(), language=language) + ' ' + item.getUnit() if item.getDescription() != "": description = '<div id="div_description"><a href="#" onclick="openPopup(\'/popup_help?id=%s&maskid=%s\', \'\', 400, 250)"> <img src="/img/tooltip.png" border="0"/></a></div>' % ( field.id, item.id) if len(item.getLabel()) > 0 and item.getLabel() != "mapping": label = item.getLabel() + ': ' required = "" if item.getRequired(): required = '<span class="required">*</span>' if ptype in("vgroup", "hgroup") or not sub: label = '<div class="label">%s %s</div>%s' % (label, required, description) else: label += required else: label = '<div class="label"> </div>' if not sub: ret += '<div id="%s" class="row" onmouseover="pick(this)" onmouseout="unpick(this)" onclick="select(this)" style="position:relative;min-height:30px">' % ( item.id) if len(label) > 0: ret += '%s<div id="editor_content">%s</div>' % (label, fieldstring) else: ret += fieldstring if not sub: # <small style="color:silver">('+(item.get("type"))+')</small>' ret += '<div align="right" id="%s_sub" style="display:none; position:absolute; right:1px; top:3px" class="edit_tools">' % ( item.id) if index > 0: ret += '<input type="image" src="/img/uparrow.png" name="up_%s" i18n:attributes="title mask_edit_up_title"/>' % (item.id) else: ret += ' ' if index < pitems - 1: ret += '<input type="image" src="/img/downarrow.png" name="down_%s" i18n:attributes="title mask_edit_down_title"/>' % ( item.id) else: ret += ' ' if field.getName() in fieldlist.keys(): if len(fieldlist[field.getName()]) > 1: ret += ' <img src="/img/attention.gif" title="%s ' % (translate("mask_edit_multi_label", language)) ret += ", ".join([schema.getName() for schema in fieldlist[field.getName()]]) + '"/>' ret += ' <input type="image" src="/img/edit.png" name="edit_%s" i18n:attributes="title mask_edit_edit_row"/> <input type="image" src="/img/delete.png" name="delete_%s" i18n:attributes="title mask_edit_delete_row" onClick="return questionDel()"/></div></div>' % (item.id, item.id) return ret
def getContent(req, ids): class SortChoice: def __init__(self, label, value): self.label = label self.value = value def getSchemes(_req): return filter(lambda x: x.isActive(), acl.AccessData(_req).filter(loadTypesFromDB())) def getDatatypes(_req, _schemes): _dtypes = [] datatypes = loadAllDatatypes() for scheme in _schemes: for dtype in scheme.getDatatypes(): if dtype not in _dtypes: for _t in datatypes: if _t.getName() == dtype and not elemInList(dtypes, _t.getName()): dtypes.append(_t) _dtypes.sort( lambda x, y: cmp( translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower() ) ) return _dtypes node = tree.getNode(ids[0]) if "action" in req.params: if req.params.get("action") == "resort": _dir = "up" field = req.params.get("value", "").strip() nl = list(node.getChildren()) if field: if field[0] == "-": field = field[1:] _dir = "down" nl.sort(lambda x, y: cmp(x.get(field).lower(), y.get(field).lower())) if _dir == "down": nl.reverse() req.write(json.dumps({"state": "ok", "values": showdir(req, node, nodes=nl, sortfield_from_req=field)})) return None elif req.params.get("action") == "save": # save selection for collection field = req.params.get("value") if field.strip() == "": node.removeAttribute("sortfield") else: node.set("sortfield", field) req.write(json.dumps({"state": "ok", "message": translate("edit_content_save_order", request=req)})) return None if node.isContainer(): schemes = [] dtypes = [] v = {"operations": showoperations(req, node), "items": showdir(req, node)} access = acl.AccessData(req) if access.hasWriteAccess(node): schemes = getSchemes(req) dtypes = getDatatypes(req, schemes) 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"]: try: 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 except TypeError: pass v["sortchoices"] = sortfields v["types"] = dtypes v["schemes"] = schemes v["id"] = ids[0] v["count"] = len(node.getContentChildren()) v["language"] = lang(req) v["t"] = t return req.getTAL("web/edit/modules/content.html", v, macro="edit_content") if hasattr(node, "editContentDefault"): return node.editContentDefault(req) return ""
def extended_search(req): from web.frontend.content import ContentList max = 3 if req.params.get("searchmode") == "extendedsuper": max = 10 sfields = [] access = AccessData(req) metatype = None collectionid = req.params.get("collection", tree.getRoot().id) try: collection = tree.getNode(collectionid) except: for coll in tree.getRoot("collections").getChildren(): collection = tree.getNode(coll.id) break q_str = '' q_user = '' first2 = 1 for i in range(1, max + 1): f = u(req.params.get("field" + str(i), "").strip()) q = u(req.params.get("query" + str(i), "").strip()) if not q and "query" + str(i) + "-from" not in req.params: continue if not first2: q_str += " and " q_user += " %s " % (translate("search_and", request=req)) first2 = 0 if not f.isdigit(): q = u(req.params.get("query" + str(i), "").strip()) q_str += f + '=' + protect(q) q_user += f + '=' + protect(q) else: masknode = tree.getNode(f) assert masknode.type == "searchmaskitem" first = 1 q_str += "(" for metatype in masknode.getChildren(): if not first: q_str += " or " q_user += " %s " % (translate("search_or", request=req)) first = 0 if "query" + str(i) + "-from" in req.params and metatype.getFieldtype() == "date": date_from = "0000-00-00T00:00:00" date_to = "0000-00-00T00:00:00" fld = metatype if str(req.params["query" + str(i) + "-from"]) != "": date_from = date.format_date( date.parse_date(str(req.params["query" + str(i) + "-from"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S") if str(req.params["query" + str(i) + "-to"]) != "": date_to = date.format_date( date.parse_date(str(req.params["query" + str(i) + "-to"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S") if date_from == "0000-00-00T00:00:00" and date_to != date_from: # from value q_str += metatype.getName() + ' <= ' + date_to q_user += "%s ≤ \"%s\"" % (metatype.getName(), str(req.params["query" + str(i) + "-to"])) elif date_to == "0000-00-00T00:00:00" and date_to != date_from: # to value q_str += metatype.getName() + ' >= ' + date_from q_user += "%s ≥ \"%s\"" % (metatype.getName(), str(req.params["query" + str(i) + "-from"])) else: q_str += '({} >= {} and {} <= {})'.format(metatype.getName(), date_from, metatype.getName(), date_to) q_user += "(%s %s \"%s\" %s \"%s\")" % (metatype.getName(), translate("search_between", request=req), str(req.params["query" + str(i) + "-from"]), translate("search_and", request=req), str(req.params["query" + str(i) + "-to"])) else: q = u(req.params.get("query" + str(i), "").strip()) q_str += metatype.getName() + '=' + protect(q) if metatype.getLabel() != "": q_user += "%s = %s" % (metatype.getLabel(), protect(q)) else: q_user += "%s = %s" % (metatype.getName(), protect(q)) q_str += ")" try: if req.params.get("act_node", "") and req.params.get("act_node") != str(collection.id): result = tree.getNode(req.params.get("act_node")).search(q_str) else: result = collection.search(q_str) result = access.filter(result) logging.getLogger('usertracing').info(access.user.name + " xsearch for '" + q_user + "', " + str(len(result)) + " results") if len(result) > 0: cl = ContentList(result, collection, q_user.strip()) cl.feedback(req) cl.linkname = "" cl.linktarget = "" return cl return SearchResult([], q_user.strip()) except: return SearchResult(None, q_user.strip())
def callhandler(handler_func, req): for handler in _request_started_handlers: handler(req) try: status = handler_func(req) except Exception as e: # XXX: this shouldn't be in Athana, most of it is mediaTUM-specific... # TODO: add some kind of exception handler system for Athana request = req.request if _config.get('host.type') != 'testing': from utils.log import make_xid_and_errormsg_hash, extra_log_info_from_req from core.translation import translate from core import db # Roll back if the error was caused by a database problem. # DB requests in this error handler will fail until rollback is called, so let's do it here. db.session.rollback() xid, hashed_errormsg, hashed_tb = make_xid_and_errormsg_hash() mail_to_address = _config.get('email.support') if not mail_to_address: _logg.warn( "no support mail address configured, consider setting it with `email.support`", trace=False) log_extra = { "xid": xid, "error_hash": hashed_errormsg, "trace_hash": hashed_tb } log_extra["req"] = extra_log_info_from_req(req) _logg.exception( u"exception (xid=%s) while handling request %s %s, %s", xid, req.method, req.path, dict(req.args), extra=log_extra) if mail_to_address: msg = translate("core_snipped_internal_server_error_with_mail", request=req).replace('${email}', mail_to_address) else: msg = translate( "core_snipped_internal_server_error_without_mail", request=req) s = msg.replace('${XID}', xid) req.reply_headers["X-XID"] = xid return error( request, 500, s.encode("utf8"), content_type='text/html; encoding=utf-8; charset=utf-8') else: _logg.error("Error in page: '%s %s', session '%s'", request.type, request.fullpath, request.session.id, exc_info=1) s = "<pre>" + _traceback.format_exc() + "</pre>" return error(request, 500, s) finally: for handler in _request_finished_handlers: handler(req)
def getContent(req, ids): user = current_user node = q(Node).get(ids[0]) if not node.has_write_access() or "changeschema" in current_user.hidden_edit_functions: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") # nobody should be able to change the type/schema of his home directory if node.id == user.home_dir_id: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") error = req.params.get("error") schemes = get_permitted_schemas() long_scheme_names = {scheme.name: scheme.getLongName() for scheme in schemes} if isinstance(node, Container): admissible_containers = [s.__name__.lower() for s in Container.get_all_subclasses(filter_classnames=["container", "collections", "home", "root"])] else: admissible_content_types = [s.__name__.lower() for s in Content.get_all_subclasses(filter_classnames=["content"])] # filter schemes for special datatypes if req.params.get("objtype", "") != "": new_type = req.params.get('objtype', '') new_schema = req.params.get('schema', '') if not new_schema: return _redirect_to_view(req) if new_type != node.type or new_schema != node.schema: if isinstance(node, Container): if not new_type in admissible_containers: logg.warn(u"changeschema: illegal container type %s", new_type) return httpstatus.HTTP_BAD_REQUEST else: if not new_type in admissible_content_types: logg.warn(u"changeschema: illegal content type %s", new_type) return httpstatus.HTTP_BAD_REQUEST available_schema_names = [s.name for s in schemes if new_type in s.getDatatypes()] if not new_schema in available_schema_names: logg.warn(u"changeschema: illegal schema %s", new_schema) return httpstatus.HTTP_BAD_REQUEST logg.info(u"{} changed node schema for node {} '{}' from '{}' to '{}'".format(user.login_name, node.id, node.name, node.type, new_type)) node.type = new_type node.schema = new_schema db.session.commit() return _redirect_to_view(req) elif "action" in req.params.keys(): available_schemes = [s for s in schemes if node.type in s.getDatatypes()] if req.params.get("action").startswith("get_schemes_for_"): new_type = req.params.get("action").replace("get_schemes_for_", "").lower() available_schemes = [s for s in schemes if new_type in s.getDatatypes()] req.writeTAL("web/edit/modules/changeschema.html", {'schemes': available_schemes, 'current_schema': node.schema}, macro="changeschema_selectscheme") return "" else: d = {'id': req.params.get('id'), 'error': error, 'node': node, 'current_type': node.type, 'current_schema': node.schema, # XXX: this is the only line that uses getTypeAlias. What is the real meaning? 'type_alias': node.getTypeAlias(), 'is_container': int(node.isContainer()), 'nodes': [node]} d['long_current_schema'] = long_scheme_names.get(node.schema) available_schemes = [s for s in schemes if node.type in s.getDatatypes()] if isinstance(node, Container): admissible_containers.sort(key=lambda x: translate(x, request=req).lower()) d['schemes'] = available_schemes d['datatypes'] = admissible_containers else: admissible_content_types.sort(key=lambda x: translate(x, request=req).lower()) d['schemes'] = available_schemes d['datatypes'] = admissible_content_types d["csrf"] = req.csrf_token.current_token return req.getTAL("web/edit/modules/changeschema.html", d, macro="changeschema_popup")
def getMetaEditor(self, item, req): """ editor mask for field definition """ attr = {} fields = [] pidnode = None if "pid" not in req.params.keys(): for p in item.getParents(): try: if p.getMasktype() == "export": pidnode = p break except: continue metadatatype = req.params.get("metadatatype") for t in metadatatype.getDatatypes(): node = tree.Node(type=t) attr.update(node.getTechnAttributes()) if req.params.get("op", "") == "new": pidnode = tree.getNode(req.params.get("pid")) if hasattr(pidnode, 'getMasktype') and pidnode.getMasktype() in ("vgroup", "hgroup"): for field in pidnode.getAllChildren(): if field.getType().getName( ) == "maskitem" and field.id != pidnode.id: fields.append(field) else: for m in metadatatype.getMasks(): if str(m.id) == str(req.params.get("pid")): for field in m.getChildren(): fields.append(field) fields.sort(lambda x, y: cmp(x.getOrderPos(), y.getOrderPos())) add_values = [] val = "" if item.getField(): val = item.getField().getValues() for t in getMetaFieldTypeNames(): f = getMetadataType(t) add_values.append( f.getMaskEditorHTML(val, metadatatype=metadatatype, language=lang(req))) metafields = metadatatype.getMetaFields() metafields.sort(lambda x, y: cmp(x.getName().lower(), y.getName().lower())) metafieldtypes = getMetaFieldTypes().values() metafieldtypes.sort(lambda x, y: cmp( translate(x.getName(), request=req).lower(), translate(y.getName(), request=req).lower())) v = {} v["op"] = req.params.get("op", "") v["pid"] = req.params.get("pid", "") v["item"] = item v["metafields"] = metafields v["fields"] = fields v["fieldtypes"] = metafieldtypes v["dateoption"] = dateoption v["t_attrs"] = attr v["icons"] = { "externer Link": "/img/extlink.png", "Email": "/img/email.png" } v["add_values"] = add_values v["translate"] = translate v["language"] = lang(req) if pidnode and hasattr( pidnode, 'getMasktype') and pidnode.getMasktype() == "export": v["mappings"] = [] for m in pidnode.getExportMapping(): v["mappings"].append(tree.getNode(m)) return req.getTAL("schema/mask/field.html", v, macro="metaeditor_" + pidnode.getMasktype()) else: return req.getTAL("schema/mask/field.html", v, macro="metaeditor")
def getContent(req, ids): user = users.getUserFromRequest(req) node = tree.getNode(ids[0]) access = acl.AccessData(req) if not access.hasWriteAccess(node) or "changeschema" in users.getHideMenusForUser(user): req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") error = req.params.get("error") currentContentType = node.getContentType() try: currentSchema = node.type.split("/")[1] # string except: currentSchema = "" currentCategoryName = node.getCategoryName() currentTypeAlias = node.getTypeAlias() schemes = AccessData(req).filter(loadTypesFromDB()) _schemes = [] for scheme in schemes: if scheme.isActive(): _schemes.append(scheme) schemes = _schemes schemeNames2LongNames = {"": ""} for s in schemes: schemeNames2LongNames[s.getName()] = s.getLongName() try: currentSchemaLongName = schemeNames2LongNames[currentSchema] except KeyError: currentSchemaLongName = "" # find out which schema allows which datatype, and hence, # which overall data types we should display dtypes = [] datatypes = loadAllDatatypes() for scheme in schemes: for dtype in scheme.getDatatypes(): if dtype not in dtypes: for t in datatypes: if t.getName() == dtype and not elemInList(dtypes, t.getName()): dtypes.append(t) dtypes.sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) admissible_objtypes = getTypes(datatypes) admissible_datatypes = [ n for n in admissible_objtypes if tree.Node("", n.name).getCategoryName() in ["document", "image", "video", "audio"] ] admissible_containers = [n for n in admissible_objtypes if tree.Node("", n.name).getCategoryName() in ["container"]] admissible_objtypes.sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) admissible_datatypes.sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) admissible_containers.sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) available_schemes = [s for s in schemes if currentContentType in s.getDatatypes()] # filter schemes for special datatypes if req.params.get("objtype", "") != "": _schemes = [] for scheme in schemes: if req.params.get("objtype", "") in scheme.getDatatypes(): _schemes.append(scheme) schemes = _schemes schemes.sort( lambda x, y: cmp( translate(x.getLongName(), request=req).lower(), translate(y.getLongName(), request=req).lower() ) ) newObjectType = req.params.get("objtype") newSchema = req.params.get("schema") if not newSchema: newSchema = "" newType = newObjectType if newSchema: newType += "/" + newSchema oldType = currentContentType if currentSchema: oldType = oldType + "/" + currentSchema if newType != oldType: node.setTypeName(newType) msg = "%s changed node schema for node %s '%s' from '%s' to '%s'" % ( user.name, node.id, node.name, oldType, newType, ) logger.info(msg) logging.getLogger("usertracing").info(msg) node.setDirty() # cache clean / reload because object type changed tree.remove_from_nodecaches(node) node = tree.getNode(node.id) currentContentType = node.getContentType() currentSchema = newSchema currentSchemaLongName = schemeNames2LongNames[currentSchema] currentCategoryName = node.getCategoryName() currentTypeAlias = node.getTypeAlias() available_schemes = [s for s in schemes if newObjectType in s.getDatatypes()] isContainer = False if hasattr(node, "isContainer"): isContainer = node.isContainer() if "action" in req.params.keys(): if req.params.get("action").startswith("get_schemes_for_"): newObjectType = req.params.get("action").replace("get_schemes_for_", "") available_schemes = [s for s in schemes if newObjectType in s.getDatatypes()] req.writeTAL( "web/edit/modules/changeschema.html", {"schemes": available_schemes, "currentSchema": currentSchema}, macro="changeschema_selectscheme", ) return "" containers = getContainers(datatypes) d = {"id": req.params.get("id"), "error": error, "node": node} d["currentContentType"] = currentContentType d["currentSchema"] = currentSchema d["currentSchemaLongName"] = currentSchemaLongName d["currentCategoryName"] = currentCategoryName d["currentTypeAlias"] = currentTypeAlias d["isContainer"] = int(isContainer) d["nodes"] = [node] if currentContentType in [dtype.name for dtype in containers]: d["schemes"] = [] d["datatypes"] = admissible_containers # containers else: d["schemes"] = available_schemes d["datatypes"] = admissible_datatypes # dtypes return req.getTAL("web/edit/modules/changeschema.html", d, macro="changeschema_popup")