Page MenuHomec4science

bibrank_config.py.wml
No OneTemporary

File Metadata

Created
Fri, Sep 13, 00:49

bibrank_config.py.wml

## 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"
<protect>## $Id$</protect>
<protect>## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES.</protect>
"""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 = """<a class=navtrail href="%s/admin/">Administrator's Area</a> &gt; <a class=navtrail href="%s/admin/bibrank/">BibRank Admin</a> """ % (weburl, weburl)
navtrail = navtrail + previous
return navtrail
def check_user(uid, adminarea=2, authorized=0):
if not authorized and not is_adminuser(uid):
return "false"
def is_adminuser(uid, role = 'cfgbibrank'):
"""check if user is a registered administrator. """
return acce.acc_authorize_action(uid, role)
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 = '<table class="errorbox">'
output += '<thead><tr><th class="errorboxheader" colspan="%s">%s</th></tr></thead>' % (len(datalist), header)
output += '<tbody>'
for row in [datalist]:
output += '<tr>'
for data in row:
output += '<td style="vertical-align: top; margin-top: 5px; width: %s;">' % (perc, )
output += data
output += '</td>'
output += '</tr>'
output += '</tbody></table>'
return output
def perform_index(ln=cdslang):
"""create the bibrank main area menu page."""
header = ['Name', 'Translations', 'Collections', 'Rank method']
methods = get_rnkmethods(ln)
actions = []
for (id,name) in methods:
actions.append([name])
for col in [(('Modify', 'modifytranslation'),),
(('Modify', 'modifycollection'),),
(('Show Details', 'showrankdetails'),
('Modify', 'modifyrank'),
('Delete', 'deleterank'))]:
actions[-1].append('<a href="%s/admin/bibrank/bibrankadmin.py/%s?rnkid=%s&ln=%s">%s</a>' % (weburl, col[0][1], id, ln, col[0][0]))
for (str, function) in col[1:]:
actions[-1][-1] += ' / <a href="%s/admin/bibrank/bibrankadmin.py/%s?rnkid=%s&ln=%s">%s</a>' % (weburl, function, id, ln, str)
output = """
<dl>
<dt>Rank method:</dt>
<dd>A method responsible for creating the necessary data to rank a result.</dd>
<dt>Translations:</dt>
<dd>Each rank method may have many names in many languages.</dd>
<dt>Collections:</dt>
<dd>Which collections the rank method should be visible in.</dd>
</dl>
"""
output += tupletotable(header=header, tuple=actions)
extra = """
<dl>
<dt><a href="%s/admin/bibrank/bibrankadmin.py/addrankarea?ln=%s">Add new rank method</a>
<dd>Go here to add a new rank method.
</dl>
""" % (weburl, ln)
return addadminbox("Explanation of concepts", datalist=[output, extra])
def perform_modifycollection(rnkid='', ln=cdslang, func='', collid='', confirm=0):
"""Modify which collections the rank method is visible to"""
output = ""
subtitle = ""
if rnkid:
rnkname = get_rnkmethodname(rnkid, ln)[0]
if func in ["0", 0] and confirm in ["1", 1]:
finresult = attach_collection(rnkid, collid)
elif func in ["1", 1] and confirm in ["1", 1]:
finresult = detach_collection(rnkid, collid)
subtitle = """Step 1 - Select collection to enable/disable rank method '%s' for""" % rnkname
output = """
<dl>
<dt>Enable for:</dt>
<dd>To make the rank method visible in the search interface for a collection,
choose the wanted collection and press the "Enable" button.</dd>
<dt>Disable for:</dt>
<dd>To hide the rank method from the search interface for a collection,
choose the wanted collection and press the "Disable" button.</dd>
<dt>'%s' is currently enabled for the following collections:</dt>
""" % rnkname
coll = get_rnkmethod_collections(rnkid)
output += """<dd>"""
if not coll:
output += """No collections"""
else:
for id, name in coll:
output += """%s, """ % name
output += """</dd>"""
output += """
</dl>
"""
coll = get_collections()
coll2 = dict(get_rnkmethod_collections(rnkid))
coll = filter(lambda x: not coll2.has_key(x[0]), coll)
if coll:
text = """
<span class="adminlabel">Enable for:</span>
<select name="collid" class="admin_w200">
"""
for id, name in coll:
text += """<option value="%s" %s>%s</option>""" % (id, (func in ["0", 0] and confirm in ["0", 0] and int(collid) == int(id)) and 'selected="selected"' or '' , name)
text += """</select>"""
output += createhiddenform(action="modifycollection",
text=text,
button="Enable",
rnkid=rnkid,
ln=ln,
func=0,
confirm=0)
if confirm in ["0", 0] and func in ["0", 0]:
subtitle = "Step 2 - Confirm to enable rank method for the chosen collection"
text = "<p>Please confirm to enable rank method '%s' for the collection '%s'</p>" % (rnkname[0], get_collections(collid)[0][1])
output += createhiddenform(action="modifycollection",
text=text,
button="Confirm",
rnkid=rnkid,
ln=ln,
collid=collid,
func=0,
confirm=1)
elif confirm in ["1", 1] and func in ["0", 0]:
subtitle = "Step 3 - Result"
if finresult:
output += """<span class="info">Rank method '%s' enabled for collection '%s'</span>""" % (rnkname[0], get_collections(collid)[0][1])
else:
output += """<span class="info">Rank method '%s' could not be enabled for collection '%s'</span>""" % (rnkname[0], get_collections(collid)[0][1])
coll = get_rnkmethod_collections(rnkid)
if coll:
text = """
<span class="adminlabel">Disable for:</span>
<select name="collid" class="admin_w200">
"""
for id, name in coll:
text += """<option value="%s" %s>%s</option>""" % (id, (func in ["1", 1] and confirm in ["0", 0] and int(collid) == int(id)) and 'selected="selected"' or '' , name)
text += """</select>"""
output += createhiddenform(action="modifycollection",
text=text,
button="Disable",
rnkid=rnkid,
ln=ln,
func=1,
confirm=0)
if confirm in ["0", 0] and func in ["1", 1]:
subtitle = "Step 2 - Confirm to disable rank method for collection"
text = "<p>Please confirm to disable rank method '%s' for collection '%s'</p>" % (rnkname[0], get_collections(collid)[0][1])
output += createhiddenform(action="modifycollection",
text=text,
button="Confirm",
rnkid=rnkid,
ln=ln,
collid=collid,
func=1,
confirm=1)
elif confirm in ["1", 1] and func in ["1", 1]:
subtitle = "Step 3 - Result"
if finresult:
output += """<span class="info">Rank method '%s' disabled for collection '%s'</span>""" % (rnkname[0], get_collections(collid)[0][1])
else:
output += """<span class="info">Rank method '%s' could not be disabled for collection '%s'</span>""" % (rnkname[0], get_collections(collid)[0][1])
try:
body = [output, extra]
except NameError:
body = [output]
return addadminbox(subtitle, body)
def perform_modifytranslation(rnkid='', ln=cdslang, sel_lang='', trans=[], confirm=0):
"""Modify the translations of a rank method"""
subtitle = ""
output = ""
if rnkid:
header = ['Name type', 'Translation']
types = getnametypes()
actions = []
if confirm in ["2", 2]:
finresult = setmodifiedtranslations(rnkid, sel_lang, types, trans)
rnkname = get_rnkmethodname(rnkid, ln)[0][0]
subtitle = """Step 1 - Select language to modify for rank method: '%s'""" % rnkname
text = """
<span class="adminlabel">Language</span>
<select name="sel_lang" class="admin_w200">
"""
cdslangs = msg_home.items()
cdslangs.sort()
for key, value in cdslangs:
text += """<option value="%s" %s>%s""" % (key, key == sel_lang and 'selected="selected"' or '', str.upper(key))
trans_names = get_rnkmethodnames(rnkid, key)
if trans_names and trans_names[0][0]:
text += ": %s" % trans_names[0][0]
if key == cdslang:
text += ' [default]'
text += "</option>"
text += """</select>"""
output = createhiddenform(action="modifytranslation",
text=text,
button="Select",
rnkid=rnkid,
ln=ln,
confirm=0)
if sel_lang:
subtitle = """Step 2 - Modify translations for rank method '%s' for language: %s""" % (rnkname, str.upper(sel_lang))
if confirm in ["0", 0]:
trans = []
for col in types:
try:
trans_names = get_rnkmethodnames(rnkid, sel_lang, col[0][0])
trans.append(trans_names[0][0])
except StandardError, e:
trans.append('')
for nr in range(0,len(types)):
actions.append(["""<span class="adminlabel">""" +types[nr][0][1] + """</span>"""])
actions[-1].append('<input type="text" name="trans" size="30" value="%s"/>' % (trans[nr]))
text = tupletotable(header=header, tuple=actions)
output += createhiddenform(action="modifytranslation",
text=text,
button="Modify",
rnkid=rnkid,
sel_lang=sel_lang,
ln=ln,
confirm=1)
if confirm in ["1", 1]:
subtitle = "Step 3 - Confirm modification"
text = """<p>Please confirm modification of translations for rank method '%s' for language: %s</p>""" % (rnkname, str.upper(sel_lang))
output += createhiddenform(action="modifytranslation",
text=text,
button="Confirm",
rnkid=rnkid,
sel_lang=sel_lang,
trans=trans,
ln=ln,
confirm=2)
if confirm in ["2", 2]:
subtitle = "Step 4 - Result"
if finresult:
output += """<span class="info">Translations modified for rank method '%s' for language: %s</span>""" % (rnkname, str.upper(sel_lang))
else:
output += """<span class="info">Sorry, could not modify translations for rank method '%s' for language: %s</span>""" % (rnkname, str.upper(sel_lang))
try:
body = [output, extra]
except NameError:
body = [output]
return addadminbox(subtitle, 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 = """
<dl>
<dt>BibRank code:</dt>
<dd>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.
</br>The template files includes the necessary parameters for the chosen rank method, and only needs to be edited with the correct tags and paths.
</br>For more information, please go to the <a href="%s/admin/bibrank/guide.html">BibRank guide</a> and read the section about adding a rank method</dd>
</dl>
""" % weburl
text = """
<span class="adminlabel">BibRank code</span>
<input class="admin_wvar" type="text" name="rnkcode" value="%s" />
""" % (rnkcode)
text += """</br>
<span class="adminlabel">Cfg template</span>
<select name="template" class="admin_w200">
<option value="">No template</option>
"""
templates = get_templates()
for templ in templates:
text += """<option value="%s" %s>%s</option>""" % (templ, template == templ and 'selected="selected"' or '', templ[9:len(templ)-4])
text += """</select>"""
output += createhiddenform(action="addrankarea",
text=text,
button="Add rank method",
ln=ln,
confirm=0)
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 += """</br>Using configuration template: '%s'.""" % (template)
else:
text += """</br>Create empty configuration file."""
output += createhiddenform(action="addrankarea",
text=text,
rnkcode=rnkcode,
button="Confirm",
template=template,
confirm=1)
elif confirm in ["1", 1]:
rnkid = addRankMethod(rnkcode)
subtitle = "Step 3 - Result"
if rnkid:
rnkid = rnkid[0]
text = """<span class="info">Added new rank method with BibRank code '%s'</span>""" % 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_rnkmethodcode(rnkid)[0][0]), 'w')
for line in indata:
file.write(line)
file.close()
if template:
text += """<span class="info"></br>Configuration file created using '%s' as template.</span>""" % template
else:
text += """<span class="info"></br>Empty configuration file created.</span>"""
except StandardError, e:
text += """<span class="info"></br>Sorry, could not create configuration file: '%s/bibrank/%s.cfg', either because it already exists, or not enough rights to create file. </span>""" % (etcdir, get_rnkmethodcode(rnkid)[0][0])
text += """</br><span class="info">Please create the file in the path given.</span>"""
else:
text = """<span class="info">Sorry, could not add rank method, rank method with the same BibRank code probably exists.</span>"""
output += text
elif not rnkcode and confirm in ["0", 0]:
output += """<span class="info">Sorry, could not add rank method, not enough data submitted.</span>"""
try:
body = [output, extra]
except NameError:
body = [output]
return addadminbox(subtitle, 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_rnkmethodcode(rnkid)[0]
else:
oldcode = rnkcode
output = """
<dl>
<dd>When changing the BibRank code of a rank method, you must also change any scheduled tasks using the old value.
</br>For more information, please go to the <a href="%s/admin/bibrank/guide.html">BibRank guide</a> and read the section about modifying a rank method's BibRank code.</dd>
</dl>
""" % weburl
text = """
<span class="adminlabel">BibRank code</span>
<input class="admin_wvar" type="text" name="rnkcode" value="%s" />
</br>
""" % (oldcode)
try:
text += """<span class="adminlabel">Cfg file</span>"""
textarea = ""
if cfgfile:
textarea +=cfgfile
else:
file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnkmethodcode(rnkid)[0][0]))
for line in file.readlines():
textarea += line
text += """<textarea class="admin_wvar" name="cfgfile" rows="15" cols="70">""" + textarea + """</textarea>"""
except StandardError, e:
text += """<span class="info">Cannot load file, either it does not exist, or not enough rights to read it: '%s/bibrank/%s.cfg'</span>""" % (etcdir, get_rnkmethodcode(rnkid)[0][0])
text += """</br><span class="info">Please create the file in the path given.</span>"""
output += createhiddenform(action="modifyrank",
text=text,
rnkid=rnkid,
button="Modify",
confirm=0)
text = ""
if rnkcode and confirm in ["0", 0] and get_rnkmethodcode(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_rnkmethodname(rnkid, ln)[0][0], get_rnkmethodcode(rnkid)[0][0], rnkcode)
if cfgfile and confirm in ["0", 0]:
subtitle = 'Step 2 - Confirm modification of configuration'
text += "</br>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_rnkmethodcode(rnkid)[0][0] != rnkcode:
oldcode = get_rnkmethodcode(rnkid)[0][0]
result = modify_rankmethod(rnkid, rnkcode)
subtitle = "Step 3 - Result"
if result:
text = """<span class="info">Rank method '%s' modified, new code is '%s'.</span>""" % (get_rnkmethodname(rnkid, ln)[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 = """<span class="info">Sorry, could not change name of cfg file, must be done manually: '%s/bibrank/%s.cfg'</span>""" % (etcdir, oldcode)
else:
text = """<span class="info">Sorry, could not modify rank method.</span>"""
output += text
if cfgfile and confirm in ["1", 1]:
try:
file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnkmethodcode(rnkid)[0][0]), 'w')
file.write(cfgfile)
file.close()
text = """<span class="info"></br>Configuration file modified: '%s/bibrank/%s.cfg'</span>""" % (etcdir, get_rnkmethodcode(rnkid)[0][0])
except StandardError, e:
text = """<span class="info"></br>Sorry, could not modify configuration file, please check for rights to do so: '%s/bibrank/%s.cfg'</span>""" % (etcdir, get_rnkmethodcode(rnkid)[0][0])
text += """</br><span class="info">Please modify the file manually.</span>"""
output += text
finoutput = addadminbox(subtitle, [output])
output = ""
text = """
<span class="adminlabel">Select</span>
<select name="template" class="admin_w200">
"""
templates = get_templates()
for templ in templates:
text += """<option value="%s" %s>%s</option>""" % (templ, template == templ and 'selected="selected"' or '', templ[9:len(templ)-4])
text += """</select></br>"""
output += createhiddenform(action="modifyrank",
text=text,
rnkid=rnkid,
button="Show template",
confirm=0)
try:
if template:
textarea = ""
text = """<span class="adminlabel">Content:</span>"""
file = open("%s/bibrank/%s" % (etcdir, template), 'r')
lines = file.readlines()
for line in lines:
textarea += line
file.close()
text += """<textarea class="admin_wvar" readonly="true" rows="15" cols="70">""" + textarea + """</textarea>"""
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 = """
<span class="warning">
<strong>
<dl>
<dt>WARNING:</dt>
<dd>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.
</br></br>For more information, please go to the <a href="%s/admin/bibrank/guide.html">BibRank guide</a> and read the section regarding deleting a rank method.</dd>
</dl>
</strong>
</span>
""" % weburl
if rnkid:
if confirm in ["0", 0]:
rnkname = get_rnkmethodname(rnkid, ln)[0]
subtitle = 'Step 1 - Confirm deletion'
text = """Delete rank method '%s'.""" % (rnkname)
output += createhiddenform(action="deleterank",
text=text,
rnkid=rnkid,
confirm=1)
elif confirm in ["1", 1]:
try:
rnkname = get_rnkmethodname(rnkid, ln)[0]
rnkcode = get_rnkmethodcode(rnkid)[0][0]
result = delete_rankmethod(rnkid)
subtitle = "Step 2 - Result"
if result:
text = """<span class="info">Rank method '%s' deleted</span>""" % rnkname
try:
os.remove("%s/bibrank/%s.cfg" % (etcdir, rnkcode))
text += """</br><span class="info">Configuration file deleted: '%s/bibrank/%s.cfg'.</span>""" % (etcdir, rnkcode)
except StandardError, e:
text += """</br><span class="info">Sorry, could not delete configuration file: '%s/bibrank/%s.cfg'.</span>""" % (etcdir, rnkcode)
text += """</br><span class="info">Please delete the file manually.</span>"""
else:
text = """<span class="info">Sorry, could not delete rank method '%s'</span>""" % rnkname
except StandardError, e:
text = """<span class="info">Sorry, could not delete rank method, most likely already deleted</span>"""
output = text
try:
body = [output, extra]
except NameError:
body = [output]
return addadminbox(subtitle, body)
def perform_showrankdetails(rnkid, ln=cdslang):
"""Returns details about the rank method given by rnkid"""
subtitle = """Overview <a href="%s/admin/bibrank/bibrankadmin.py/modifyrank?rnkid=%s&ln=%s">[Modify]</a>""" % (weburl, rnkid, ln)
text = """
BibRank code: %s</br>
Last updated by BibRank:
""" % (get_rnkmethodcode(rnkid)[0][0])
if get_rnkmethod(rnkid)[0][2]:
text += "%s</br>" % get_rnkmethod(rnkid)[0][2]
else:
text += "Not yet run.</br>"
output = addadminbox(subtitle, [text])
subtitle = """Rank method sets"""
text = ""
try:
threshold = deserialize_via_numeric_array(get_rnkmethod(rnkid)[0][3])
res = get_rnkset(rnkid)
for i in range(0, len(res)):
set = deserialize_via_numeric_array(res[i][2])
text += "Star %s : %s (Threshold: %s)</br>" % (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 <a href="%s/admin/bibrank/bibrankadmin.py/modifycollection?rnkid=%s&ln=%s">[Modify]</a>""" % (weburl, rnkid, ln)
text = ""
coll = get_rnkmethod_collections(rnkid)
for key, value in coll:
text+= "%s</br>" % value
if not coll:
text +="No collections"
output += addadminbox(subtitle, [text])
subtitle = """Translations <a href="%s/admin/bibrank/bibrankadmin.py/modifytranslation?rnkid=%s&ln=%s">[Modify]</a>""" % (weburl, rnkid, ln)
prev_lang = ''
trans = get_translations(rnkid)
types = getnametypes()
types = dict(map(lambda x: (x[0][0], x[0][1]), types))
text = ""
if trans:
for lang, type, name in trans:
if lang and type and name:
if prev_lang != lang:
prev_lang = lang
text += """%s: <a href="%s/admin/bibrank/bibrankadmin.py/modifytranslation?rnkid=%s&ln=%s&sel_lang=%s">[Modify]</a></br>""" % (str.upper(lang), weburl, rnkid, ln, lang)
if types.has_key(type):
text+= """<span style="margin-left: 10px">'%s'</span><span class="note">(%s)</span></br>""" % (name, types[type])
else:
text = """No translations exists"""
output += addadminbox(subtitle, [text])
subtitle = """Configuration file: '%s/bibrank/%s.cfg' <a href="%s/admin/bibrank/bibrankadmin.py/modifyrank?rnkid=%s&ln=%s">[Modify]</a>""" % (etcdir, get_rnkmethodcode(rnkid)[0][0], weburl, rnkid, ln)
text = ""
try:
file = open("%s/bibrank/%s.cfg" % (etcdir, get_rnkmethodcode(rnkid)[0][0]))
text += """<pre>"""
for line in file.readlines():
text += line
text += """</pre>"""
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 get_rnkmethods(ln=cdslang, type=''):
"""Returns a list of all rank methods, either with the name in the current language, the default language, or just the 'code'
ln - a language supported by cdsware
type - the type of value wanted, like 'ln', 'sn'"""
if not type:
type = getmainnametype()
try:
res = run_sql("SELECT id_rnkMETHOD,value FROM rnkMETHODNAME where type='%s' and ln='%s'" % (type,ln))
if ln != cdslang:
res1 = run_sql("SELECT id_rnkMETHOD,value FROM rnkMETHODNAME WHERE ln='%s' and type='%s'" % (cdslang, type))
res2 = dict(res)
result = filter(lambda x: not res2.has_key(x[0]), res1)
res = res + result
res1 = run_sql("SELECT id,name FROM rnkMETHOD")
res2 = dict(res)
result = filter(lambda x: not res2.has_key(x[0]), res1)
res = res + result
return res
except StandardError, e:
raise StandardError
def get_rnkmethodname(rnkid,ln=cdslang, type=''):
"""Returns a name for the rankmethod. If a translation in the current language does not exist, the default language will be tried, and if not, the name from rnkMETHOD
will be returned.
rnkid - id from rnkMETHOD
ln - a language supported by cdsware
type - the type of value wanted, like 'ln', 'sn'"""
if not type:
type = getmainnametype()
try:
res = run_sql("SELECT value FROM rnkMETHODNAME where type='%s' and ln='%s' and id_rnkMETHOD=%s" % (type, ln, rnkid))
if not res:
res = run_sql("SELECT value FROM rnkMETHODNAME WHERE ln='%s' and id_rnkMETHOD=%s and type='%s'" % (cdslang, rnkid, type))
if not res:
res = run_sql("SELECT name FROM rnkMETHOD where id=%s" % rnkid)
return res
except StandardError, e:
raise StandardError
def get_rnkmethodnames(rnkid, ln, type=''):
"""Returns the value from rnkMETHODNAME based on arguments
rnkid - id from rnkMETHOD
ln - a language supported by cdsware
type - the type of value wanted, like 'ln', 'sn'"""
if not type:
type = getmainnametype()
try:
res = run_sql("SELECT value FROM rnkMETHODNAME where type='%s' and ln='%s' and id_rnkMETHOD=%s" % (type, ln, rnkid))
return res
except StandardError, e:
return ()
def get_rnkmethodcode(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_rnkmethod(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 getnametypes():
"""Return a list of the various translationnames for the rank methods"""
return [(('ln', 'Long name'),),(('sn', 'Short name'),)]
def getmainnametype():
"""Return the main/default translationname"""
return getnametypes()[0][0][0]
def get_rnkset(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_collections(collid=''):
"""Returns a list of all collections, or one specific
collid = if this is empty, return all collections, if given, return the specified collection."""
try:
if collid:
res = run_sql("SELECT id, name FROM COLLECTION WHERE id=%s" % collid)
else:
res = run_sql("SELECT id, name FROM COLLECTION ORDER BY name")
return res
except StandardError, e:
return ()
def get_rnkmethod_collections(rnkid):
""" 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_collections()
result = filter(lambda x: res1.has_key(x[0]), res2)
return result
except StandardError, e:
raise ()
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_collection(rnkid, collid):
"""attach rank method to collection
rnkid - id from rnkMETHOD table
collid - id of collection, as in collection table """
try:
res = run_sql("INSERT INTO collection_rnkMETHOD(id_collection, id_rnkMETHOD) values (%s,%s)" % (collid, rnkid))
return "true"
except StandardError, e:
return ""
def detach_collection(rnkid, collid):
"""detach rank method from collection
rnkid - id from rnkMETHOD table
collid - id of collection, as in collection table """
try:
res = run_sql("DELETE FROM collection_rnkMETHOD WHERE id_collection=%s AND id_rnkMETHOD=%s" % (collid, rnkid))
except StandardError, e:
return ""
return "true"
def delete_rankmethod(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_rankmethod(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 addRankMethod(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'" % rnkcode)
return res
except StandardError, e:
return ""
def setmodifiedtranslations(rnkid, sel_lang, types, trans):
"""add or modify translations for a given rank method
rnkid - the id of the rank method from rnkMETHOD table
sel_lang - the languge to be changed
types - the language types
trans - the translations, in same order as in types """
try:
for nr in range(0,len(trans)):
res = run_sql("SELECT value FROM rnkMETHODNAME WHERE id_rnkMETHOD=%s AND type='%s' AND ln='%s'" % (rnkid, types[nr][0][0] , sel_lang))
if res:
res = run_sql("UPDATE rnkMETHODNAME SET value='%s' WHERE id_rnkMETHOD=%s AND type='%s' AND ln='%s'" % (MySQLdb.escape_string(trans[nr]), rnkid, types[nr][0][0] , sel_lang))
else:
res = run_sql("INSERT INTO rnkMETHODNAME(id_rnkMETHOD, type, ln, value) VALUES (%s,'%s','%s','%s')" % (rnkid, types[nr][0][0] , sel_lang, MySQLdb.escape_string(trans[nr])))
return "true"
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."""
try: per = str(100 // len(datalist)) + '%'
except ZeroDivisionError: per = 1
output = '<table class="%s" ' % (cls, ) + '>\n'
output += """
<thead>
<tr>
<th class="adminheaderleft" colspan="%s">%s</th>
</tr>
</thead>
<tbody>
""" % (len(datalist), header)
for row in [datalist]:
output += ' <tr>\n'
for data in row:
output += """
<td style="vertical-align: top; margin-top: 5px; width: %s;">
%s
</td>
""" % (per, data)
output += ' </tr>\n'
output += """
</tbody>
</table>
"""
return output
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 = '<table class="%s" ' % (cls, ) + 'width="95%">\n'
output += """
<thead>
<tr>
<th class="adminheaderleft" colspan="%s">%s</th>
</tr>
</thead>
<tbody>
""" % (len(datalist), header)
output += ' <tr>\n'
output += """
<td style="vertical-align: top; margin-top: 5px; width: %s;">
%s
</td>
""" % (per+'%', datalist[0])
if len(datalist) > 1:
output += """
<td style="vertical-align: top; margin-top: 5px; width: %s;">
%s
</td>
""" % ('25%', datalist[1])
output += ' </tr>\n'
output += """
</tbody>
</table>
"""
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 += ' <th class="adminheader">%s</th>\n' % (h, )
if tblstr: tblstr = ' <tr>\n%s\n </tr>\n' % (tblstr, )
tblstr = start + '<table class="admin_wvar_nomargin">\n' + tblstr
# extra column
try:
extra = '<tr>'
if type(firstrow) not in [int, long, str, dict]:
# for data in firstrow: extra += '<td class="%s">%s</td>\n' % ('admintd', data)
for i in range(len(firstrow)): extra += '<td class="%s">%s</td>\n' % (align[i], firstrow[i])
else:
extra += ' <td class="%s">%s</td>\n' % (align[0], firstrow)
extra += '<td rowspan="%s" style="vertical-align: top">\n%s\n</td>\n</tr>\n' % (len(tuple), extracolumn)
except IndexError:
extra = ''
tblstr += extra
# for i in range(1, len(tuple)):
for row in tuple[1:]:
tblstr += ' <tr>\n'
# row = tuple[i]
if type(row) not in [int, long, str, dict]:
# for data in row: tblstr += '<td class="admintd">%s</td>\n' % (data,)
for i in range(len(row)): tblstr += '<td class="%s">%s</td>\n' % (align[i], row[i])
else:
tblstr += ' <td class="%s">%s</td>\n' % (align[0], row)
tblstr += ' </tr> \n'
tblstr += '</table> \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, '<input type="checkbox" name="%s" value="%s" %s />' % (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 = '<form action="%s" method="POST">\n' % (action, )
output += '<table>\n<tr><td style="vertical-align: top">'
output += text
if cnfrm:
output += ' <input type="checkbox" name="confirm" value="1"/>'
for key in hidden.keys():
if type(hidden[key]) is list:
for value in hidden[key]:
output += ' <input type="hidden" name="%s" value="%s"/>\n' % (key, value)
else:
output += ' <input type="hidden" name="%s" value="%s"/>\n' % (key, hidden[key])
output += '</td><td style="vertical-align: bottom">'
output += ' <input class="adminbutton" type="submit" value="%s"/>\n' % (button, )
output += '</td></tr></table>'
output += '</form>\n'
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))

Event Timeline