diff --git a/modules/bibrank/lib/bibrankadminlib.py b/modules/bibrank/lib/bibrankadminlib.py index 2698546d4..e9af179c1 100644 --- a/modules/bibrank/lib/bibrankadminlib.py +++ b/modules/bibrank/lib/bibrankadminlib.py @@ -1,1087 +1,1092 @@ ## Administrator interface for BibRank ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## read config variables: #include "config.wml" #include "configbis.wml" #include "cdswmllib.wml" ## $Id$ ## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES. """CDSware BibRank Administrator Interface.""" __lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>""" ## fill config variables: import access_control_engine as acce import cgi import re import MySQLdb import Numeric import os from zlib import compress,decompress from messages import * from dbquery import run_sql from config import * from webpage import page, pageheaderonly, pagefooteronly from webuser import getUid, get_email from mod_python import apache __version__ = "$Id$" def getnavtrail(previous = ''): navtrail = """Admin Area > BibRank Admin """ % (weburl, weburl) navtrail = navtrail + previous return navtrail def check_user(uid, role, adminarea=2, authorized=0): if not authorized and not is_adminuser(uid, role): return "false" def is_adminuser(uid, role): """check if user is a registered administrator. """ return acce.acc_authorize_action(uid, role) def perform_index(ln=cdslang): """create the bibrank main area menu page.""" header = ['Name', 'Translations', 'Collections', 'Rank method'] rnk_list = get_current_name('', ln, get_rnk_nametypes()[0][0], "rnkMETHOD") actions = [] for (rnkID, name) in rnk_list: actions.append([name]) for col in [(('Modify', 'modifytranslations'),), (('Modify', 'modifycollection'),), (('Show Details', 'showrankdetails'), ('Modify', 'modifyrank'), ('Delete', 'deleterank'))]: actions[-1].append('%s' % (weburl, col[0][1], rnkID, ln, col[0][0])) for (str, function) in col[1:]: actions[-1][-1] += ' / %s' % (weburl, function, rnkID, ln, str) output = """ Add new rank method

""" % (weburl, ln) output += tupletotable(header=header, tuple=actions) - return addadminbox("""Overview of rank methodss   [?]""" % weburl, datalist=[output, '']) + return addadminbox("""Overview of rank methods   [?]""" % weburl, datalist=[output, '']) def perform_modifycollection(rnkID='', ln=cdslang, func='', colID='', confirm=0): """Modify which collections the rank method is visible to""" output = "" subtitle = "" if rnkID: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] if func in ["0", 0] and confirm in ["1", 1]: finresult = attach_col_rnk(rnkID, colID) elif func in ["1", 1] and confirm in ["1", 1]: finresult = detach_col_rnk(rnkID, colID) if colID: colNAME = get_current_name(colID, ln, get_col_nametypes()[0][0], "collection")[0][1] subtitle = """Step 1 - Select collection to enable/disable rank method '%s' for""" % rnkNAME output = """
The rank method is currently enabled for these collections:
""" col_list = get_rnk_col(rnkID, ln) if not col_list: output += """No collections""" else: for (id, name) in col_list: output += """%s, """ % name output += """
""" col_list = get_current_name('', ln, get_col_nametypes()[0][0], "collection") col_rnk = dict(get_rnk_col(rnkID)) col_list = filter(lambda x: not col_rnk.has_key(x[0]), col_list) if col_list: text = """ Enable for: """ output += createhiddenform(action="modifycollection", text=text, button="Enable", rnkID=rnkID, ln=ln, func=0, - confirm=0) + confirm=1) if confirm in ["0", 0] and func in ["0", 0] and colID: subtitle = "Step 2 - Confirm to enable rank method for the chosen collection" text = "

Please confirm to enable rank method '%s' for the collection '%s'

" % (rnkNAME, colNAME) output += createhiddenform(action="modifycollection", text=text, button="Confirm", rnkID=rnkID, ln=ln, colID=colID, func=0, confirm=1) elif confirm in ["1", 1] and func in ["0", 0] and colID: subtitle = "Step 3 - Result" if finresult: output += """Rank method '%s' enabled for collection '%s'""" % (rnkNAME, colNAME) else: output += """Rank method '%s' could not be enabled for collection '%s'""" % (rnkNAME[0], colNAME) - + elif confirm not in ["0", 0] and func in ["0", 0]: + output += """Please select a collection.""" + col_list = get_rnk_col(rnkID, ln) if col_list: text = """ Disable for: """ output += createhiddenform(action="modifycollection", text=text, button="Disable", rnkID=rnkID, ln=ln, func=1, - confirm=0) + confirm=1) if confirm in ["0", 0] and func in ["1", 1] and colID: subtitle = "Step 2 - Confirm to disable rank method for collection" text = "

Please confirm to disable rank method '%s' for collection '%s'

" % (rnkNAME, colNAME) output += createhiddenform(action="modifycollection", text=text, button="Confirm", rnkID=rnkID, ln=ln, colID=colID, func=1, confirm=1) elif confirm in ["1", 1] and func in ["1", 1] and colID: subtitle = "Step 3 - Result" if finresult: output += """Rank method '%s' disabled for collection '%s'""" % (rnkNAME, colNAME) else: output += """Rank method '%s' could not be disabled for collection '%s'""" % (rnkNAME, colNAME) + elif confirm not in ["0", 0] and func in ["1", 1]: + output += """Please select a collection.""" try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_modifytranslations(rnkID, ln, sel_type, trans, confirm, callback='yes'): """Modify the translations of a rank method""" output = '' subtitle = '' cdslangs = get_languages() cdslangs.sort() if confirm in ["2", 2] and rnkID: finresult = modify_translations(rnkID, cdslangs, sel_type, trans, "rnkMETHOD") rnk_dict = dict(get_current_name('', ln, get_rnk_nametypes()[0][0], "rnkMETHOD")) if rnkID and rnk_dict.has_key(int(rnkID)): rnkID = int(rnkID) subtitle = """3. Modify translations for rank method '%s'""" % rnk_dict[rnkID] if type(trans) is str: trans = [trans] if sel_type == '': sel_type = get_rnk_nametypes()[0][0] header = ['Language', 'Translation'] actions = [] text = """ Name type """ output += createhiddenform(action="modifytranslations", text=text, button="Select", rnkID=rnkID, ln=ln, confirm=0) if confirm in [-1, "-1", 0, "0"]: trans = [] for key, value in cdslangs: try: trans_names = get_name(rnkID, key, sel_type, "rnkMETHOD") trans.append(trans_names[0][0]) except StandardError, e: trans.append('') for nr in range(0,len(cdslangs)): actions.append(["%s %s" % (cdslangs[nr][1], (cdslangs[nr][0]==cdslang and '(def)' or ''))]) actions[-1].append('' % trans[nr]) text = tupletotable(header=header, tuple=actions) output += createhiddenform(action="modifytranslations", text=text, button="Modify", rnkID=rnkID, sel_type=sel_type, ln=ln, - confirm=1) + confirm=2) if sel_type and len(trans): if confirm in ["1", 1]: text = """Please confirm modification of translations for rank method '%s'.""" % (rnk_dict[rnkID]) output += createhiddenform(action="modifytranslations", text=text, button="Confirm", rnkID=rnkID, sel_type=sel_type, trans=trans, ln=ln, confirm=2) elif confirm in ["2", 2]: if finresult: output += """Translations modified for rank method '%s'.""" % (rnk_dict[rnkID]) else: output += """Sorry, could not modify translations for rank method '%s'.""" % (rnk_dict[rnkID]) try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_addrankarea(rnkcode='', ln=cdslang, template='', confirm=-1): """form to add a new rank method with these values: """ subtitle = 'Step 1 - Create new rank method' output = """
BibRank code:
A unique code that identifies a rank method, is used when running the bibrank daemon and used to name the configuration file for the method.
The template files includes the necessary parameters for the chosen rank method, and only needs to be edited with the correct tags and paths.
For more information, please go to the BibRank guide and read the section about adding a rank method
""" % weburl text = """ BibRank code """ % (rnkcode) text += """
Cfg template """ output += createhiddenform(action="addrankarea", text=text, button="Add rank method", ln=ln, - confirm=0) + confirm=1) if rnkcode: if confirm in ["0", 0]: subtitle = 'Step 2 - Confirm addition of rank method' text = """Add rank method with BibRank code: '%s'.""" % (rnkcode) if template: text += """
Using configuration template: '%s'.""" % (template) else: text += """
Create empty configuration file.""" output += createhiddenform(action="addrankarea", text=text, rnkcode=rnkcode, button="Confirm", template=template, confirm=1) elif confirm in ["1", 1]: rnkID = add_rnk(rnkcode) subtitle = "Step 3 - Result" if rnkID: rnkID = rnkID[0] text = """Added new rank method with BibRank code '%s'""" % rnkcode try: if template: infile = open("%s/bibrank/%s" % (etcdir, template), 'r') indata = infile.readlines() infile.close() else: indata = () file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0]), 'w') for line in indata: file.write(line) file.close() if template: text += """
Configuration file created using '%s' as template.
""" % template else: text += """
Empty configuration file created.
""" except StandardError, e: text += """
Sorry, could not create configuration file: '%s/bibrank/%s.cfg', either because it already exists, or not enough rights to create file.
Please create the file in the path given.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) else: text = """Sorry, could not add rank method, rank method with the same BibRank code probably exists.""" output += text - elif not rnkcode and confirm in ["0", 0]: + elif not rnkcode and confirm not in [-1, "-1"]: output += """Sorry, could not add rank method, not enough data submitted.""" try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_modifyrank(rnkID, rnkcode='', ln=cdslang, template='', cfgfile='', confirm=0): """form to modify a rank method rnkID - id of the rank method """ subtitle = 'Step 1 - Please modify the wanted values below' if not rnkcode: oldcode = get_rnk_code(rnkID)[0] else: oldcode = rnkcode output = """
When changing the BibRank code of a rank method, you must also change any scheduled tasks using the old value.
For more information, please go to the BibRank guide and read the section about modifying a rank method's BibRank code.
""" % weburl text = """ BibRank code
""" % (oldcode) try: text += """Cfg file""" textarea = "" if cfgfile: textarea +=cfgfile else: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0])) for line in file.readlines(): textarea += line text += """""" except StandardError, e: text += """Cannot load file, either it does not exist, or not enough rights to read it: '%s/bibrank/%s.cfg'
Please create the file in the path given.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, button="Modify", - confirm=0) + confirm=1) text = "" if rnkcode and confirm in ["0", 0] and get_rnk_code(rnkID)[0][0] != rnkcode: subtitle = 'Step 2 - Confirm modification of configuration' text += "Modify rank method '%s' with old code '%s' and set new code '%s'." % (get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][0], get_rnk_code(rnkID)[0][0], rnkcode) if cfgfile and confirm in ["0", 0]: subtitle = 'Step 2 - Confirm modification of configuration' text += "
Modify configuration file" if (rnkcode or cfgfile) and confirm in ["0", 0] and not template: output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, rnkcode=rnkcode, cfgfile=cfgfile, button="Confirm", confirm=1) if rnkcode and confirm in ["1", 1] and get_rnk_code(rnkID)[0][0] != rnkcode: oldcode = get_rnk_code(rnkID)[0][0] result = modify_rnk(rnkID, rnkcode) subtitle = "Step 3 - Result" if result: text = """Rank method '%s' modified, new code is '%s'.""" % (get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][0], rnkcode) try: file = open("%s/bibrank/%s.cfg" % (etcdir, oldcode), 'r') file2 = open("%s/bibrank/%s.cfg" % (etcdir, rnkcode), 'w') lines = file.readlines() for line in lines: file2.write(line) file.close() file2.close() os.remove("%s/bibrank/%s.cfg" % (etcdir, oldcode)) except StandardError, e: text = """Sorry, could not change name of cfg file, must be done manually: '%s/bibrank/%s.cfg'""" % (etcdir, oldcode) else: text = """Sorry, could not modify rank method.""" output += text if cfgfile and confirm in ["1", 1]: try: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0]), 'w') file.write(cfgfile) file.close() text = """
Configuration file modified: '%s/bibrank/%s.cfg'
""" % (etcdir, get_rnk_code(rnkID)[0][0]) except StandardError, e: text = """
Sorry, could not modify configuration file, please check for rights to do so: '%s/bibrank/%s.cfg'
Please modify the file manually.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) output += text finoutput = addadminbox(subtitle + """   [?]""" % weburl, [output]) output = "" text = """ Select
""" output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, button="Show template", confirm=0) try: if template: textarea = "" text = """Content:""" file = open("%s/bibrank/%s" % (etcdir, template), 'r') lines = file.readlines() for line in lines: textarea += line file.close() text += """""" output += text except StandardError, e: output += """Cannot load file, either it does not exist, or not enough rights to read it: '%s/bibrank/%s'""" % (etcdir, template) finoutput += addadminbox("View templates", [output]) return finoutput def perform_deleterank(rnkID, ln=cdslang, confirm=0): """form to delete a rank method """ subtitle ='' output = """
WARNING:
When deleting a rank method, you also deletes all data related to the rank method, like translations, which collections it was attached to and the data necessary to rank the searchresults. Any scheduled tasks using the deleted rank method will also stop working.

For more information, please go to the BibRank guide and read the section regarding deleting a rank method.
""" % weburl if rnkID: if confirm in ["0", 0]: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] subtitle = 'Step 1 - Confirm deletion' text = """Delete rank method '%s'.""" % (rnkNAME) output += createhiddenform(action="deleterank", text=text, + button="Confirm", rnkID=rnkID, confirm=1) elif confirm in ["1", 1]: try: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] rnkcode = get_rnk_code(rnkID)[0][0] result = delete_rnk(rnkID) subtitle = "Step 2 - Result" if result: text = """Rank method '%s' deleted""" % rnkNAME try: os.remove("%s/bibrank/%s.cfg" % (etcdir, rnkcode)) text += """
Configuration file deleted: '%s/bibrank/%s.cfg'.""" % (etcdir, rnkcode) except StandardError, e: text += """
Sorry, could not delete configuration file: '%s/bibrank/%s.cfg'.
Please delete the file manually.
""" % (etcdir, rnkcode) else: text = """Sorry, could not delete rank method '%s'""" % rnkNAME except StandardError, e: text = """Sorry, could not delete rank method, most likely already deleted""" output = text try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_showrankdetails(rnkID, ln=cdslang): """Returns details about the rank method given by rnkID""" subtitle = """Overview [Modify]""" % (weburl, rnkID, ln) text = """ BibRank code: %s
Last updated by BibRank: """ % (get_rnk_code(rnkID)[0][0]) if get_rnk(rnkID)[0][2]: text += "%s
" % get_rnk(rnkID)[0][2] else: text += "Not yet run.
" output = addadminbox(subtitle, [text]) subtitle = """Rank method sets""" text = "" try: threshold = deserialize_via_numeric_array(get_rnk(rnkID)[0][3]) res = get_rnk_set(rnkID) for i in range(0, len(res)): set = deserialize_via_numeric_array(res[i][2]) text += "Star %s : %s (Threshold: %s)
" % (res[i][1], set._nbhits, threshold[res[i][1]]) except StandardError, e: text = "BibRank not yet run, cannot show sets" output += addadminbox(subtitle, [text]) subtitle = """Attached to collections [Modify]""" % (weburl, rnkID, ln) text = "" col = get_rnk_col(rnkID, ln) for key, value in col: text+= "%s
" % value if not col: text +="No collections" output += addadminbox(subtitle, [text]) subtitle = """Translations [Modify]""" % (weburl, rnkID, ln) prev_lang = '' trans = get_translations(rnkID) types = get_rnk_nametypes() types = dict(map(lambda x: (x[0], x[1]), types)) text = "" languages = dict(get_languages()) if trans: for lang, type, name in trans: if lang and type and name: if prev_lang != lang: prev_lang = lang text += """%s:
""" % (languages[lang]) if types.has_key(type): text+= """'%s'(%s)
""" % (name, types[type]) else: text = """No translations exists""" output += addadminbox(subtitle, [text]) subtitle = """Configuration file: '%s/bibrank/%s.cfg' [Modify]""" % (etcdir, get_rnk_code(rnkID)[0][0], weburl, rnkID, ln) text = "" try: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0])) text += """
"""
         for line in file.readlines():
             text += line
         text += """
""" except StandardError, e: text = """Cannot load file, either it does not exist, or not enough rights to read it.""" output += addadminbox(subtitle, [text]) return output def compare_on_val(second, first): return cmp(second[1], first[1]) def get_rnk_code(rnkID): """Returns the name from rnkMETHOD based on argument rnkID - id from rnkMETHOD""" try: res = run_sql("SELECT name FROM rnkMETHOD where id=%s" % (rnkID)) return res except StandardError, e: return () def get_rnk(rnkID=''): """Return one or all rank methods rnkID - return the rank method given, or all if not given""" try: if rnkID: res = run_sql("SELECT id,name,last_updated,star_category_ranges from rnkMETHOD WHERE id=%s" % rnkID) else: res = run_sql("SELECT id,name,last_updated,star_category_ranges from rnkMETHOD") return res except StandardError, e: return () def get_translations(rnkID): """Returns the translations in rnkMETHODNAME for a rankmethod rnkID - the id of the rankmethod from rnkMETHOD """ try: res = run_sql("SELECT ln, type, value FROM rnkMETHODNAME where id_rnkMETHOD=%s ORDER BY ln,type" % (rnkID)) return res except StandardError, e: return () def get_rnk_nametypes(): """Return a list of the various translationnames for the rank methods""" type = [] type.append(('ln', 'Long name')) type.append(('sn', 'Short name')) return type def get_col_nametypes(): """Return a list of the various translationnames for the rank methods""" type = [] type.append(('ln', 'Long name')) return type def get_rnk_set(rnkID=''): """Return all rank sets, or all for a specified rank method rnkID = if given, return rank sets of specified rank method, if not, return all. """ try: if rnkID: res = run_sql("SELECT id_rnkMETHOD,star_category,hitset from rnkSET WHERE id_rnkMETHOD=%s ORDER BY star_category" % rnkID) else: res = run_sql("SELECT id_rnkMETHOD,star_category,hitset from rnkSET order by id_rnkMETHOD,starcategory") return res except StandardError, e: return () def get_rnk_col(rnkID, ln=cdslang): """ Returns a list of the collections the given rank method is attached to rnkID - id from rnkMETHOD""" try: res1 = dict(run_sql("SELECT id_collection, '' FROM collection_rnkMETHOD WHERE id_rnkMETHOD=%s" % rnkID)) res2 = get_current_name('',ln, get_col_nametypes()[0][0], "collection") result = filter(lambda x: res1.has_key(x[0]), res2) return result except StandardError, e: return () def get_templates(): """Read etcdir/bibrank and returns a list of all files with 'template' """ templates = [] files = os.listdir(etcdir + "/bibrank/") for file in files: if str.find(file,"template_") != -1: templates.append(file) return templates def attach_col_rnk(rnkID, colID): """attach rank method to collection rnkID - id from rnkMETHOD table colID - id of collection, as in collection table """ try: res = run_sql("INSERT INTO collection_rnkMETHOD(id_collection, id_rnkMETHOD) values (%s,%s)" % (colID, rnkID)) return "true" except StandardError, e: return "" def detach_col_rnk(rnkID, colID): """detach rank method from collection rnkID - id from rnkMETHOD table colID - id of collection, as in collection table """ try: res = run_sql("DELETE FROM collection_rnkMETHOD WHERE id_collection=%s AND id_rnkMETHOD=%s" % (colID, rnkID)) except StandardError, e: return "" return "true" def delete_rnk(rnkID): """Deletes all data for the given rank method rnkID - delete all data in the tables associated with ranking and this id """ try: res = run_sql("DELETE FROM rnkMETHOD WHERE id=%s" % rnkID) res = run_sql("DELETE FROM rnkMETHODNAME WHERE id_rnkMETHOD=%s" % rnkID) res = run_sql("DELETE FROM collection_rnkMETHOD WHERE id_rnkMETHOD=%s" % rnkID) res = run_sql("DELETE FROM rnkSET WHERE id_rnkMETHOD=%s" % rnkID) return "true" except StandardError, e: return "" def modify_rnk(rnkID, rnkcode): """change the code for the rank method given rnkID - change in rnkMETHOD where id is like this rnkcode - new value for field 'name' in rnkMETHOD """ try: res = run_sql("UPDATE rnkMETHOD set name='%s' WHERE id=%s" % (MySQLdb.escape_string(rnkcode), rnkID)) return "true" except StandardError, e: return "" def add_rnk(rnkcode): """Adds a new rank method to rnkMETHOD rnkcode - the "code" for the rank method, to be used by bibrank daemon """ try: res = run_sql("INSERT INTO rnkMETHOD(name) VALUES('%s')" % MySQLdb.escape_string(rnkcode)) res = run_sql("SELECT id FROM rnkMETHOD WHERE name='%s'" % MySQLdb.escape_string(rnkcode)) return res except StandardError, e: return "" def addadminbox(header='', datalist=[], cls="admin_wvar"): """used to create table around main data on a page, row based. header - header on top of the table datalist - list of the data to be added row by row cls - possible to select wich css-class to format the look of the table.""" if len(datalist) == 1: per = '100' else: per = '75' output = '\n' output += """ """ % (len(datalist), header) output += ' \n' output += """ """ % (per+'%', datalist[0]) if len(datalist) > 1: output += """ """ % ('25%', datalist[1]) output += ' \n' output += """
%s
%s %s
""" return output def tupletotable(header=[], tuple=[], start='', end='', extracolumn=''): """create html table for a tuple. header - optional header for the columns tuple - create table of this start - text to be added in the beginning, most likely beginning of a form end - text to be added in the end, mot likely end of a form. extracolumn - mainly used to put in a button. """ # study first row in tuple for alignment align = [] try: firstrow = tuple[0] if type(firstrow) in [int, long]: align = ['admintdright'] elif type(firstrow) in [str, dict]: align = ['admintdleft'] else: for item in firstrow: try: align.append(type(int(item)) is int and 'admintdright') except ValueError: align.append('admintdleft') except IndexError: firstrow = [] tblstr = '' for h in header + ['']: tblstr += ' %s\n' % (h, ) if tblstr: tblstr = ' \n%s\n \n' % (tblstr, ) tblstr = start + '\n' + tblstr # extra column try: extra = '' if type(firstrow) not in [int, long, str, dict]: # for data in firstrow: extra += '\n' % ('admintd', data) for i in range(len(firstrow)): extra += '\n' % (align[i], firstrow[i]) else: extra += ' \n' % (align[0], firstrow) extra += '\n\n' % (len(tuple), extracolumn) except IndexError: extra = '' tblstr += extra # for i in range(1, len(tuple)): for row in tuple[1:]: tblstr += ' \n' # row = tuple[i] if type(row) not in [int, long, str, dict]: # for data in row: tblstr += '\n' % (data,) for i in range(len(row)): tblstr += '\n' % (align[i], row[i]) else: tblstr += ' \n' % (align[0], row) tblstr += ' \n' tblstr += '
%s%s%s\n%s\n
%s%s%s
\n ' tblstr += end return tblstr def tupletotable_onlyselected(header=[], tuple=[], selected=[], start='', end='', extracolumn=''): """create html table for a tuple. header - optional header for the columns tuple - create table of this selected - indexes of selected rows in the tuple start - put this in the beginning end - put this in the beginning extracolumn - mainly used to put in a button""" tuple2 = [] for index in selected: tuple2.append(tuple[int(index)-1]) return tupletotable(header=header, tuple=tuple2, start=start, end=end, extracolumn=extracolumn) def addcheckboxes(datalist=[], name='authids', startindex=1, checked=[]): """adds checkboxes in front of the listdata. datalist - add checkboxes in front of this list name - name of all the checkboxes, values will be associated with this name startindex - usually 1 because of the header checked - values of checkboxes to be pre-checked """ if not type(checked) is list: checked = [checked] for row in datalist: if 1 or row[0] not in [-1, "-1", 0, "0"]: # always box, check another place chkstr = str(startindex) in checked and 'checked="checked"' or '' row.insert(0, '' % (name, startindex, chkstr)) else: row.insert(0, '') startindex += 1 return datalist def createhiddenform(action="", text="", button="confirm", cnfrm='', **hidden): """create select with hidden values and submit button action - name of the action to perform on submit text - additional text, can also be used to add non hidden input button - value/caption on the submit button cnfrm - if given, must check checkbox to confirm **hidden - dictionary with name=value pairs for hidden input """ output = '
\n' % (action, ) output += '\n
' output += text if cnfrm: output += ' ' for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += ' \n' % (key, value) else: output += ' \n' % (key, hidden[key]) output += '' output += ' \n' % (button, ) output += '
' output += '
\n' return output def adderrorbox(header='', datalist=[]): """used to create table around main data on a page, row based""" try: perc= str(100 // len(datalist)) + '%' except ZeroDivisionError: perc= 1 output = '' output += '' % (len(datalist), header) output += '' for row in [datalist]: output += '' for data in row: output += '' output += '' output += '
%s
' % (perc, ) output += data output += '
' return output def serialize_via_numeric_array_dumps(arr): return Numeric.dumps(arr) def serialize_via_numeric_array_compr(str): return compress(str) def serialize_via_numeric_array_escape(str): return MySQLdb.escape_string(str) def serialize_via_numeric_array(arr): """Serialize Numeric array into a compressed string.""" return serialize_via_numeric_array_escape(serialize_via_numeric_array_compr(serialize_via_numeric_array_dumps(arr))) def deserialize_via_numeric_array(string): """Decompress and deserialize string into a Numeric array.""" return Numeric.loads(decompress(string)) def serialize_via_marshal(obj): """Serialize Python object via marshal into a compressed string.""" return MySQLdb.escape_string(compress(dumps(obj))) def deserialize_via_marshal(string): """Decompress and deserialize string into a Python object via marshal.""" return loads(decompress(string)) def get_languages(): languages = [] for (lang, lang_namelong) in <: print generate_language_list_for_python("long"); :>: languages.append((lang, lang_namelong)) languages.sort() return languages def get_current_name(ID, ln, rtype, table): """Returns a list of the names, either with the name in the current language, the default language, or just the name from the given table ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn'""" name = "name" if table == "rnkMETHOD": name = "NAME" try: res = "" if ID: res = run_sql("SELECT id_%s,value FROM %s%s where type='%s' and ln='%s' and id_%s=%s" % (table, table, name, rtype,ln, table, ID)) else: res = run_sql("SELECT id_%s,value FROM %s%s where type='%s' and ln='%s'" % (table, table, name, rtype,ln)) if ln != cdslang: if ID: res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s' and id_%s=%s" % (table, table, name, cdslang, rtype, table, ID)) else: res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s'" % (table, table, name, cdslang, rtype)) res2 = dict(res) result = filter(lambda x: not res2.has_key(x[0]), res1) res = res + result if ID: res1 = run_sql("SELECT id,name FROM %s where id=%s" % (table, ID)) else: res1 = run_sql("SELECT id,name FROM %s" % table) res2 = dict(res) result = filter(lambda x: not res2.has_key(x[0]), res1) res = res + result res = list(res) res.sort(compare_on_val) return res except StandardError, e: raise StandardError def get_name(ID, ln, rtype, table): """Returns the value from the table name based on arguments ID - id ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn' table - tablename""" name = "name" if table == "rnkMETHOD": name = "NAME" try: res = run_sql("SELECT value FROM %s%s WHERE type='%s' and ln='%s' and id_%s=%s" % (table, name, rtype, ln, table, ID)) return res except StandardError, e: return () def modify_translations(ID, langs, sel_type, trans, table): """add or modify translations in tables given by table frmID - the id of the format from the format table sel_type - the name type langs - the languages trans - the translations, in same order as in langs table - the table""" try: for nr in range(0,len(langs)): res = run_sql("SELECT value FROM %sname WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, table, ID, sel_type, langs[nr][0])) if res: if trans[nr]: res = run_sql("UPDATE %sname SET value='%s' WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, MySQLdb.escape_string(trans[nr]), table, ID, sel_type, langs[nr][0])) else: res = run_sql("DELETE FROM %sname WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, table, ID, sel_type, langs[nr][0])) else: if trans[nr]: res = run_sql("INSERT INTO %sname(id_%s, type, ln, value) VALUES (%s,'%s','%s','%s')" % (table, table, ID, sel_type, langs[nr][0], MySQLdb.escape_string(trans[nr]))) return "true" except StandardError, e: return "" diff --git a/modules/bibrank/lib/bibrankadminlib.py.wml b/modules/bibrank/lib/bibrankadminlib.py.wml index 2698546d4..e9af179c1 100644 --- a/modules/bibrank/lib/bibrankadminlib.py.wml +++ b/modules/bibrank/lib/bibrankadminlib.py.wml @@ -1,1087 +1,1092 @@ ## Administrator interface for BibRank ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## read config variables: #include "config.wml" #include "configbis.wml" #include "cdswmllib.wml" ## $Id$ ## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES. """CDSware BibRank Administrator Interface.""" __lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>""" ## fill config variables: import access_control_engine as acce import cgi import re import MySQLdb import Numeric import os from zlib import compress,decompress from messages import * from dbquery import run_sql from config import * from webpage import page, pageheaderonly, pagefooteronly from webuser import getUid, get_email from mod_python import apache __version__ = "$Id$" def getnavtrail(previous = ''): navtrail = """Admin Area > BibRank Admin """ % (weburl, weburl) navtrail = navtrail + previous return navtrail def check_user(uid, role, adminarea=2, authorized=0): if not authorized and not is_adminuser(uid, role): return "false" def is_adminuser(uid, role): """check if user is a registered administrator. """ return acce.acc_authorize_action(uid, role) def perform_index(ln=cdslang): """create the bibrank main area menu page.""" header = ['Name', 'Translations', 'Collections', 'Rank method'] rnk_list = get_current_name('', ln, get_rnk_nametypes()[0][0], "rnkMETHOD") actions = [] for (rnkID, name) in rnk_list: actions.append([name]) for col in [(('Modify', 'modifytranslations'),), (('Modify', 'modifycollection'),), (('Show Details', 'showrankdetails'), ('Modify', 'modifyrank'), ('Delete', 'deleterank'))]: actions[-1].append('%s' % (weburl, col[0][1], rnkID, ln, col[0][0])) for (str, function) in col[1:]: actions[-1][-1] += ' / %s' % (weburl, function, rnkID, ln, str) output = """ Add new rank method

""" % (weburl, ln) output += tupletotable(header=header, tuple=actions) - return addadminbox("""Overview of rank methodss   [?]""" % weburl, datalist=[output, '']) + return addadminbox("""Overview of rank methods   [?]""" % weburl, datalist=[output, '']) def perform_modifycollection(rnkID='', ln=cdslang, func='', colID='', confirm=0): """Modify which collections the rank method is visible to""" output = "" subtitle = "" if rnkID: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] if func in ["0", 0] and confirm in ["1", 1]: finresult = attach_col_rnk(rnkID, colID) elif func in ["1", 1] and confirm in ["1", 1]: finresult = detach_col_rnk(rnkID, colID) if colID: colNAME = get_current_name(colID, ln, get_col_nametypes()[0][0], "collection")[0][1] subtitle = """Step 1 - Select collection to enable/disable rank method '%s' for""" % rnkNAME output = """
The rank method is currently enabled for these collections:
""" col_list = get_rnk_col(rnkID, ln) if not col_list: output += """No collections""" else: for (id, name) in col_list: output += """%s, """ % name output += """
""" col_list = get_current_name('', ln, get_col_nametypes()[0][0], "collection") col_rnk = dict(get_rnk_col(rnkID)) col_list = filter(lambda x: not col_rnk.has_key(x[0]), col_list) if col_list: text = """ Enable for: """ output += createhiddenform(action="modifycollection", text=text, button="Enable", rnkID=rnkID, ln=ln, func=0, - confirm=0) + confirm=1) if confirm in ["0", 0] and func in ["0", 0] and colID: subtitle = "Step 2 - Confirm to enable rank method for the chosen collection" text = "

Please confirm to enable rank method '%s' for the collection '%s'

" % (rnkNAME, colNAME) output += createhiddenform(action="modifycollection", text=text, button="Confirm", rnkID=rnkID, ln=ln, colID=colID, func=0, confirm=1) elif confirm in ["1", 1] and func in ["0", 0] and colID: subtitle = "Step 3 - Result" if finresult: output += """Rank method '%s' enabled for collection '%s'""" % (rnkNAME, colNAME) else: output += """Rank method '%s' could not be enabled for collection '%s'""" % (rnkNAME[0], colNAME) - + elif confirm not in ["0", 0] and func in ["0", 0]: + output += """Please select a collection.""" + col_list = get_rnk_col(rnkID, ln) if col_list: text = """ Disable for: """ output += createhiddenform(action="modifycollection", text=text, button="Disable", rnkID=rnkID, ln=ln, func=1, - confirm=0) + confirm=1) if confirm in ["0", 0] and func in ["1", 1] and colID: subtitle = "Step 2 - Confirm to disable rank method for collection" text = "

Please confirm to disable rank method '%s' for collection '%s'

" % (rnkNAME, colNAME) output += createhiddenform(action="modifycollection", text=text, button="Confirm", rnkID=rnkID, ln=ln, colID=colID, func=1, confirm=1) elif confirm in ["1", 1] and func in ["1", 1] and colID: subtitle = "Step 3 - Result" if finresult: output += """Rank method '%s' disabled for collection '%s'""" % (rnkNAME, colNAME) else: output += """Rank method '%s' could not be disabled for collection '%s'""" % (rnkNAME, colNAME) + elif confirm not in ["0", 0] and func in ["1", 1]: + output += """Please select a collection.""" try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_modifytranslations(rnkID, ln, sel_type, trans, confirm, callback='yes'): """Modify the translations of a rank method""" output = '' subtitle = '' cdslangs = get_languages() cdslangs.sort() if confirm in ["2", 2] and rnkID: finresult = modify_translations(rnkID, cdslangs, sel_type, trans, "rnkMETHOD") rnk_dict = dict(get_current_name('', ln, get_rnk_nametypes()[0][0], "rnkMETHOD")) if rnkID and rnk_dict.has_key(int(rnkID)): rnkID = int(rnkID) subtitle = """3. Modify translations for rank method '%s'""" % rnk_dict[rnkID] if type(trans) is str: trans = [trans] if sel_type == '': sel_type = get_rnk_nametypes()[0][0] header = ['Language', 'Translation'] actions = [] text = """ Name type """ output += createhiddenform(action="modifytranslations", text=text, button="Select", rnkID=rnkID, ln=ln, confirm=0) if confirm in [-1, "-1", 0, "0"]: trans = [] for key, value in cdslangs: try: trans_names = get_name(rnkID, key, sel_type, "rnkMETHOD") trans.append(trans_names[0][0]) except StandardError, e: trans.append('') for nr in range(0,len(cdslangs)): actions.append(["%s %s" % (cdslangs[nr][1], (cdslangs[nr][0]==cdslang and '(def)' or ''))]) actions[-1].append('' % trans[nr]) text = tupletotable(header=header, tuple=actions) output += createhiddenform(action="modifytranslations", text=text, button="Modify", rnkID=rnkID, sel_type=sel_type, ln=ln, - confirm=1) + confirm=2) if sel_type and len(trans): if confirm in ["1", 1]: text = """Please confirm modification of translations for rank method '%s'.""" % (rnk_dict[rnkID]) output += createhiddenform(action="modifytranslations", text=text, button="Confirm", rnkID=rnkID, sel_type=sel_type, trans=trans, ln=ln, confirm=2) elif confirm in ["2", 2]: if finresult: output += """Translations modified for rank method '%s'.""" % (rnk_dict[rnkID]) else: output += """Sorry, could not modify translations for rank method '%s'.""" % (rnk_dict[rnkID]) try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_addrankarea(rnkcode='', ln=cdslang, template='', confirm=-1): """form to add a new rank method with these values: """ subtitle = 'Step 1 - Create new rank method' output = """
BibRank code:
A unique code that identifies a rank method, is used when running the bibrank daemon and used to name the configuration file for the method.
The template files includes the necessary parameters for the chosen rank method, and only needs to be edited with the correct tags and paths.
For more information, please go to the BibRank guide and read the section about adding a rank method
""" % weburl text = """ BibRank code """ % (rnkcode) text += """
Cfg template """ output += createhiddenform(action="addrankarea", text=text, button="Add rank method", ln=ln, - confirm=0) + confirm=1) if rnkcode: if confirm in ["0", 0]: subtitle = 'Step 2 - Confirm addition of rank method' text = """Add rank method with BibRank code: '%s'.""" % (rnkcode) if template: text += """
Using configuration template: '%s'.""" % (template) else: text += """
Create empty configuration file.""" output += createhiddenform(action="addrankarea", text=text, rnkcode=rnkcode, button="Confirm", template=template, confirm=1) elif confirm in ["1", 1]: rnkID = add_rnk(rnkcode) subtitle = "Step 3 - Result" if rnkID: rnkID = rnkID[0] text = """Added new rank method with BibRank code '%s'""" % rnkcode try: if template: infile = open("%s/bibrank/%s" % (etcdir, template), 'r') indata = infile.readlines() infile.close() else: indata = () file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0]), 'w') for line in indata: file.write(line) file.close() if template: text += """
Configuration file created using '%s' as template.
""" % template else: text += """
Empty configuration file created.
""" except StandardError, e: text += """
Sorry, could not create configuration file: '%s/bibrank/%s.cfg', either because it already exists, or not enough rights to create file.
Please create the file in the path given.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) else: text = """Sorry, could not add rank method, rank method with the same BibRank code probably exists.""" output += text - elif not rnkcode and confirm in ["0", 0]: + elif not rnkcode and confirm not in [-1, "-1"]: output += """Sorry, could not add rank method, not enough data submitted.""" try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_modifyrank(rnkID, rnkcode='', ln=cdslang, template='', cfgfile='', confirm=0): """form to modify a rank method rnkID - id of the rank method """ subtitle = 'Step 1 - Please modify the wanted values below' if not rnkcode: oldcode = get_rnk_code(rnkID)[0] else: oldcode = rnkcode output = """
When changing the BibRank code of a rank method, you must also change any scheduled tasks using the old value.
For more information, please go to the BibRank guide and read the section about modifying a rank method's BibRank code.
""" % weburl text = """ BibRank code
""" % (oldcode) try: text += """Cfg file""" textarea = "" if cfgfile: textarea +=cfgfile else: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0])) for line in file.readlines(): textarea += line text += """""" except StandardError, e: text += """Cannot load file, either it does not exist, or not enough rights to read it: '%s/bibrank/%s.cfg'
Please create the file in the path given.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, button="Modify", - confirm=0) + confirm=1) text = "" if rnkcode and confirm in ["0", 0] and get_rnk_code(rnkID)[0][0] != rnkcode: subtitle = 'Step 2 - Confirm modification of configuration' text += "Modify rank method '%s' with old code '%s' and set new code '%s'." % (get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][0], get_rnk_code(rnkID)[0][0], rnkcode) if cfgfile and confirm in ["0", 0]: subtitle = 'Step 2 - Confirm modification of configuration' text += "
Modify configuration file" if (rnkcode or cfgfile) and confirm in ["0", 0] and not template: output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, rnkcode=rnkcode, cfgfile=cfgfile, button="Confirm", confirm=1) if rnkcode and confirm in ["1", 1] and get_rnk_code(rnkID)[0][0] != rnkcode: oldcode = get_rnk_code(rnkID)[0][0] result = modify_rnk(rnkID, rnkcode) subtitle = "Step 3 - Result" if result: text = """Rank method '%s' modified, new code is '%s'.""" % (get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][0], rnkcode) try: file = open("%s/bibrank/%s.cfg" % (etcdir, oldcode), 'r') file2 = open("%s/bibrank/%s.cfg" % (etcdir, rnkcode), 'w') lines = file.readlines() for line in lines: file2.write(line) file.close() file2.close() os.remove("%s/bibrank/%s.cfg" % (etcdir, oldcode)) except StandardError, e: text = """Sorry, could not change name of cfg file, must be done manually: '%s/bibrank/%s.cfg'""" % (etcdir, oldcode) else: text = """Sorry, could not modify rank method.""" output += text if cfgfile and confirm in ["1", 1]: try: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0]), 'w') file.write(cfgfile) file.close() text = """
Configuration file modified: '%s/bibrank/%s.cfg'
""" % (etcdir, get_rnk_code(rnkID)[0][0]) except StandardError, e: text = """
Sorry, could not modify configuration file, please check for rights to do so: '%s/bibrank/%s.cfg'
Please modify the file manually.
""" % (etcdir, get_rnk_code(rnkID)[0][0]) output += text finoutput = addadminbox(subtitle + """   [?]""" % weburl, [output]) output = "" text = """ Select
""" output += createhiddenform(action="modifyrank", text=text, rnkID=rnkID, button="Show template", confirm=0) try: if template: textarea = "" text = """Content:""" file = open("%s/bibrank/%s" % (etcdir, template), 'r') lines = file.readlines() for line in lines: textarea += line file.close() text += """""" output += text except StandardError, e: output += """Cannot load file, either it does not exist, or not enough rights to read it: '%s/bibrank/%s'""" % (etcdir, template) finoutput += addadminbox("View templates", [output]) return finoutput def perform_deleterank(rnkID, ln=cdslang, confirm=0): """form to delete a rank method """ subtitle ='' output = """
WARNING:
When deleting a rank method, you also deletes all data related to the rank method, like translations, which collections it was attached to and the data necessary to rank the searchresults. Any scheduled tasks using the deleted rank method will also stop working.

For more information, please go to the BibRank guide and read the section regarding deleting a rank method.
""" % weburl if rnkID: if confirm in ["0", 0]: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] subtitle = 'Step 1 - Confirm deletion' text = """Delete rank method '%s'.""" % (rnkNAME) output += createhiddenform(action="deleterank", text=text, + button="Confirm", rnkID=rnkID, confirm=1) elif confirm in ["1", 1]: try: rnkNAME = get_current_name(rnkID, ln, get_rnk_nametypes()[0][0], "rnkMETHOD")[0][1] rnkcode = get_rnk_code(rnkID)[0][0] result = delete_rnk(rnkID) subtitle = "Step 2 - Result" if result: text = """Rank method '%s' deleted""" % rnkNAME try: os.remove("%s/bibrank/%s.cfg" % (etcdir, rnkcode)) text += """
Configuration file deleted: '%s/bibrank/%s.cfg'.""" % (etcdir, rnkcode) except StandardError, e: text += """
Sorry, could not delete configuration file: '%s/bibrank/%s.cfg'.
Please delete the file manually.
""" % (etcdir, rnkcode) else: text = """Sorry, could not delete rank method '%s'""" % rnkNAME except StandardError, e: text = """Sorry, could not delete rank method, most likely already deleted""" output = text try: body = [output, extra] except NameError: body = [output] return addadminbox(subtitle + """   [?]""" % weburl, body) def perform_showrankdetails(rnkID, ln=cdslang): """Returns details about the rank method given by rnkID""" subtitle = """Overview [Modify]""" % (weburl, rnkID, ln) text = """ BibRank code: %s
Last updated by BibRank: """ % (get_rnk_code(rnkID)[0][0]) if get_rnk(rnkID)[0][2]: text += "%s
" % get_rnk(rnkID)[0][2] else: text += "Not yet run.
" output = addadminbox(subtitle, [text]) subtitle = """Rank method sets""" text = "" try: threshold = deserialize_via_numeric_array(get_rnk(rnkID)[0][3]) res = get_rnk_set(rnkID) for i in range(0, len(res)): set = deserialize_via_numeric_array(res[i][2]) text += "Star %s : %s (Threshold: %s)
" % (res[i][1], set._nbhits, threshold[res[i][1]]) except StandardError, e: text = "BibRank not yet run, cannot show sets" output += addadminbox(subtitle, [text]) subtitle = """Attached to collections [Modify]""" % (weburl, rnkID, ln) text = "" col = get_rnk_col(rnkID, ln) for key, value in col: text+= "%s
" % value if not col: text +="No collections" output += addadminbox(subtitle, [text]) subtitle = """Translations [Modify]""" % (weburl, rnkID, ln) prev_lang = '' trans = get_translations(rnkID) types = get_rnk_nametypes() types = dict(map(lambda x: (x[0], x[1]), types)) text = "" languages = dict(get_languages()) if trans: for lang, type, name in trans: if lang and type and name: if prev_lang != lang: prev_lang = lang text += """%s:
""" % (languages[lang]) if types.has_key(type): text+= """'%s'(%s)
""" % (name, types[type]) else: text = """No translations exists""" output += addadminbox(subtitle, [text]) subtitle = """Configuration file: '%s/bibrank/%s.cfg' [Modify]""" % (etcdir, get_rnk_code(rnkID)[0][0], weburl, rnkID, ln) text = "" try: file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnk_code(rnkID)[0][0])) text += """
"""
         for line in file.readlines():
             text += line
         text += """
""" except StandardError, e: text = """Cannot load file, either it does not exist, or not enough rights to read it.""" output += addadminbox(subtitle, [text]) return output def compare_on_val(second, first): return cmp(second[1], first[1]) def get_rnk_code(rnkID): """Returns the name from rnkMETHOD based on argument rnkID - id from rnkMETHOD""" try: res = run_sql("SELECT name FROM rnkMETHOD where id=%s" % (rnkID)) return res except StandardError, e: return () def get_rnk(rnkID=''): """Return one or all rank methods rnkID - return the rank method given, or all if not given""" try: if rnkID: res = run_sql("SELECT id,name,last_updated,star_category_ranges from rnkMETHOD WHERE id=%s" % rnkID) else: res = run_sql("SELECT id,name,last_updated,star_category_ranges from rnkMETHOD") return res except StandardError, e: return () def get_translations(rnkID): """Returns the translations in rnkMETHODNAME for a rankmethod rnkID - the id of the rankmethod from rnkMETHOD """ try: res = run_sql("SELECT ln, type, value FROM rnkMETHODNAME where id_rnkMETHOD=%s ORDER BY ln,type" % (rnkID)) return res except StandardError, e: return () def get_rnk_nametypes(): """Return a list of the various translationnames for the rank methods""" type = [] type.append(('ln', 'Long name')) type.append(('sn', 'Short name')) return type def get_col_nametypes(): """Return a list of the various translationnames for the rank methods""" type = [] type.append(('ln', 'Long name')) return type def get_rnk_set(rnkID=''): """Return all rank sets, or all for a specified rank method rnkID = if given, return rank sets of specified rank method, if not, return all. """ try: if rnkID: res = run_sql("SELECT id_rnkMETHOD,star_category,hitset from rnkSET WHERE id_rnkMETHOD=%s ORDER BY star_category" % rnkID) else: res = run_sql("SELECT id_rnkMETHOD,star_category,hitset from rnkSET order by id_rnkMETHOD,starcategory") return res except StandardError, e: return () def get_rnk_col(rnkID, ln=cdslang): """ Returns a list of the collections the given rank method is attached to rnkID - id from rnkMETHOD""" try: res1 = dict(run_sql("SELECT id_collection, '' FROM collection_rnkMETHOD WHERE id_rnkMETHOD=%s" % rnkID)) res2 = get_current_name('',ln, get_col_nametypes()[0][0], "collection") result = filter(lambda x: res1.has_key(x[0]), res2) return result except StandardError, e: return () def get_templates(): """Read etcdir/bibrank and returns a list of all files with 'template' """ templates = [] files = os.listdir(etcdir + "/bibrank/") for file in files: if str.find(file,"template_") != -1: templates.append(file) return templates def attach_col_rnk(rnkID, colID): """attach rank method to collection rnkID - id from rnkMETHOD table colID - id of collection, as in collection table """ try: res = run_sql("INSERT INTO collection_rnkMETHOD(id_collection, id_rnkMETHOD) values (%s,%s)" % (colID, rnkID)) return "true" except StandardError, e: return "" def detach_col_rnk(rnkID, colID): """detach rank method from collection rnkID - id from rnkMETHOD table colID - id of collection, as in collection table """ try: res = run_sql("DELETE FROM collection_rnkMETHOD WHERE id_collection=%s AND id_rnkMETHOD=%s" % (colID, rnkID)) except StandardError, e: return "" return "true" def delete_rnk(rnkID): """Deletes all data for the given rank method rnkID - delete all data in the tables associated with ranking and this id """ try: res = run_sql("DELETE FROM rnkMETHOD WHERE id=%s" % rnkID) res = run_sql("DELETE FROM rnkMETHODNAME WHERE id_rnkMETHOD=%s" % rnkID) res = run_sql("DELETE FROM collection_rnkMETHOD WHERE id_rnkMETHOD=%s" % rnkID) res = run_sql("DELETE FROM rnkSET WHERE id_rnkMETHOD=%s" % rnkID) return "true" except StandardError, e: return "" def modify_rnk(rnkID, rnkcode): """change the code for the rank method given rnkID - change in rnkMETHOD where id is like this rnkcode - new value for field 'name' in rnkMETHOD """ try: res = run_sql("UPDATE rnkMETHOD set name='%s' WHERE id=%s" % (MySQLdb.escape_string(rnkcode), rnkID)) return "true" except StandardError, e: return "" def add_rnk(rnkcode): """Adds a new rank method to rnkMETHOD rnkcode - the "code" for the rank method, to be used by bibrank daemon """ try: res = run_sql("INSERT INTO rnkMETHOD(name) VALUES('%s')" % MySQLdb.escape_string(rnkcode)) res = run_sql("SELECT id FROM rnkMETHOD WHERE name='%s'" % MySQLdb.escape_string(rnkcode)) return res except StandardError, e: return "" def addadminbox(header='', datalist=[], cls="admin_wvar"): """used to create table around main data on a page, row based. header - header on top of the table datalist - list of the data to be added row by row cls - possible to select wich css-class to format the look of the table.""" if len(datalist) == 1: per = '100' else: per = '75' output = '\n' output += """ """ % (len(datalist), header) output += ' \n' output += """ """ % (per+'%', datalist[0]) if len(datalist) > 1: output += """ """ % ('25%', datalist[1]) output += ' \n' output += """
%s
%s %s
""" return output def tupletotable(header=[], tuple=[], start='', end='', extracolumn=''): """create html table for a tuple. header - optional header for the columns tuple - create table of this start - text to be added in the beginning, most likely beginning of a form end - text to be added in the end, mot likely end of a form. extracolumn - mainly used to put in a button. """ # study first row in tuple for alignment align = [] try: firstrow = tuple[0] if type(firstrow) in [int, long]: align = ['admintdright'] elif type(firstrow) in [str, dict]: align = ['admintdleft'] else: for item in firstrow: try: align.append(type(int(item)) is int and 'admintdright') except ValueError: align.append('admintdleft') except IndexError: firstrow = [] tblstr = '' for h in header + ['']: tblstr += ' %s\n' % (h, ) if tblstr: tblstr = ' \n%s\n \n' % (tblstr, ) tblstr = start + '\n' + tblstr # extra column try: extra = '' if type(firstrow) not in [int, long, str, dict]: # for data in firstrow: extra += '\n' % ('admintd', data) for i in range(len(firstrow)): extra += '\n' % (align[i], firstrow[i]) else: extra += ' \n' % (align[0], firstrow) extra += '\n\n' % (len(tuple), extracolumn) except IndexError: extra = '' tblstr += extra # for i in range(1, len(tuple)): for row in tuple[1:]: tblstr += ' \n' # row = tuple[i] if type(row) not in [int, long, str, dict]: # for data in row: tblstr += '\n' % (data,) for i in range(len(row)): tblstr += '\n' % (align[i], row[i]) else: tblstr += ' \n' % (align[0], row) tblstr += ' \n' tblstr += '
%s%s%s\n%s\n
%s%s%s
\n ' tblstr += end return tblstr def tupletotable_onlyselected(header=[], tuple=[], selected=[], start='', end='', extracolumn=''): """create html table for a tuple. header - optional header for the columns tuple - create table of this selected - indexes of selected rows in the tuple start - put this in the beginning end - put this in the beginning extracolumn - mainly used to put in a button""" tuple2 = [] for index in selected: tuple2.append(tuple[int(index)-1]) return tupletotable(header=header, tuple=tuple2, start=start, end=end, extracolumn=extracolumn) def addcheckboxes(datalist=[], name='authids', startindex=1, checked=[]): """adds checkboxes in front of the listdata. datalist - add checkboxes in front of this list name - name of all the checkboxes, values will be associated with this name startindex - usually 1 because of the header checked - values of checkboxes to be pre-checked """ if not type(checked) is list: checked = [checked] for row in datalist: if 1 or row[0] not in [-1, "-1", 0, "0"]: # always box, check another place chkstr = str(startindex) in checked and 'checked="checked"' or '' row.insert(0, '' % (name, startindex, chkstr)) else: row.insert(0, '') startindex += 1 return datalist def createhiddenform(action="", text="", button="confirm", cnfrm='', **hidden): """create select with hidden values and submit button action - name of the action to perform on submit text - additional text, can also be used to add non hidden input button - value/caption on the submit button cnfrm - if given, must check checkbox to confirm **hidden - dictionary with name=value pairs for hidden input """ output = '
\n' % (action, ) output += '\n
' output += text if cnfrm: output += ' ' for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += ' \n' % (key, value) else: output += ' \n' % (key, hidden[key]) output += '' output += ' \n' % (button, ) output += '
' output += '
\n' return output def adderrorbox(header='', datalist=[]): """used to create table around main data on a page, row based""" try: perc= str(100 // len(datalist)) + '%' except ZeroDivisionError: perc= 1 output = '' output += '' % (len(datalist), header) output += '' for row in [datalist]: output += '' for data in row: output += '' output += '' output += '
%s
' % (perc, ) output += data output += '
' return output def serialize_via_numeric_array_dumps(arr): return Numeric.dumps(arr) def serialize_via_numeric_array_compr(str): return compress(str) def serialize_via_numeric_array_escape(str): return MySQLdb.escape_string(str) def serialize_via_numeric_array(arr): """Serialize Numeric array into a compressed string.""" return serialize_via_numeric_array_escape(serialize_via_numeric_array_compr(serialize_via_numeric_array_dumps(arr))) def deserialize_via_numeric_array(string): """Decompress and deserialize string into a Numeric array.""" return Numeric.loads(decompress(string)) def serialize_via_marshal(obj): """Serialize Python object via marshal into a compressed string.""" return MySQLdb.escape_string(compress(dumps(obj))) def deserialize_via_marshal(string): """Decompress and deserialize string into a Python object via marshal.""" return loads(decompress(string)) def get_languages(): languages = [] for (lang, lang_namelong) in <: print generate_language_list_for_python("long"); :>: languages.append((lang, lang_namelong)) languages.sort() return languages def get_current_name(ID, ln, rtype, table): """Returns a list of the names, either with the name in the current language, the default language, or just the name from the given table ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn'""" name = "name" if table == "rnkMETHOD": name = "NAME" try: res = "" if ID: res = run_sql("SELECT id_%s,value FROM %s%s where type='%s' and ln='%s' and id_%s=%s" % (table, table, name, rtype,ln, table, ID)) else: res = run_sql("SELECT id_%s,value FROM %s%s where type='%s' and ln='%s'" % (table, table, name, rtype,ln)) if ln != cdslang: if ID: res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s' and id_%s=%s" % (table, table, name, cdslang, rtype, table, ID)) else: res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s'" % (table, table, name, cdslang, rtype)) res2 = dict(res) result = filter(lambda x: not res2.has_key(x[0]), res1) res = res + result if ID: res1 = run_sql("SELECT id,name FROM %s where id=%s" % (table, ID)) else: res1 = run_sql("SELECT id,name FROM %s" % table) res2 = dict(res) result = filter(lambda x: not res2.has_key(x[0]), res1) res = res + result res = list(res) res.sort(compare_on_val) return res except StandardError, e: raise StandardError def get_name(ID, ln, rtype, table): """Returns the value from the table name based on arguments ID - id ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn' table - tablename""" name = "name" if table == "rnkMETHOD": name = "NAME" try: res = run_sql("SELECT value FROM %s%s WHERE type='%s' and ln='%s' and id_%s=%s" % (table, name, rtype, ln, table, ID)) return res except StandardError, e: return () def modify_translations(ID, langs, sel_type, trans, table): """add or modify translations in tables given by table frmID - the id of the format from the format table sel_type - the name type langs - the languages trans - the translations, in same order as in langs table - the table""" try: for nr in range(0,len(langs)): res = run_sql("SELECT value FROM %sname WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, table, ID, sel_type, langs[nr][0])) if res: if trans[nr]: res = run_sql("UPDATE %sname SET value='%s' WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, MySQLdb.escape_string(trans[nr]), table, ID, sel_type, langs[nr][0])) else: res = run_sql("DELETE FROM %sname WHERE id_%s=%s AND type='%s' AND ln='%s'" % (table, table, ID, sel_type, langs[nr][0])) else: if trans[nr]: res = run_sql("INSERT INTO %sname(id_%s, type, ln, value) VALUES (%s,'%s','%s','%s')" % (table, table, ID, sel_type, langs[nr][0], MySQLdb.escape_string(trans[nr]))) return "true" except StandardError, e: return ""