diff --git a/modules/websubmit/lib/websubmit_engine.py b/modules/websubmit/lib/websubmit_engine.py
index 5e9368322..0d6adc834 100644
--- a/modules/websubmit/lib/websubmit_engine.py
+++ b/modules/websubmit/lib/websubmit_engine.py
@@ -1,1607 +1,1607 @@
 ## $Id$
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """WebSubmit: the mechanism for the submission of new records into CDS Invenio
    via a Web interface.
 """
 
 __revision__ = "$Id$"
 
 ## import interesting modules:
 import string
 import os
 import sys
 import time
 import types
 import re
 from urllib import quote_plus
 from cgi import escape
 
 try:
     from mod_python import apache
 except ImportError:
     pass
 
 from invenio.config import \
      CFG_BINDIR, \
      CFG_SITE_LANG, \
      CFG_SITE_NAME, \
      CFG_SITE_URL, \
      CFG_PYLIBDIR, \
      CFG_WEBSUBMIT_STORAGEDIR, \
      CFG_VERSION
 from invenio.dbquery import run_sql, Error
 from invenio.access_control_engine import acc_authorize_action
 from invenio.access_control_admin import acc_is_role
 from invenio.webpage import page, create_error_box
 from invenio.webuser import getUid, get_email, collect_user_info
 from invenio.websubmit_config import *
 from invenio.messages import gettext_set_language, wash_language
 from invenio.errorlib import register_exception
 
 
 from websubmit_dblayer import \
      get_storage_directory_of_action, \
      get_longname_of_doctype, \
      get_longname_of_action, \
      get_num_pages_of_submission, \
      get_parameter_value_for_doctype, \
      submission_exists_in_log, \
      log_new_pending_submission, \
      log_new_completed_submission, \
      update_submission_modified_date_in_log, \
      update_submission_reference_in_log, \
      update_submission_reference_and_status_in_log, \
      get_form_fields_on_submission_page, \
      get_element_description, \
      get_element_check_description, \
      get_form_fields_not_on_submission_page, \
      function_step_is_last, \
      get_collection_children_of_submission_collection, \
      get_submission_collection_name, \
      get_doctype_children_of_submission_collection, \
      get_categories_of_doctype, \
      get_doctype_details, \
      get_actions_on_submission_page_for_doctype, \
      get_action_details, \
      get_parameters_of_function, \
      get_details_of_submission, \
      get_functions_for_submission_step, \
      get_submissions_at_level_X_with_score_above_N, \
      submission_is_finished
 
 import invenio.template
 websubmit_templates = invenio.template.load('websubmit')
 
 def interface(req,
               c=CFG_SITE_NAME,
               ln=CFG_SITE_LANG,
               doctype="",
               act="",
               startPg=1,
               indir="",
               access="",
               mainmenu="",
               fromdir="",
               file="",
               nextPg="",
               nbPg="",
               curpage=1):
     """This function is called after a user has visited a document type's
        "homepage" and selected the type of "action" to perform. Having
        clicked an action-button (e.g. "Submit a New Record"), this function
        will be called . It performs the task of initialising a new submission
        session (retrieving information about the submission, creating a
        working submission-directory, etc), and "drawing" a submission page
        containing the WebSubmit form that the user uses to input the metadata
        to be submitted.
        When a user moves between pages in the submission interface, this
        function is recalled so that it can save the metadata entered into the
        previous page by the user, and draw the current submission-page.
 
        Note: During a submission, for each page refresh, this function will be
        called while the variable "step" (a form variable, seen by
        websubmit_webinterface, which calls this function) is 0 (ZERO).
 
        In other words, this function handles the FRONT-END phase of a
        submission, BEFORE the WebSubmit functions are called.
 
        @param req: (apache request object) *** NOTE: Added into this object, is
         a variable called "form" (req.form). This is added into the object in
         the index function of websubmit_webinterface. It contains a
         "mod_python.util.FieldStorage" instance, that contains the form-fields
         found on the previous submission page.
        @param c: (string), defaulted to CFG_SITE_NAME. The name of the CDS Invenio
         installation.
        @param ln: (string), defaulted to CFG_SITE_LANG. The language in which to
         display the pages.
        @param doctype: (string) - the doctype ID of the doctype for which the
         submission is being made.
        @param act: (string) - The ID of the action being performed (e.g.
         submission of bibliographic information; modification of bibliographic
         information, etc).
        @param startPg: (integer) - Starting page for the submission? Defaults
         to 1.
        @param indir: (string) - the directory used to store all submissions
         of the given "type" of this submission. For example, if the submission
         is of the type "modify bibliographic information", this variable would
         contain "modify".
        @param access: (string) - the "access" number for the submission
         (e.g. 1174062451_7010). This number is also used as the name for the
         current working submission directory.
        @param mainmenu: (string) - contains the URL (minus the CDS Invenio
         home stem) for the submission's home-page. (E.g. If this submission
         is "PICT", the "mainmenu" file would contain "/submit?doctype=PICT".
        @param fromdir: (integer)
        @param file: (string)
        @param nextPg: (string)
        @param nbPg: (string)
        @param curpage: (integer) - the current submission page number. Defaults
         to 1.
     """
 
     ln = wash_language(ln)
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     sys.stdout = req
     # get user ID:
     uid = getUid(req)
     uid_email = get_email(uid)
     # variable initialisation
     t = ""
     field = []
     fieldhtml = []
     level = []
     fullDesc = []
     text = []
     check = []
     select = []
     radio = []
     upload = []
     txt = []
     noPage = []
     # Preliminary tasks
     # check that the user is logged in
     if uid_email == "" or uid_email == "guest":
         return warningMsg(websubmit_templates.tmpl_warning_message(
                            ln = ln,
                            msg = _("Sorry, you must log in to perform this action.")
                          ), req, ln)
         # warningMsg("""<center><font color="red"></font></center>""",req, ln)
     # check we have minimum fields
     if not doctype or not act or not access:
         ## We don't have all the necessary information to go ahead
         ## with this submission:
         return warningMsg(_("Not enough information to go ahead with the submission."), req, c, ln)
 
     ## Before continuing to display the submission form interface,
     ## verify that this submission has not already been completed:
     if submission_is_finished(doctype, act, access, uid_email):
         ## This submission has already been completed.
         ## This situation can arise when, having completed a submission,
         ## the user uses the browser's back-button to go back to the form
         ## stage of the submission and then tries to submit once more.
         ## This is unsafe and should not be allowed. Instead of re-displaying
         ## the submission forms, display an error message to the user:
         wrnmsg = """<b>This submission has been completed. Please go to the""" \
                  """ <a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s">""" \
                  """main menu</a> to start a new submission.</b>""" \
                  % { 'doctype' : quote_plus(doctype), 'ln' : ln }
         return warningMsg(wrnmsg, req)
 
 
     ## retrieve the action and doctype data:
 
     ## Concatenate action ID and doctype ID to make the submission ID:
     subname = "%s%s" % (act, doctype)
 
     if not indir:
         ## Get the submission storage directory from the DB:
         submission_dir = get_storage_directory_of_action(act)
         if submission_dir:
             indir = submission_dir
         else:
             ## Unable to determine the submission-directory:
             return warningMsg(_("Unable to find the submission directory."), req, c, ln)
 
     ## get the document type's long-name:
     doctype_lname = get_longname_of_doctype(doctype)
     if doctype_lname is not None:
         ## Got the doctype long-name: replace spaces with HTML chars:
         docname = doctype_lname.replace(" ", "&nbsp;")
     else:
         ## Unknown document type:
         return warningMsg(_("Unknown document type"), req, c, ln)
 
     ## get the action's long-name:
     actname = get_longname_of_action(act)
     if actname is None:
         ## Unknown action:
         return warningMsg(_("Unknown action"), req, c, ln)
 
     ## Get the number of pages for this submission:
     num_submission_pages = get_num_pages_of_submission(subname)
     if num_submission_pages is not None:
         nbpages = num_submission_pages
     else:
         ## Unable to determine the number of pages for this submission:
         return warningMsg(_("Unable to determine the number of submission pages."), req, c, ln)
 
     ## If unknown, get the current page of submission:
     if startPg != "" and curpage in ("", 0):
         curpage = startPg
 
     ## retrieve the name of the file in which the reference of
     ## the submitted document will be stored
     rn_filename = get_parameter_value_for_doctype(doctype, "edsrn")
     if rn_filename is not None:
         edsrn = rn_filename
     else:
         ## Unknown value for edsrn - set it to an empty string:
         edsrn = ""
 
     ## This defines the path to the directory containing the action data
     curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, indir, doctype, access)
     try:
         assert(curdir == os.path.abspath(curdir))
     except AssertionError:
-        register_exception(req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype="%s", access="%s"' % (indir, doctype, access))
+        register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype="%s", access="%s"' % (indir, doctype, access))
         return warningMsg(_("Invalid parameters"), req, c, ln)
 
     ## if this submission comes from another one (fromdir is then set)
     ## We retrieve the previous submission directory and put it in the proper one
     if fromdir != "":
         olddir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, fromdir, doctype, access)
         try:
             assert(olddir == os.path.abspath(olddir))
         except AssertionError:
-            register_exception(req, alert_admin=True, prefix='Possible cracking tentative: fromdir="%s", doctype="%s", access="%s"' % (fromdir, doctype, access))
+            register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: fromdir="%s", doctype="%s", access="%s"' % (fromdir, doctype, access))
             return warningMsg(_("Invalid parameters"), req, c, ln)
 
         if os.path.exists(olddir):
             os.rename(olddir, curdir)
     ## If the submission directory still does not exist, we create it
     if not os.path.exists(curdir):
         try:
             os.makedirs(curdir)
         except Exception, e:
             register_exception(req=req, alert_admin=True)
             return warningMsg(_("Unable to create a directory for this submission. The administrator has been alerted."), req, c, ln)
     # retrieve the original main menu url and save it in the "mainmenu" file
     if mainmenu != "":
         fp = open(os.path.join(curdir, "mainmenu"), "w")
         fp.write(mainmenu)
         fp.close()
     # and if the file containing the URL to the main menu exists
     # we retrieve it and store it in the $mainmenu variable
     if os.path.exists(os.path.join(curdir, "mainmenu")):
         fp = open(os.path.join(curdir, "mainmenu"), "r");
         mainmenu = fp.read()
         fp.close()
     else:
         mainmenu = "%s/submit" % (CFG_SITE_URL,)
     # various authentication related tasks...
     if uid_email != "guest" and uid_email != "":
         #First save the username (email address) in the SuE file. This way bibconvert will be able to use it if needed
         fp = open(os.path.join(curdir, "SuE"), "w")
         fp.write(uid_email)
         fp.close()
     # is user authorized to perform this action?
     (auth_code, auth_message) = acc_authorize_action(req, "submit", verbose=0, doctype=doctype, act=act)
     if acc_is_role("submit", doctype=doctype, act=act) and auth_code != 0:
         return warningMsg("""<center><font color="red">%s</font></center>""" % auth_message, req)
 
     ## update the "journal of submission":
     ## Does the submission already exist in the log?
     submission_exists = \
          submission_exists_in_log(doctype, act, access, uid_email)
     if submission_exists == 1:
         ## update the modification-date of this submission in the log:
         update_submission_modified_date_in_log(doctype, act, access, uid_email)
     else:
         ## Submission doesn't exist in log - create it:
         log_new_pending_submission(doctype, act, access, uid_email)
 
     # Save the form fields entered in the previous submission page
     # If the form was sent with the GET method
     form = req.form
     value = ""
     # we parse all the form variables
     for key, formfields in form.items():
         filename = key.replace("[]", "")
         file_to_open = os.path.join(curdir, filename)
         try:
             assert(file_to_open == os.path.abspath(file_to_open))
             assert(file_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR))
         except AssertionError:
-            register_exception(req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", filename="%s"' % (curdir, filename))
+            register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", filename="%s"' % (curdir, filename))
             return warningMsg(_("Invalid parameters"), req, c, ln)
 
         # the field is an array
         if isinstance(formfields, types.ListType):
             fp = open(file_to_open, "w")
             for formfield in formfields:
                 #stripslashes(value)
                 value = specialchars(formfield)
                 fp.write(value+"\n")
             fp.close()
         # the field is a normal string
         elif isinstance(formfields, types.StringTypes) and formfields != "":
             value = formfields
             fp = open(file_to_open, "w")
             fp.write(specialchars(value))
             fp.close()
         # the field is a file
         elif hasattr(formfields,"filename") and formfields.filename is not None:
             dir_to_open = os.path.join(curdir, 'files', key)
             try:
                 assert(dir_to_open == os.path.abspath(dir_to_open))
                 assert(dir_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR))
             except AssertionError:
-                register_exception(req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", key="%s"' % (curdir, key))
+                register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", key="%s"' % (curdir, key))
                 return warningMsg(_("Invalid parameters"), req, c, ln)
             if not os.path.exists(dir_to_open):
                 try:
                     os.makedirs(dir_to_open)
                 except:
-                    register_exception(req, alert_admin=True)
+                    register_exception(req=req, alert_admin=True)
                     return warningMsg(_("Cannot create submission directory. The administrator has been alerted."), req, c, ln)
             filename = formfields.filename
             ## Before saving the file to disc, wash the filename (in particular
             ## washing away UNIX and Windows (e.g. DFS) paths):
             filename = os.path.basename(filename.split('\\')[-1])
             filename = filename.strip()
             if filename != "":
                 # This may be dangerous if the file size is bigger than the available memory
                 data = formfields.file.read()
                 fp = open(os.path.join(dir_to_open, filename), "w")
                 fp.write(data)
                 fp.close()
                 fp = open(os.path.join(curdir, "lastuploadedfile"), "w")
                 fp.write(filename)
                 fp.close()
                 fp = open(file_to_open, "w")
                 fp.write(filename)
                 fp.close()
             else:
                 return warningMsg(_("No file uploaded?"), req, c, ln)
 
         ## if the found field is the reference of the document,
         ## save this value in the "journal of submissions":
         if uid_email != "" and uid_email != "guest":
             if key == edsrn:
                 update_submission_reference_in_log(doctype, access, uid_email, value)
 
     ## create the interface:
     subname = "%s%s" % (act, doctype)
 
     ## Get all of the form fields that appear on this page, ordered by fieldnum:
     form_fields = get_form_fields_on_submission_page(subname, curpage)
 
     full_fields = []
     values = []
 
     for field_instance in form_fields:
         full_field = {}
         ## Retrieve the field's description:
         element_descr = get_element_description(field_instance[3])
         try:
             assert(element_descr is not None)
         except AssertionError:
             msg = _("Unknown form field found on submission page.")
-            register_exception(req, alert_admin=True, prefix=msg)
+            register_exception(req=req, alert_admin=True, prefix=msg)
             ## The form field doesn't seem to exist - return with error message:
             return warningMsg(_("Unknown form field found on submission page."), req, c, ln)
 
         if element_descr[8] is None:
             val = ""
         else:
             val = element_descr[8]
 
         ## we also retrieve and add the javascript code of the checking function, if needed
         ## Set it to empty string to begin with:
         full_field['javascript'] = ''
         if field_instance[7] != '':
             check_descr = get_element_check_description(field_instance[7])
             if check_descr is not None:
                 ## Retrieved the check description:
                 full_field['javascript'] = check_descr
 
         full_field['type'] = element_descr[3]
         full_field['name'] = field_instance[3]
         full_field['rows'] = element_descr[5]
         full_field['cols'] = element_descr[6]
         full_field['val'] = val
         full_field['size'] = element_descr[4]
         full_field['maxlength'] = element_descr[7]
         full_field['htmlcode'] = element_descr[9]
         full_field['typename'] = field_instance[1]  ## TODO: Investigate this, Not used?
                                                     ## It also seems to refer to pagenum.
 
         # The 'R' fields must be executed in the engine's environment,
         # as the runtime functions access some global and local
         # variables.
         if full_field ['type'] == 'R':
             co = compile (full_field ['htmlcode'].replace("\r\n","\n"), "<string>", "exec")
             exec(co)
         else:
             text = websubmit_templates.tmpl_submit_field (ln = ln, field = full_field)
 
         # we now determine the exact type of the created field
         if full_field['type'] not in [ 'D','R']:
             field.append(full_field['name'])
             level.append(field_instance[5])
             fullDesc.append(field_instance[4])
             txt.append(field_instance[6])
             check.append(field_instance[7])
             # If the field is not user-defined, we try to determine its type
             # (select, radio, file upload...)
             # check whether it is a select field or not
             if re.search("SELECT", text, re.IGNORECASE) is not None:
                 select.append(1)
             else:
                 select.append(0)
             # checks whether it is a radio field or not
             if re.search(r"TYPE=[\"']?radio", text, re.IGNORECASE) is not None:
                 radio.append(1)
             else:
                 radio.append(0)
             # checks whether it is a file upload or not
             if re.search(r"TYPE=[\"']?file", text, re.IGNORECASE) is not None:
                 upload.append(1)
             else:
                 upload.append(0)
             # if the field description contains the "<COMBO>" string, replace
             # it by the category selected on the document page submission page
             combofile = "combo%s" % doctype
             if os.path.exists("%s/%s" % (curdir, combofile)):
                 f = open("%s/%s" % (curdir, combofile), "r")
                 combo = f.read()
                 f.close()
             else:
                 combo=""
             text = text.replace("<COMBO>", combo)
             # if there is a <YYYY> tag in it, replace it by the current year
             year = time.strftime("%Y");
             text = text.replace("<YYYY>", year)
             # if there is a <TODAY> tag in it, replace it by the current year
             today = time.strftime("%d/%m/%Y");
             text = text.replace("<TODAY>", today)
             fieldhtml.append(text)
         else:
             select.append(0)
             radio.append(0)
             upload.append(0)
             # field.append(value) - initial version, not working with JS, taking a submitted value
             field.append(field_instance[3])
             level.append(field_instance[5])
             txt.append(field_instance[6])
             fullDesc.append(field_instance[4])
             check.append(field_instance[7])
             fieldhtml.append(text)
         full_field['fullDesc'] = field_instance[4]
         full_field['text'] = text
 
         # If a file exists with the name of the field we extract the saved value
         text = ''
         if os.path.exists(os.path.join(curdir, full_field['name'])):
             file = open(os.path.join(curdir, full_field['name']), "r");
             text = file.read()
             text = re.compile("[\n\r]*$").sub("", text)
             text = re.compile("\n").sub("\\n", text)
             text = re.compile("\r").sub("", text)
             file.close()
 
         values.append(text)
 
         full_fields.append(full_field)
 
     returnto = {}
     if int(curpage) == int(nbpages):
         subname = "%s%s" % (act, doctype)
         other_form_fields = \
               get_form_fields_not_on_submission_page(subname, curpage)
         nbFields = 0
         message = ""
         fullcheck_select = []
         fullcheck_radio = []
         fullcheck_upload = []
         fullcheck_field = []
         fullcheck_level = []
         fullcheck_txt = []
         fullcheck_noPage = []
         fullcheck_check = []
         for field_instance in other_form_fields:
             if field_instance[5] == "M":
                 ## If this field is mandatory, get its description:
                 element_descr = get_element_description(field_instance[3])
                 try:
                     assert(element_descr is not None)
                 except AssertionError:
                     msg = _("Unknown form field found on submission page.")
-                    register_exception(req, alert_admin=True, prefix=msg)
+                    register_exception(req=req, alert_admin=True, prefix=msg)
                     ## The form field doesn't seem to exist - return with error message:
                     return warningMsg(_("Unknown form field found on submission page."), req, c, ln)
                 if element_descr[3] in ['D', 'R']:
                     if element_descr[3] == "D":
                         text = element_descr[9]
                     else:
                         text = eval(element_descr[9])
                     formfields = text.split(">")
                     for formfield in formfields:
                         match = re.match("name=([^ <>]+)", formfield, re.IGNORECASE)
                         if match is not None:
                             names = match.groups
                             for value in names:
                                 if value != "":
                                     value = re.compile("[\"']+").sub("", value)
                                     fullcheck_field.append(value)
                                     fullcheck_level.append(field_instance[5])
                                     fullcheck_txt.append(field_instance[6])
                                     fullcheck_noPage.append(field_instance[1])
                                     fullcheck_check.append(field_instance[7])
                                     nbFields = nbFields + 1
                 else:
                     fullcheck_noPage.append(field_instance[1])
                     fullcheck_field.append(field_instance[3])
                     fullcheck_level.append(field_instance[5])
                     fullcheck_txt.append(field_instance[6])
                     fullcheck_check.append(field_instance[7])
                     nbFields = nbFields+1
         # tests each mandatory field
         fld = 0
         res = 1
         for i in xrange(nbFields):
             res = 1
             if not os.path.exists(os.path.join(curdir, fullcheck_field[i])):
                 res=0
             else:
                 file = open(os.path.join(curdir, fullcheck_field[i]), "r")
                 text = file.read()
                 if text == '':
                     res=0
                 else:
                     if text == "Select:":
                         res=0
             if res == 0:
                 fld = i
                 break
         if not res:
             returnto = {
                          'field' : fullcheck_txt[fld],
                          'page'  : fullcheck_noPage[fld],
                        }
 
     t += websubmit_templates.tmpl_page_interface(
           ln = ln,
           docname = docname,
           actname = actname,
           curpage = curpage,
           nbpages = nbpages,
           file = file,
           nextPg = nextPg,
           access = access,
           nbPg = nbPg,
           doctype = doctype,
           act = act,
           indir = indir,
           fields = full_fields,
           javascript = websubmit_templates.tmpl_page_interface_js(
                          ln = ln,
                          upload = upload,
                          field = field,
                          fieldhtml = fieldhtml,
                          txt = txt,
                          check = check,
                          level = level,
                          curdir = curdir,
                          values = values,
                          select = select,
                          radio = radio,
                          curpage = curpage,
                          nbpages = nbpages,
                          returnto = returnto,
                        ),
           mainmenu = mainmenu,
          )
 
     # start display:
     req.content_type = "text/html"
     req.send_http_header()
     p_navtrail = """<a href="/submit?ln=%(ln)s" class="navtrail">%(submit)s</a>&nbsp;>&nbsp;<a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s" class="navtrail">%(docname)s</a>&nbsp;""" % {
                    'submit'  : _("Submit"),
                    'doctype' : quote_plus(doctype),
                    'docname' : escape(docname),
                    'ln' : ln
                  }
     return page(title= actname,
                 body = t,
                 navtrail = p_navtrail,
                 description = "submit documents",
                 keywords = "submit",
                 uid = uid,
                 language = ln,
                 req = req,
                 navmenuid='submit')
 
 
 def endaction(req,
               c=CFG_SITE_NAME,
               ln=CFG_SITE_LANG,
               doctype="",
               act="",
               startPg=1,
               indir="",
               access="",
               mainmenu="",
               fromdir="",
               file="",
               nextPg="",
               nbPg="",
               curpage=1,
               step=1,
               mode="U"):
     """Having filled-in the WebSubmit form created for metadata by the interface
        function, the user clicks a button to either "finish the submission" or
        to "proceed" to the next stage of the submission. At this point, a
        variable called "step" will be given a value of 1 or above, which means
        that this function is called by websubmit_webinterface.
        So, during all non-zero steps of the submission, this function is called.
 
        In other words, this function is called during the BACK-END phase of a
        submission, in which WebSubmit *functions* are being called.
 
        The function first ensures that all of the WebSubmit form field values
        have been saved in the current working submission directory, in text-
        files with the same name as the field elements have. It then determines
        the functions to be called for the given step of the submission, and
        executes them.
        Following this, if this is the last step of the submission, it logs the
        submission as "finished" in the journal of submissions.
 
        @param req: (apache request object) *** NOTE: Added into this object, is
         a variable called "form" (req.form). This is added into the object in
         the index function of websubmit_webinterface. It contains a
         "mod_python.util.FieldStorage" instance, that contains the form-fields
         found on the previous submission page.
        @param c: (string), defaulted to CFG_SITE_NAME. The name of the CDS Invenio
         installation.
        @param ln: (string), defaulted to CFG_SITE_LANG. The language in which to
         display the pages.
        @param doctype: (string) - the doctype ID of the doctype for which the
         submission is being made.
        @param act: (string) - The ID of the action being performed (e.g.
         submission of bibliographic information; modification of bibliographic
         information, etc).
        @param startPg: (integer) - Starting page for the submission? Defaults
         to 1.
        @param indir: (string) - the directory used to store all submissions
         of the given "type" of this submission. For example, if the submission
         is of the type "modify bibliographic information", this variable would
         contain "modify".
        @param access: (string) - the "access" number for the submission
         (e.g. 1174062451_7010). This number is also used as the name for the
         current working submission directory.
        @param mainmenu: (string) - contains the URL (minus the CDS Invenio
         home stem) for the submission's home-page. (E.g. If this submission
         is "PICT", the "mainmenu" file would contain "/submit?doctype=PICT".
        @param fromdir:
        @param file:
        @param nextPg:
        @param nbPg:
        @param curpage: (integer) - the current submission page number. Defaults
         to 1.
        @param step: (integer) - the current step of the submission. Defaults to
         1.
        @param mode:
     """
 
     global rn, sysno, dismode, curdir, uid, uid_email, last_step, action_score
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     try:
         rn
     except NameError:
         rn = ""
     dismode = mode
     ln = wash_language(ln)
     sys.stdout = req
     t = ""
     # get user ID:
     uid = getUid(req)
     uid_email = get_email(uid)
     # Preliminary tasks
     # check that the user is logged in
     if uid_email == "" or uid_email == "guest":
         return warningMsg(websubmit_templates.tmpl_warning_message(
                            ln = ln,
                            msg = _("Sorry, you must log in to perform this action.")
                          ), req, ln)
 
     ## check we have minimum fields
     if not doctype or not act or not access:
         ## We don't have all the necessary information to go ahead
         ## with this submission:
         return warningMsg(_("Not enough information to go ahead with the submission."), req, c, ln)
 
     ## Before continuing to process the submitted data, verify that
     ## this submission has not already been completed:
     if submission_is_finished(doctype, act, access, uid_email):
         ## This submission has already been completed.
         ## This situation can arise when, having completed a submission,
         ## the user uses the browser's back-button to go back to the form
         ## stage of the submission and then tries to submit once more.
         ## This is unsafe and should not be allowed. Instead of re-processing
         ## the submitted data, display an error message to the user:
         wrnmsg = """<b>This submission has been completed. Please go to the""" \
                  """ <a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s">""" \
                  """main menu</a> to start a new submission.</b>""" \
                  % { 'doctype' : quote_plus(doctype), 'ln' : ln }
         return warningMsg(wrnmsg, req)
 
     ## retrieve the action and doctype data
     if not indir:
         ## Get the submission storage directory from the DB:
         submission_dir = get_storage_directory_of_action(act)
         if submission_dir:
             indir = submission_dir
         else:
             ## Unable to determine the submission-directory:
             return warningMsg(_("Unable to find the submission directory."), \
                             req, c, ln)
 
     # The following words are reserved and should not be used as field names
     reserved_words = ["stop", "file", "nextPg", "startPg", "access", "curpage", "nbPg", "act", \
                       "indir", "doctype", "mode", "step", "deleted", "file_path", "userfile_name"]
     # This defines the path to the directory containing the action data
     curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, indir, doctype, access)
     try:
         assert(curdir == os.path.abspath(curdir))
         curdir = os.path.abspath(curdir)
         assert(curdir.startswith(CFG_WEBSUBMIT_STORAGEDIR))
     except AssertionError:
-        register_exception(req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype=%s, access=%s' % (indir, doctype, access))
+        register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype=%s, access=%s' % (indir, doctype, access))
         return warningMsg(_("Invalid parameters"), req, c, ln)
 
     ## If the submission directory still does not exist, we create it
     if not os.path.exists(curdir):
         try:
             os.makedirs(curdir)
         except Exception, e:
             register_exception(req=req, alert_admin=True)
             return warningMsg(_("Unable to create a directory for this submission. The administrator has been alerted."), req, c, ln)
 
     # retrieve the original main menu url ans save it in the "mainmenu" file
     if mainmenu != "":
         fp = open(os.path.join(curdir, "mainmenu"), "w")
         fp.write(mainmenu)
         fp.close()
     # and if the file containing the URL to the main menu exists
     # we retrieve it and store it in the $mainmenu variable
     if os.path.exists(os.path.join(curdir, "mainmenu")):
         fp = open(os.path.join(curdir, "mainmenu"), "r");
         mainmenu = fp.read()
         fp.close()
     else:
         mainmenu = "%s/submit" % (CFG_SITE_URL,)
 
     ## retrieve the name of the file in which the reference of
     ## the submitted document will be stored
     rn_filename = get_parameter_value_for_doctype(doctype, "edsrn")
     if rn_filename is not None:
         edsrn = rn_filename
     else:
         ## Unknown value for edsrn - set it to an empty string:
         edsrn = ""
 
     ## Determine whether the action is finished
     ## (ie there are no other steps after the current one):
     finished = function_step_is_last(doctype, act, step)
 
     # Save the form fields entered in the previous submission page
     # If the form was sent with the GET method
     form = req.form
     value = ""
     # we parse all the form variables
     for key in form.keys():
         formfields = form[key]
         filename = key.replace("[]", "")
 
         file_to_open = os.path.join(curdir, filename)
         try:
             assert(file_to_open == os.path.abspath(file_to_open))
             assert(file_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR))
         except AssertionError:
-            register_exception(req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", filename="%s"' % (curdir, filename))
+            register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", filename="%s"' % (curdir, filename))
             return warningMsg(_("Invalid parameters"), req, c, ln)
 
         # the field is an array
         if isinstance(formfields,types.ListType):
             fp = open(file_to_open, "w")
             for formfield in formfields:
                 #stripslashes(value)
                 value = specialchars(formfield)
                 fp.write(value+"\n")
             fp.close()
         # the field is a normal string
         elif isinstance(formfields, types.StringTypes) and formfields != "":
             value = formfields
             fp = open(file_to_open, "w")
             fp.write(specialchars(value))
             fp.close()
         # the field is a file
         elif hasattr(formfields, "filename") and formfields.filename is not None:
             dir_to_open = os.path.join(curdir, 'files', key)
             try:
                 assert(dir_to_open == os.path.abspath(dir_to_open))
                 assert(dir_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR))
             except AssertionError:
-                register_exception(req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", key="%s"' % (curdir, key))
+                register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: curdir="%s", key="%s"' % (curdir, key))
                 return warningMsg(_("Invalid parameters"), req, c, ln)
 
             if not os.path.exists(dir_to_open):
                 try:
                     os.makedirs(dir_to_open)
                 except:
-                    register_exception(req, alert_admin=True)
+                    register_exception(req=req, alert_admin=True)
                     return warningMsg(_("Cannot create submission directory. The administrator has been alerted."), req, c, ln)
             filename = formfields.filename
             ## Before saving the file to disc, wash the filename (in particular
             ## washing away UNIX and Windows (e.g. DFS) paths):
             filename = os.path.basename(filename.split('\\')[-1])
             filename = filename.strip()
             if filename != "":
                 # This may be dangerous if the file size is bigger than the available memory
                 data = formfields.file.read()
                 fp = open(os.path.join(dir_to_open, filename), "w")
                 fp.write(data)
                 fp.close()
                 fp = open(os.path.join(curdir, "lastuploadedfile"), "w")
                 fp.write(filename)
                 fp.close()
                 fp = open(file_to_open, "w")
                 fp.write(filename)
                 fp.close()
             else:
                 return warningMsg(_("No file uploaded?"), req, c, ln)
         ## if the found field is the reference of the document
         ## we save this value in the "journal of submissions"
         if uid_email != "" and uid_email != "guest":
             if key == edsrn:
                 update_submission_reference_in_log(doctype, access, uid_email, value)
 
     ## get the document type's long-name:
     doctype_lname = get_longname_of_doctype(doctype)
     if doctype_lname is not None:
         ## Got the doctype long-name: replace spaces with HTML chars:
         docname = doctype_lname.replace(" ", "&nbsp;")
     else:
         ## Unknown document type:
         return warningMsg(_("Unknown document type"), req, c, ln)
 
     ## get the action's long-name:
     actname = get_longname_of_action(act)
     if actname is None:
         ## Unknown action:
         return warningMsg(_("Unknown action"), req, c, ln)
 
     ## Get the number of pages for this submission:
     subname = "%s%s" % (act, doctype)
     num_submission_pages = get_num_pages_of_submission(subname)
     if num_submission_pages is not None:
         nbpages = num_submission_pages
     else:
         ## Unable to determine the number of pages for this submission:
         return warningMsg(_("Unable to determine the number of submission pages."), \
                         req, CFG_SITE_NAME, ln)
 
     ## Determine whether the action is finished
     ## (ie there are no other steps after the current one):
     last_step = function_step_is_last(doctype, act, step)
 
     next_action = '' ## The next action to be proposed to the user
 
     # Prints the action details, returning the mandatory score
     action_score = action_details(doctype, act)
     current_level = get_level(doctype, act)
 
     # Calls all the function's actions
     function_content = ''
     try:
         ## Handle the execution of the functions for this
         ## submission/step:
         start_time = time.time()
         function_content = print_function_calls(req=req, doctype=doctype,
                                                 action=act,
                                                 step=step,
                                                 form=form,
                                                 start_time=start_time,
                                                 ln=ln)
     except InvenioWebSubmitFunctionError, e:
-        register_exception(req, alert_admin=True, prefix='doctype="%s", action="%s", step="%s", form="%s", start_time="%s"' % (doctype, act, step, form, start_time))
+        register_exception(req=req, alert_admin=True, prefix='doctype="%s", action="%s", step="%s", form="%s", start_time="%s"' % (doctype, act, step, form, start_time))
         ## There was a serious function-error. Execution ends.
-        return warningMsg(_("A serious function-error has been encountered. Adminstrators have been alerted"), req, c, ln)
+        return warningMsg(_("A serious function-error has been encountered. Adminstrators have been alerted. <br /><em>Please not that this might be due to wrong characters inserted into the form</em> (e.g. by copy and pasting some text from a PDF file)."), req, c, ln)
     except InvenioWebSubmitFunctionStop, e:
         ## For one reason or another, one of the functions has determined that
         ## the data-processing phase (i.e. the functions execution) should be
         ## halted and the user should be returned to the form interface once
         ## more. (NOTE: Redirecting the user to the Web-form interface is
         ## currently done using JavaScript. The "InvenioWebSubmitFunctionStop"
         ## exception contains a "value" string, which is effectively JavaScript
         ## - probably an alert box and a form that is submitted). **THIS WILL
         ## CHANGE IN THE FUTURE WHEN JavaScript IS REMOVED!**
         if e.value is not None:
             function_content = e.value
         else:
             function_content = e
     else:
         ## No function exceptions (InvenioWebSubmitFunctionStop,
         ## InvenioWebSubmitFunctionError) were raised by the functions. Propose
         ## the next action (if applicable), and log the submission as finished:
 
         ## If the action was mandatory we propose the next
         ## mandatory action (if any)
         if action_score != -1 and last_step == 1:
             next_action = Propose_Next_Action(doctype, \
                                               action_score, \
                                               access, \
                                               current_level, \
                                               indir)
 
         ## If we are in the last step of an action, we can update
         ## the "journal of submissions"
         if last_step == 1:
             if uid_email != "" and uid_email != "guest" and rn != "":
                 ## update the "journal of submission":
                 ## Does the submission already exist in the log?
                 submission_exists = \
                      submission_exists_in_log(doctype, act, access, uid_email)
                 if submission_exists == 1:
                     ## update the rn and status to finished for this submission
                     ## in the log:
                     update_submission_reference_and_status_in_log(doctype, \
                                                                   act, \
                                                                   access, \
                                                                   uid_email, \
                                                                   rn, \
                                                                   "finished")
                 else:
                     ## Submission doesn't exist in log - create it:
                     log_new_completed_submission(doctype, \
                                                  act, \
                                                  access, \
                                                  uid_email, \
                                                  rn)
 
     ## Having executed the functions, create the page that will be displayed
     ## to the user:
     t = websubmit_templates.tmpl_page_endaction(
           ln = ln,
           # these fields are necessary for the navigation
           file = file,
           nextPg = nextPg,
           startPg = startPg,
           access = access,
           curpage = curpage,
           nbPg = nbPg,
           nbpages = nbpages,
           doctype = doctype,
           act = act,
           docname = docname,
           actname = actname,
           indir = indir,
           mainmenu = mainmenu,
           finished = finished,
           function_content = function_content,
           next_action = next_action,
         )
 
     # start display:
     req.content_type = "text/html"
     req.send_http_header()
 
     p_navtrail = '<a href="/submit?ln='+ln+'" class="navtrail">' + _("Submit") +\
                  """</a>&nbsp;>&nbsp;<a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s" class="navtrail">%(docname)s</a>""" % {
                    'doctype' : quote_plus(doctype),
                    'docname' : escape(docname),
                    'ln' : ln,
                  }
     return page(title= actname,
                 body = t,
                 navtrail = p_navtrail,
                 description="submit documents",
                 keywords="submit",
                 uid = uid,
                 language = ln,
                 req = req,
                 navmenuid='submit')
 
 def home(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
     """This function generates the WebSubmit "home page".
        Basically, this page contains a list of submission-collections
        in WebSubmit, and gives links to the various document-type
        submissions.
        Document-types only appear on this page when they have been
        connected to a submission-collection in WebSubmit.
        @param req: (apache request object)
        @param c: (string) - defaults to CFG_SITE_NAME
        @param ln: (string) - The CDS Invenio interface language of choice.
         Defaults to CFG_SITE_LANG (the default language of the installation).
        @return: (string) - the Web page to be displayed.
     """
     ln = wash_language(ln)
     # get user ID:
     try:
         uid = getUid(req)
     except Error, e:
         return errorMsg(e, req, c, ln)
     # start display:
     req.content_type = "text/html"
     req.send_http_header()
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     finaltext = websubmit_templates.tmpl_submit_home_page(
                     ln = ln,
                     catalogues = makeCataloguesTable(ln)
                 )
 
     return page(title=_("Submit"),
                body=finaltext,
                navtrail=[],
                description="submit documents",
                keywords="submit",
                uid=uid,
                language=ln,
                req=req,
                navmenuid='submit'
                )
 
 def makeCataloguesTable(ln=CFG_SITE_LANG):
     """Build the 'catalogues' (submission-collections) tree for
        the WebSubmit home-page. This tree contains the links to
        the various document types in WebSubmit.
        @param ln: (string) - the language of the interface.
         (defaults to 'CFG_SITE_LANG').
        @return: (string) - the submission-collections tree.
     """
     text = ""
     catalogues = []
 
     ## Get the submission-collections attached at the top level
     ## of the submission-collection tree:
     top_level_collctns = get_collection_children_of_submission_collection(0)
     if len(top_level_collctns) != 0:
         ## There are submission-collections attatched to the top level.
         ## retrieve their details for displaying:
         for child_collctn in top_level_collctns:
             catalogues.append(getCatalogueBranch(child_collctn[0], 1))
 
         text = websubmit_templates.tmpl_submit_home_catalogs(
                  ln=ln,
                  catalogs=catalogues
                )
     else:
         text = websubmit_templates.tmpl_submit_home_catalog_no_content(ln=ln)
     return text
 
 def getCatalogueBranch(id_father, level):
     """Build up a given branch of the submission-collection
        tree. I.e. given a parent submission-collection ID,
        build up the tree below it. This tree will include
        doctype-children, as well as other submission-
        collections and their children.
        Finally, return the branch as a dictionary.
        @param id_father: (integer) - the ID of the submission-collection
         from which to begin building the branch.
        @param level: (integer) - the level of the current submission-
         collection branch.
        @return: (dictionary) - the branch and its sub-branches.
     """
     elem = {} ## The dictionary to contain this branch of the tree.
     ## First, get the submission-collection-details:
     collctn_name = get_submission_collection_name(id_father)
     if collctn_name is not None:
         ## Got the submission-collection's name:
         elem['name'] = collctn_name
     else:
         ## The submission-collection is unknown to the DB
         ## set its name as empty:
         elem['name'] = ""
     elem['id']    = id_father
     elem['level'] = level
 
     ## Now get details of the doctype-children of this
     ## submission-collection:
     elem['docs'] = []  ## List to hold the doctype-children
                        ## of the submission-collection
     doctype_children = \
        get_doctype_children_of_submission_collection(id_father)
     for child_doctype in doctype_children:
         elem['docs'].append(getDoctypeBranch(child_doctype[0]))
 
     ## Now, get the collection-children of this submission-collection:
     elem['sons'] = []
     collctn_children = \
          get_collection_children_of_submission_collection(id_father)
     for child_collctn in collctn_children:
         elem['sons'].append(getCatalogueBranch(child_collctn[0], level + 1))
 
     ## Now return this branch of the built-up 'collection-tree':
     return elem
 
 def getDoctypeBranch(doctype):
     """Create a document-type 'leaf-node' for the submission-collections
        tree. Basically, this leaf is a dictionary containing the name
        and ID of the document-type submission to which it links.
        @param doctype: (string) - the ID of the document type.
        @return: (dictionary) - the document-type 'leaf node'. Contains
         the following values:
           + id:   (string) - the document-type ID.
           + name: (string) - the (long) name of the document-type.
     """
     ldocname = get_longname_of_doctype(doctype)
     if ldocname is None:
         ldocname = "Unknown Document Type"
     return { 'id' : doctype, 'name' : ldocname, }
 
 def displayCatalogueBranch(id_father, level, catalogues):
     text = ""
     collctn_name = get_submission_collection_name(id_father)
     if collctn_name is None:
         ## If this submission-collection wasn't known in the DB,
         ## give it the name "Unknown Submission-Collection" to
         ## avoid errors:
         collctn_name = "Unknown Submission-Collection"
 
     ## Now, create the display for this submission-collection:
     if level == 1:
         text = "<LI><font size=\"+1\"><strong>%s</strong></font>\n" \
                % collctn_name
     else:
         ## TODO: These are the same (and the if is ugly.) Why?
         if level == 2:
             text = "<LI>%s\n" % collctn_name
         else:
             if level > 2:
                 text = "<LI>%s\n" % collctn_name
 
     ## Now display the children document-types that are attached
     ## to this submission-collection:
     ## First, get the children:
     doctype_children = get_doctype_children_of_submission_collection(id_father)
     collctn_children = get_collection_children_of_submission_collection(id_father)
 
     if len(doctype_children) > 0 or len(collctn_children) > 0:
         ## There is something to display, so open a list:
         text = text + "<UL>\n"
     ## First, add the doctype leaves of this branch:
     for child_doctype in doctype_children:
         ## Add the doctype 'leaf-node':
         text = text + displayDoctypeBranch(child_doctype[0], catalogues)
 
     ## Now add the submission-collection sub-branches:
     for child_collctn in collctn_children:
         catalogues.append(child_collctn[0])
         text = text + displayCatalogueBranch(child_collctn[0], level+1, catalogues)
 
     ## Finally, close up the list if there were nodes to display
     ## at this branch:
     if len(doctype_children) > 0 or len(collctn_children) > 0:
         text = text + "</UL>\n"
 
     return text
 
 def displayDoctypeBranch(doctype, catalogues):
     text = ""
     ldocname = get_longname_of_doctype(doctype)
     if ldocname is None:
         ldocname = "Unknown Document Type"
     text = "<LI><a href=\"\" onmouseover=\"javascript:" \
            "popUpTextWindow('%s',true,event);\" onmouseout" \
            "=\"javascript:popUpTextWindow('%s',false,event);\" " \
            "onClick=\"document.forms[0].doctype.value='%s';" \
            "document.forms[0].submit();return false;\">%s</a>\n" \
            % (doctype, doctype, doctype, ldocname)
     return text
 
 
 def action(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG, doctype=""):
     # load the right message language
     _ = gettext_set_language(ln)
 
     nbCateg = 0
     snameCateg = []
     lnameCateg = []
     actionShortDesc = []
     indir = []
     actionbutton = []
     statustext = []
     t = ""
     ln = wash_language(ln)
     # get user ID:
     try:
         uid = getUid(req)
         uid_email = get_email(uid)
     except Error, e:
         return errorMsg(e, req, c, ln)
     #parses database to get all data
     ## first, get the list of categories
     doctype_categs = get_categories_of_doctype(doctype)
     for doctype_categ in doctype_categs:
         nbCateg = nbCateg+1
         snameCateg.append(doctype_categ[0])
         lnameCateg.append(doctype_categ[1])
 
     ## Now get the details of the document type:
     doctype_details = get_doctype_details(doctype)
     if doctype_details is None:
         ## Doctype doesn't exist - raise error:
         return errorMsg (_("Unable to find document type.") + str(doctype), req)
     else:
         docFullDesc  = doctype_details[0]
         docShortDesc = doctype_details[1]
         description  = doctype_details[4]
 
     ## Get the details of the actions supported by this document-type:
     doctype_actions = get_actions_on_submission_page_for_doctype(doctype)
     for doctype_action in doctype_actions:
         ## Get the details of this action:
         action_details = get_action_details(doctype_action[0])
         if action_details is not None:
             actionShortDesc.append(doctype_action[0])
             indir.append(action_details[1])
             actionbutton.append(action_details[4])
             statustext.append(action_details[5])
 
     ## Send the gathered information to the template so that the doctype's
     ## home-page can be displayed:
     t = websubmit_templates.tmpl_action_page(
           ln=ln,
           uid=uid, guest=(uid_email == "" or uid_email == "guest"),
           pid = os.getpid(),
           now = time.time(),
           doctype = doctype,
           description = description,
           docfulldesc = docFullDesc,
           snameCateg = snameCateg,
           lnameCateg = lnameCateg,
           actionShortDesc = actionShortDesc,
           indir = indir,
           # actionbutton = actionbutton,
           statustext = statustext,
         )
 
     p_navtrail = """<a href="/submit?ln=%(ln)s" class="navtrail">%(submit)s</a>""" % {'submit' : _("Submit"),
                                                                                       'ln' : ln}
 
     return page(title = docFullDesc,
                 body=t,
                 navtrail=p_navtrail,
                 description="submit documents",
                 keywords="submit",
                 uid=uid,
                 language=ln,
                 req=req,
                 navmenuid='submit'
                )
 
 def Request_Print(m, txt):
     """The argumemts to this function are the display mode (m) and the text
        to be displayed (txt).
        If the argument mode is 'ALL' then the text is unconditionally echoed
        m can also take values S (Supervisor Mode) and U (User Mode). In these
        circumstances txt is only echoed if the argument mode is the same as
        the current mode
     """
     global dismode
     if m == "A" or m == dismode:
         return txt
     else:
         return ""
 
 def Evaluate_Parameter (field, doctype):
     # Returns the literal value of the parameter. Assumes that the value is
     # uniquely determined by the doctype, i.e. doctype is the primary key in
     # the table
     # If the table name is not null, evaluate the parameter
 
     ## TODO: The above comment looks like nonesense? This
     ## function only seems to get the values of parameters
     ## from the db...
 
     ## Get the value for the parameter:
     param_val = get_parameter_value_for_doctype(doctype, field)
     if param_val is None:
         ## Couldn't find a value for this parameter for this doctype.
         ## Instead, try with the default doctype (DEF):
         param_val = get_parameter_value_for_doctype("DEF", field)
     if param_val is None:
         ## There was no value for the parameter for the default doctype.
         ## Nothing can be done about it - return an empty string:
         return ""
     else:
         ## There was some kind of value for the parameter; return it:
         return param_val
 
 
 def Get_Parameters (function, doctype):
     """For a given function of a given document type, a dictionary
        of the parameter names and values are returned.
        @param function: (string) - the name of the function for which the
         parameters are to be retrieved.
        @param doctype: (string) - the ID of the document type.
        @return: (dictionary) - of the parameters of the function.
         Keyed by the parameter name, values are of course the parameter
         values.
     """
     parray = {}
     ## Get the names of the parameters expected by this function:
     func_params = get_parameters_of_function(function)
     for func_param in func_params:
         ## For each of the parameters, get its value for this document-
         ## type and add it into the dictionary of parameters:
         parameter = func_param[0]
         parray[parameter] = Evaluate_Parameter (parameter, doctype)
     return parray
 
 def get_level(doctype, action):
     """Get the level of a given submission. If unknown, return 0
        as the level.
        @param doctype: (string) - the ID of the document type.
        @param action: (string) - the ID of the action.
        @return: (integer) - the level of the submission; 0 otherwise.
     """
     subm_details = get_details_of_submission(doctype, action)
     if subm_details is not None:
         ## Return the level of this action
         subm_level = subm_details[9]
         try:
             int(subm_level)
         except ValueError:
             return 0
         else:
             return subm_level
     else:
         return 0
 
 def action_details (doctype, action):
     # Prints whether the action is mandatory or optional. The score of the
     # action is returned (-1 if the action was optional)
     subm_details = get_details_of_submission(doctype, action)
     if subm_details is not None:
         if subm_details[9] != "0":
             ## This action is mandatory; return the score:
             return subm_details[10]
         else:
             return -1
     else:
         return -1
 
 def print_function_calls (req, doctype, action, step, form, start_time, ln=CFG_SITE_LANG):
     # Calls the functions required by an "action" action on a "doctype" document
     # In supervisor mode, a table of the function calls is produced
     global htdocsdir,CFG_WEBSUBMIT_STORAGEDIR,access,CFG_PYLIBDIR,dismode
     user_info = collect_user_info(req)
     # load the right message language
     _ = gettext_set_language(ln)
     t = ""
 
     ## Get the list of functions to be called
     funcs_to_call = get_functions_for_submission_step(doctype, action, step)
 
     ## If no functions are found at this step for this doctype,
     ## get the functions for the DEF(ault) doctype:
     if len(funcs_to_call) == 0:
         funcs_to_call = get_functions_for_submission_step("DEF", action, step)
     if len(funcs_to_call) > 0:
         # while there are functions left...
         functions = []
         for function in funcs_to_call:
             function_name = function[0]
             function_score = function[1]
             currfunction = {
               'name' : function_name,
               'score' : function_score,
               'error' : 0,
               'text' : '',
             }
             if os.path.exists("%s/invenio/websubmit_functions/%s.py" % (CFG_PYLIBDIR, function_name)):
                 # import the function itself
                 #function = getattr(invenio.websubmit_functions, function_name)
                 execfile("%s/invenio/websubmit_functions/%s.py" % (CFG_PYLIBDIR, function_name), globals())
                 if not globals().has_key(function_name):
                     currfunction['error'] = 1
                 else:
                     function = globals()[function_name]
                     # Evaluate the parameters, and place them in an array
                     parameters = Get_Parameters(function_name, doctype)
                     # Call function:
                     log_function(curdir, "Start %s" % function_name, start_time)
                     try:
                         try:
                             ## Attempt to call the function with 4 arguments:
                             ## ("parameters", "curdir" and "form" as usual),
                             ## and "user_info" - the dictionary of user
                             ## information:
                             ##
                             ## Note: The function should always be called with
                             ## these keyword arguments because the "TypeError"
                             ## except clause checks for a specific mention of
                             ## the 'user_info' keyword argument when a legacy
                             ## function (one that accepts only 'parameters',
                             ## 'curdir' and 'form') has been called and if
                             ## the error string doesn't contain this,
                             ## the TypeError will be considered as a something
                             ## that was incorrectly handled in the function and
                             ## will be propagated as an
                             ## InvenioWebSubmitFunctionError instead of the
                             ## function being called again with the legacy 3
                             ## arguments.
                             func_returnval = function(parameters=parameters, \
                                                       curdir=curdir, \
                                                       form=form, \
                                                       user_info=user_info)
                         except TypeError, err:
                             ## If the error contains the string "got an
                             ## unexpected keyword argument", it means that the
                             ## function doesn't accept the "user_info"
                             ## argument. Test for this:
                             if "got an unexpected keyword argument 'user_info'" in \
                                str(err).lower():
                                 ## As expected, the function doesn't accept
                                 ## the user_info keyword argument. Call it
                                 ## again with the legacy 3 arguments
                                 ## (parameters, curdir, form):
                                 func_returnval = \
                                                function(parameters=parameters, \
                                                         curdir=curdir, \
                                                         form=form)
                             else:
                                 ## An unexpected "TypeError" was caught.
                                 ## It looks as though the function itself didn't
                                 ## handle something correctly.
                                 ## Convert this error into an
                                 ## InvenioWebSubmitFunctionError and raise it:
                                 msg = "Unhandled TypeError caught when " \
                                       "calling [%s] WebSubmit function: " \
                                       "[%s]" % (function_name, str(err))
                                 raise InvenioWebSubmitFunctionError(msg)
                     except InvenioWebSubmitFunctionWarning, err:
                         ## There was an unexpected behaviour during the
                         ## execution. Log the message into function's log
                         ## and go to next function
                         log_function(curdir, "***Warning*** from %s: %s" \
                                      % (function_name, str(err)), start_time)
                         ## Reset "func_returnval" to None:
                         func_returnval = None
                     log_function(curdir, "End %s" % function_name, start_time)
                     if func_returnval is not None:
                         ## Append the returned value as a string:
                         currfunction['text'] = str(func_returnval)
                     else:
                         ## The function the NoneType. Don't keep that value as
                         ## the currfunction->text. Replace it with the empty
                         ## string.
                         currfunction['text'] = ""
             else:
                 currfunction['error'] = 1
             functions.append(currfunction)
 
         t = websubmit_templates.tmpl_function_output(
               ln = ln,
               display_on = (dismode == 'S'),
               action = action,
               doctype = doctype,
               step = step,
               functions = functions,
             )
     else :
         if dismode == 'S':
             t = "<br /><br /><b>" + _("The chosen action is not supported by the document type.") + "</b>"
     return t
 
 
 def Propose_Next_Action (doctype, action_score, access, currentlevel, indir, ln=CFG_SITE_LANG):
     global machine, CFG_WEBSUBMIT_STORAGEDIR, act, rn
     t = ""
     next_submissions = \
          get_submissions_at_level_X_with_score_above_N(doctype, currentlevel, action_score)
 
     if len(next_submissions) > 0:
         actions = []
         first_score = next_submissions[0][10]
         for action in next_submissions:
             if action[10] == first_score:
                 ## Get the submission directory of this action:
                 nextdir = get_storage_directory_of_action(action[1])
                 if nextdir is None:
                     nextdir = ""
                 curraction = {
                   'page' : action[11],
                   'action' : action[1],
                   'doctype' : doctype,
                   'nextdir' : nextdir,
                   'access' : access,
                   'indir' : indir,
                   'name' : action[12],
                 }
                 actions.append(curraction)
 
         t = websubmit_templates.tmpl_next_action(
               ln = ln,
               actions = actions,
             )
     return t
 
 def specialchars(text):
     text = string.replace(text, "&#147;", "\042");
     text = string.replace(text, "&#148;", "\042");
     text = string.replace(text, "&#146;", "\047");
     text = string.replace(text, "&#151;", "\055");
     text = string.replace(text, "&#133;", "\056\056\056");
     return text
 
 def log_function(curdir, message, start_time, filename="function_log"):
     """Write into file the message and the difference of time
     between starttime and current time
     @param curdir:(string) path to the destination dir
     @param message: (string) message to write into the file
     @param starttime: (float) time to compute from
     @param filname: (string) name of log file
     """
     time_lap = "%.3f" % (time.time() - start_time)
     if os.access(curdir, os.F_OK|os.W_OK):
         fd = open("%s/%s" % (curdir, filename), "a+")
         fd.write("""%s --- %s\n""" % (message, time_lap))
         fd.close()
 
 
 ## FIXME: Duplicated
 
 def errorMsg(title, req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
     # load the right message language
     _ = gettext_set_language(ln)
 
     return page(title = _("Error"),
                 body = create_error_box(req, title=title, verbose=0, ln=ln),
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='submit')
 
 def warningMsg(title, req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
     # load the right message language
     _ = gettext_set_language(ln)
 
     return page(title = _("Warning"),
                 body = title,
                 description="%s - Warning" % c,
                 keywords="%s, Warning" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='submit')
diff --git a/modules/websubmit/lib/websubmit_templates.py b/modules/websubmit/lib/websubmit_templates.py
index ff6ba0272..d1026159a 100644
--- a/modules/websubmit/lib/websubmit_templates.py
+++ b/modules/websubmit/lib/websubmit_templates.py
@@ -1,3044 +1,3044 @@
 ## $Id$
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 __revision__ = "$Id$"
 
 import urllib
 import time
 import cgi
 import gettext
 import string
 import locale
 import re
 import operator
 import os
 
 from invenio.config import \
      CFG_SITE_URL, \
      CFG_VERSION, \
      CFG_SITE_URL, \
      CFG_SITE_LANG
 from invenio.messages import gettext_set_language
 from invenio.dateutils import convert_datetext_to_dategui
 from invenio.webmessage_mailutils import email_quoted_txt2html
 from invenio.htmlutils import escape_html
 import invenio.template
 
 class Template:
 
     # Parameters allowed in the web interface for fetching files
     files_default_urlargd = {
         'version': (str, ""), # version "" means "latest"
         'docname': (str, ""), # the docname (optional)
         'format' : (str, ""), # the format
         'verbose' : (int, 0) # the verbosity
         }
 
 
     def tmpl_submit_home_page(self, ln, catalogues):
         """
         The content of the home page of the submit engine
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'catalogues' *string* - The HTML code for the catalogues list
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         return """
           <script type="text/javascript" language="Javascript1.2">
           var allLoaded = 1;
           </script>
            <table class="searchbox" width="100%%" summary="">
               <tr>
                   <th class="portalboxheader">%(document_types)s:</th>
               </tr>
               <tr>
                   <td class="portalboxbody">
                     <br />
                     %(please_select)s:
                     <br /><br />
                     <table width="100%%">
                     <tr>
                         <td width="50%%" class="narrowsearchboxbody">
                           <form method="get" action="/submit">
                             <input type="hidden" name="doctype" />
                             <input type="hidden" name="ln" value="%(ln)s" />
                               %(catalogues)s
                           </form>
                         </td>
                     </tr>
                     </table>
                   </td>
               </tr>
             </table>""" % {
               'document_types' : _("Document types available for submission"),
               'please_select' : _("Please select the type of document you want to submit"),
               'catalogues' : catalogues,
               'ln' : ln,
             }
 
     def tmpl_submit_home_catalog_no_content(self, ln):
         """
         The content of the home page of submit in case no doctypes are available
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = "<h3>" + _("No document types available.") + "</h3>\n"
         return out
 
     def tmpl_submit_home_catalogs(self, ln, catalogs):
         """
         Produces the catalogs' list HTML code
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'catalogs' *array* - The catalogs of documents, each one a hash with the properties:
                 - 'id' - the internal id
                 - 'name' - the name
                 - 'sons' - sub-catalogs
                 - 'docs' - the contained document types, in the form:
                       - 'id' - the internal id
                       - 'name' - the name
             There is at least one catalog
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         # import pprint
         # out = "<pre>" + pprint.pformat(catalogs)
         out = ""
         for catalog in catalogs:
             out += "\n<ul>"
             out += self.tmpl_submit_home_catalogs_sub(ln, catalog)
             out += "\n</ul>\n"
 
         return out
 
     def tmpl_print_warning(self, msg, type, prologue, epilogue):
         """Prints warning message and flushes output.
 
         Parameters:
 
           - 'msg' *string* - The message string
 
           - 'type' *string* - the warning type
 
           - 'prologue' *string* - HTML code to display before the warning
 
           - 'epilogue' *string* - HTML code to display after the warning
         """
 
         out = '\n%s<span class="quicknote">' % (prologue)
         if type:
             out += '%s: ' % type
         out += '%s</span>%s' % (msg, epilogue)
         return out
 
 
     def tmpl_submit_home_catalogs_sub(self, ln, catalog):
         """
         Recursive function that produces a catalog's HTML display
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'catalog' *array* - A catalog of documents, with the properties:
                 - 'id' - the internal id
                 - 'name' - the name
                 - 'sons' - sub-catalogs
                 - 'docs' - the contained document types, in the form:
                       - 'id' - the internal id
                       - 'name' - the name
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         if catalog['level'] == 1:
             out = "<li><font size=\"+1\"><strong>%s</strong></font>\n" % catalog['name']
         else:
             if catalog['level'] == 2:
                 out = "<li>%s\n" % catalog['name']
             else:
                 if catalog['level'] > 2:
                     out = "<li>%s\n" % catalog['name']
 
         if len(catalog['docs']) or len(catalog['sons']):
             out += "<ul>\n"
 
         if len(catalog['docs']) != 0:
             for row in catalog['docs']:
                 out += self.tmpl_submit_home_catalogs_doctype(ln, row)
 
         if len(catalog['sons']) != 0:
             for row in catalog['sons']:
                 out += self.tmpl_submit_home_catalogs_sub(ln, row)
 
         if len(catalog['docs']) or len(catalog['sons']):
             out += "</ul></li>"
         else:
             out += "</li>"
 
         return out
 
     def tmpl_submit_home_catalogs_doctype(self, ln, doc):
         """
         Recursive function that produces a catalog's HTML display
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doc' *array* - A catalog of documents, with the properties:
                       - 'id' - the internal id
                       - 'name' - the name
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         return """<li><a href="" onclick="document.forms[0].doctype.value='%(id)s';document.forms[0].submit();return false;">%(name)s</a></li>""" % doc
 
     def tmpl_action_page(self, ln, uid, guest, pid, now, doctype,
                          description, docfulldesc, snameCateg,
                          lnameCateg, actionShortDesc, indir,
                          statustext):
         """
         Recursive function that produces a catalog's HTML display
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'guest' *boolean* - If the user is logged in or not
 
           - 'pid' *string* - The current process id
 
           - 'now' *string* - The current time (security control features)
 
           - 'doctype' *string* - The selected doctype
 
           - 'description' *string* - The description of the doctype
 
           - 'docfulldesc' *string* - The title text of the page
 
           - 'snameCateg' *array* - The short names of all the categories of documents
 
           - 'lnameCateg' *array* - The long names of all the categories of documents
 
           - 'actionShortDesc' *array* - The short names (codes) for the different actions
 
           - 'indir' *array* - The directories for each of the actions
 
           - 'statustext' *array* - The names of the different action buttons
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = ""
 
         out += """
               <script language="JavaScript" type="text/javascript">
               var checked = 0;
               function tester() {
               """
         if (guest):
             out += "alert(\"%(please_login_js)s\");return false;\n" % {
                      'please_login_js' : _("Please log in first.") + '\\n' + _("Use the top-right menu to log in.")
                    }
 
         out += """
                     if (checked == 0) {
                         alert ("%(select_cat)s");
                         return false;
                     } else {
                         return true;
                     }
                 }
 
                 function clicked() {
                     checked=1;
                 }
 
                 function selectdoctype(nb) {
                     document.forms[0].act.value = docname[nb];
                 }
                 </script>
                 <form method="get" action="/submit">
                 <input type="hidden" name="doctype" value="%(doctype)s" />
                 <input type="hidden" name="indir" />
                 <input type="hidden" name="access" value="%(now)i_%(pid)s" />
 
                 <input type="hidden" name="act" />
                 <input type="hidden" name="startPg" value="1" />
                 <input type="hidden" name="mainmenu" value="/submit?doctype=%(doctype)s&amp;ln=%(ln)s" />
 
                 <input type="hidden" name="ln" value="%(ln)s" />
                 <table class="searchbox" width="100%%" summary="">
                   <tr>
                     <th class="portalboxheader">%(docfulldesc)s</th>
                   </tr>
                   <tr>
                       <td class="portalboxbody">%(description)s
                         <br />
                         <script language="JavaScript" type="text/javascript">
                         var nbimg = document.images.length + 1;
                         </script>
                         <br />
                         <table align="center" cellpadding="0" cellspacing="0" border="0">
                         <tr valign="top">
                 """ % {
                       'select_cat' : _("Please select a category"),
                       'doctype' : doctype,
                       'now' : now,
                       'pid' : pid,
                       'docfulldesc' : docfulldesc,
                       'description' : description,
                       'ln' : ln,
                     }
 
         if len(snameCateg) :
             out += """<td align="right">"""
             for i in range(0, len(snameCateg)):
                 out += """<label for="combo%(shortname)s">%(longname)s</label><input type="radio" name="combo%(doctype)s" id="combo%(shortname)s" value="%(shortname)s" onclick="clicked();" />&nbsp;<br />""" % {
                          'longname' : lnameCateg[i],
                          'doctype' : doctype,
                          'shortname' : snameCateg[i],
                        }
             out += "</td>"
         else:
             out += "<script>checked=1;</script>"
         out += """<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                   <td>
                     <table><tr><td>
                """
         #display list of actions
         for i in range(0, len(actionShortDesc)):
             out += """<input type="submit" class="adminbutton" value="%(status)s" onclick="if (tester()) { document.forms[0].indir.value='%(indir)s';document.forms[0].act.value='%(act)s';document.forms[0].submit();}; return false;" /><br />""" % {
                      'status' : statustext[i],
                      'indir' : indir[i],
                      'act' : actionShortDesc[i]
                    }
         out += """  </td></tr></table>
                     </td>
                 </tr>
                 </table>
                 <br />"""
         if len(snameCateg) :
             out += """<strong class="headline">%(notice)s:</strong><br />
                     %(select_cat)s""" % {
                      'notice' : _("Notice"),
                      'select_cat' : _("Select a category and then click on an action button."),
                     }
         out += """
                 <br /><br />
 
                 </td>
                 </tr>
                 </table>
                 </form>
                 <form action="/submit"><hr />
                   <font color="black"><small>%(continue_explain)s</small></font>
                   <table border="0" bgcolor="#CCCCCC" width="100%%"><tr>
                     <td width="100%%">
                     <small>Access Number: <input size="15" name="AN" />
                       <input type="hidden" name="doctype" value="%(doctype)s" />
                       <input type="hidden" name="ln" value="%(ln)s" />
                       <input class="adminbutton" type="submit" value=" %(go)s " />
                     </small>
                     </td></tr>
                   </table>
                   <hr />
                  </form>
                  """ % {
                 'continue_explain' : _("To continue with a previously interrupted submission, enter an access number into the box below:"),
                   'doctype' : doctype,
                   'go' : _("GO"),
                   'ln' : ln,
                 }
 
         return out
 
     def tmpl_warning_message(self, ln, msg):
         """
         Produces a warning message for the specified text
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'msg' *string* - The message to display
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         return """<center><font color="red">%s</font></center>""" % msg
 
     def tmpl_page_interface(self, ln, docname, actname, curpage, nbpages, file, nextPg, access, nbPg, doctype, act, indir, fields, javascript, mainmenu):
         """
         Produces a page with the specified fields (in the submit chain)
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The document type
 
           - 'docname' *string* - The document type name
 
           - 'actname' *string* - The action name
 
           - 'act' *string* - The action
 
           - 'curpage' *int* - The current page of submitting engine
 
           - 'nbpages' *int* - The total number of pages
 
           - 'nextPg' *int* - The next page
 
           - 'access' *string* - The submission number
 
           - 'nbPg' *string* - ??
 
           - 'indir' *string* - the directory of submitting
 
           - 'fields' *array* - the fields to display in the page, with each record having the structure:
 
               - 'fullDesc' *string* - the description of the field
 
               - 'text' *string* - the HTML code of the field
 
               - 'javascript' *string* - if the field has some associated javascript code
 
               - 'type' *string* - the type of field (T, F, I, H, D, S, R)
 
               - 'name' *string* - the name of the field
 
               - 'rows' *string* - the number of rows for textareas
 
               - 'cols' *string* - the number of columns for textareas
 
               - 'val' *string* - the default value of the field
 
               - 'size' *string* - the size for text fields
 
               - 'maxlength' *string* - the maximum length for text fields
 
               - 'htmlcode' *string* - the complete HTML code for user-defined fields
 
               - 'typename' *string* - the long name of the type
 
           - 'javascript' *string* - the javascript code to insert in the page
 
           - 'mainmenu' *string* - the url of the main menu
 
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         # top menu
         out = """
                 <form method="post" action="/submit" enctype="multipart/form-data" onsubmit="return tester();">
                 <center><table cellspacing="0" cellpadding="0" border="0">
                   <tr>
                     <td class="submitHeader"><b>%(docname)s&nbsp;</b></td>
                     <td class="submitHeader"><small>&nbsp;%(actname)s&nbsp;</small></td>
                     <td valign="bottom">
                         <table cellspacing="0" cellpadding="0" border="0" width="100%%">
                         <tr><td class="submitEmptyPage">&nbsp;&nbsp;</td>
               """ % {
                 'docname' : docname,
                 'actname' : actname,
               }
 
         for i in range(1, nbpages+1):
             if i == int(curpage):
                 out += """<td class="submitCurrentPage"><small>&nbsp;page: %s&nbsp;</small></td>""" % curpage
             else:
                 out += """<td class="submitPage"><small>&nbsp;<a href='' onclick="if (tester2() == 1){document.forms[0].curpage.value=%s;document.forms[0].submit();return false;} else { return false; }">%s</a>&nbsp;</small></td>""" % (i, i)
         out += """        <td class="submitEmptyPage">&nbsp;&nbsp;
                         </td></tr></table>
                     </td>
                     <td class="submitHeader" align="right">&nbsp;<a href="" onclick="window.open('/submit/summary?doctype=%(doctype)s&amp;act=%(act)s&amp;access=%(access)s&amp;indir=%(indir)s&amp;ln=%(ln)s','summary','scrollbars=yes,menubar=no,width=500,height=250');return false;"><font color="white"><small>%(summary)s(2)</small></font></a>&nbsp;</td>
                   </tr>
                   <tr><td colspan="5" class="submitHeader">
                     <table border="0" cellspacing="0" cellpadding="15" width="100%%" class="submitBody"><tr><td>
                      <br />
                      <input type="hidden" name="file" value="%(file)s" />
                      <input type="hidden" name="nextPg" value="%(nextPg)s" />
                      <input type="hidden" name="access" value="%(access)s" />
                      <input type="hidden" name="curpage" value="%(curpage)s" />
                      <input type="hidden" name="nbPg" value="%(nbPg)s" />
                      <input type="hidden" name="doctype" value="%(doctype)s" />
                      <input type="hidden" name="act" value="%(act)s" />
                      <input type="hidden" name="indir" value="%(indir)s" />
                      <input type="hidden" name="mode" value="U" />
                      <input type="hidden" name="step" value="0" />
                      <input type="hidden" name="ln" value="%(ln)s" />
                 """ % {
                  'summary' : _("SUMMARY"),
                  'doctype' : doctype,
                  'act' : act,
                  'access' : access,
                  'indir' : indir,
                  'file' : file,
                  'nextPg' : nextPg,
                  'curpage' : curpage,
                  'nbPg' : nbPg,
                  'ln' : ln,
                }
 
         for field in fields:
             if field['javascript']:
                 out += """<script language="JavaScript1.1"  type="text/javascript">
                           %s
                           </script>
                        """ % field['javascript']
 
             # now displays the html form field(s)
             out += "%s\n%s\n" % (field['fullDesc'], field['text'])
 
         out += javascript
         out += "<br />&nbsp;<br />&nbsp;</td></tr></table></td></tr>\n"
 
         # Display the navigation cell
         # Display "previous page" navigation arrows
         out += """<tr><td colspan="5"><table border="0" cellpadding="0" cellspacing="0" width="100%%"><tr>"""
         if int(curpage) != 1:
             out += """ <td class="submitHeader" align="left">&nbsp;
                          <a href='' onclick="if (tester2() == 1) {document.forms[0].curpage.value=%(prpage)s;document.forms[0].submit();return false;} else { return false; }">
                            <img src="%(images)s/left-trans.gif" alt="%(prevpage)s" border="0" />
                              <strong><font color="white">%(prevpage)s</font></strong>
                          </a>
                        </td>
             """ % {
               'prpage' : int(curpage) - 1,
               'images' : CFG_SITE_URL + '/img',
               'prevpage' : _("Previous page"),
             }
         else:
             out += """ <td class="submitHeader">&nbsp;</td>"""
         # Display the submission number
         out += """ <td class="submitHeader" align="center"><small>%(submission)s: %(access)s</small></td>\n""" % {
                 'submission' : _("Submission number") + '(1)',
                 'access' : access,
               }
         # Display the "next page" navigation arrow
         if int(curpage) != int(nbpages):
             out += """ <td class="submitHeader" align="right">
                          <a href='' onclick="if (tester2()){document.forms[0].curpage.value=%(nxpage)s;document.forms[0].submit();return false;} else {return false;}; return false;">
                           <strong><font color="white">%(nextpage)s</font></strong>
                           <img src="%(images)s/right-trans.gif" alt="%(nextpage)s" border="0" />
                         </a>
                        </td>
             """ % {
               'nxpage' : int(curpage) + 1,
               'images' : CFG_SITE_URL + '/img',
               'nextpage' : _("Next page"),
             }
         else:
             out += """ <td class="submitHeader">&nbsp;</td>"""
         out += """</tr></table></td></tr></table></center></form>
 
                   <br />
                   <br />
                  <a href="%(mainmenu)s" onclick="return confirm('%(surequit)s')">
                  <img src="%(images)s/mainmenu.gif" border="0" alt="%(back)s" align="right" /></a>
                  <br /><br />
                  <hr />
                   <small>%(take_note)s</small><br />
                   <small>%(explain_summary)s</small><br />
                """ % {
                  'surequit' : _("Are you sure you want to quit this submission?"),
                  'back' : _("Back to main menu"),
                  'mainmenu' : mainmenu,
                  'images' : CFG_SITE_URL + '/img',
                  'take_note' : '(1) ' + _("This is your submission access number. It can be used to continue with an interrupted submission in case of problems."),
                  'explain_summary' : '(2) ' + _("Mandatory fields appear in red in the SUMMARY window."),
                }
         return out
 
     def tmpl_submit_field(self, ln, field):
         """
         Produces the HTML code for the specified field
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'field' *array* - the field to display in the page, with the following structure:
 
               - 'javascript' *string* - if the field has some associated javascript code
 
               - 'type' *string* - the type of field (T, F, I, H, D, S, R)
 
               - 'name' *string* - the name of the field
 
               - 'rows' *string* - the number of rows for textareas
 
               - 'cols' *string* - the number of columns for textareas
 
               - 'val' *string* - the default value of the field
 
               - 'size' *string* - the size for text fields
 
               - 'maxlength' *string* - the maximum length for text fields
 
               - 'htmlcode' *string* - the complete HTML code for user-defined fields
 
               - 'typename' *string* - the long name of the type
 
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         # If the field is a textarea
         if field['type'] == 'T':
             ## Field is a textarea:
             text = "<textarea name=\"%s\" rows=\"%s\" cols=\"%s\">%s</textarea>" \
                   % (field['name'], field['rows'], field['cols'], cgi.escape(str(field['val']), 1))
         # If the field is a file upload
         elif field['type'] == 'F':
             ## the field is a file input:
             text = """<input type="file" name="%s" size="%s"%s />""" \
                    % (field['name'], field['size'], "%s" \
                       % ((field['maxlength'] in (0, None) and " ") or (""" maxlength="%s\"""" % field['maxlength'])) )
         # If the field is a text input
         elif field['type'] == 'I':
             ## Field is a text input:
             text = """<input type="text" name="%s" size="%s" value="%s"%s />""" \
                    % (field['name'], field['size'], field['val'], "%s" \
                       % ((field['maxlength'] in (0, None) and " ") or (""" maxlength="%s\"""" % field['maxlength'])) )
         # If the field is a hidden input
         elif field['type'] == 'H':
             text = "<input type=\"hidden\" name=\"%s\" value=\"%s\" />" % (field['name'], field['val'])
         # If the field is user-defined
         elif field['type'] == 'D':
             text = field['htmlcode']
         # If the field is a select box
         elif field['type'] == 'S':
             text = field['htmlcode']
         # If the field type is not recognized
         else:
             text = "%s: unknown field type" % field['typename']
 
         return text
 
     def tmpl_page_interface_js(self, ln, upload, field, fieldhtml, txt, check, level, curdir, values, select, radio, curpage, nbpages, returnto):
         """
         Produces the javascript for validation and value filling for a submit interface page
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'upload' *array* - booleans if the field is a <input type="file"> field
 
           - 'field' *array* - the fields' names
 
           - 'fieldhtml' *array* - the fields' HTML representation
 
           - 'txt' *array* - the fields' long name
 
           - 'check' *array* - if the fields should be checked (in javascript)
 
           - 'level' *array* - strings, if the fields should be filled (M) or not (O)
 
           - 'curdir' *array* - the current directory of the submission
 
           - 'values' *array* - the current values of the fields
 
           - 'select' *array* - booleans, if the controls are "select" controls
 
           - 'radio' *array* - booleans, if the controls are "radio" controls
 
           - 'curpage' *int* - the current page
 
           - 'nbpages' *int* - the total number of pages
 
           - 'returnto' *array* - a structure with 'field' and 'page', if a mandatory field on antoher page was not completed
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         nbFields = len(upload)
         # if there is a file upload field, we change the encoding type
         out = """<script language="JavaScript1.1" type="text/javascript">
               """
         for i in range(0,nbFields):
             if upload[i] == 1:
                 out += "document.forms[0].encoding = \"multipart/form-data\";\n"
                 break
         # we don't want the form to be submitted if the user enters 'Return'
         # tests if mandatory fields are well filled
         out += """function tester(){
                    return false;
                   }
                   function tester2() {
                """
         for i in range(0,nbFields):
             if re.search("%s\[\]" % field[i],fieldhtml[i]):
                 fieldname = "%s[]" % field[i]
             else:
                 fieldname = field[i]
             out += "  el = document.forms[0].elements['%s'];\n" % fieldname
             # If the field must be checked we call the checking function
             if check[i] != "":
                 out += """if (%(check)s(el.value) == 0) {
                             el.focus();
                             return 0;
                           } """ % {
                             'check' : check[i]
                           }
             # If the field is mandatory, we check a value has been selected
             if level[i] == 'M':
                 if select[i] != 0:
                     # If the field is a select box
                     out += """if ((el.selectedIndex == -1)||(el.selectedIndex == 0)){
                                     alert("%(field_mandatory)s");
                                     return 0;
                               } """ % {
                                 'field_mandatory' : _("The field %s is mandatory.") % txt[i] + '\\n' + _("Please make a choice in the select box")
                               }
                 elif radio[i] != 0:
                     # If the field is a radio buttonset
                     out += """var check=0;
                               for (var j = 0; j < el.length; j++) {
                                 if (el.options[j].checked){
                                   check++;
                                 }
                               }
                               if (check == 0) {
                                 alert("%(press_button)s");
                                 return 0;
                               }""" % {
                                 'press_button':_("Please press a button.")
                               }
                 else:
                     # If the field is a text input
                     out += """if (el.value == '') {
                                alert("%(field_mandatory)s");
                                return 0;
                               }""" % {
                                 'field_mandatory' : _("The field %s is mandatory. Please fill it in.") % txt[i]
                               }
         out += """  return 1;
                   }
                <!-- Fill the fields in with the previous saved values-->
                """
 
         # # # # # # # # # # # # # # # # # # # # # # # # #
         # Fill the fields with the previously saved values
         # # # # # # # # # # # # # # # # # # # # # # # # #
         for i in range(0,nbFields):
             if re.search("%s\[\]"%field[i],fieldhtml[i]):
                 fieldname = "%s[]" % field[i]
             else:
                 fieldname = field[i]
             text = values[i]
 
             if text != '':
                 if select[i] != 0:
                     # If the field is a SELECT element
                     vals = text.split("\n")
                     tmp=""
                     for val in vals:
                         if tmp != "":
                             tmp = tmp + " || "
                         tmp = tmp + "el.options[j].value == \"%s\" || el.options[j].text == \"%s\"" % (val,val)
                     if tmp != "":
                         out += """
                                  <!--SELECT field found-->
                                  el = document.forms[0].elements['%(fieldname)s'];
                                  for (var j = 0; j < el.length; j++){
                                    if (%(tmp)s){
                                      el.options[j].selected = true;
                                    }
                                  }""" % {
                                    'fieldname' : fieldname,
                                    'tmp' : tmp,
                                  }
                 elif radio[i] != 0:
                     # If the field is a RADIO element
                     out += """<!--RADIO field found-->
                               el = document.forms[0].elements['%(fieldname)s'];
                               if (el.value == "%(text)s"){
                                 el.checked=true;
                               }""" % {
                                 'fieldname' : fieldname,
                                 'text' : cgi.escape(str(text)),
                               }
                 elif upload[i] == 0:
                     text = text.replace('"','\"')
                     text = text.replace("\n","\\n")
                     # If the field is not an upload element
                     out += """<!--input field found-->
                                el = document.forms[0].elements['%(fieldname)s'];
                                el.value="%(text)s";
                            """ % {
                              'fieldname' : fieldname,
                              'text' : cgi.escape(str(text)),
                            }
         out += """<!--End Fill in section-->
                """
 
         # JS function finish
         # This function tests each mandatory field in the whole submission and checks whether
         # the field has been correctly filled in or not
         # This function is called when the user presses the "End
         # Submission" button
         if int(curpage) == int(nbpages):
             out += """function finish() {
                    """
             if returnto:
                 out += """alert ("%(msg)s");
                           document.forms[0].curpage.value="%(page)s";
                           document.forms[0].submit();
                          }
                        """ % {
                          'msg' : _("The field %(field)s is mandatory.") + '\n' \
                                  + _("Going back to page") \
                                  + str(returnto['page']),
                          'page' : returnto['page']
                        }
             else:
                 out += """ if (tester2()) {
                              document.forms[0].action="/submit";
                              document.forms[0].step.value=1;
                              document.forms[0].submit();
                            } else {
                              return false;
                            }
                          }"""
         out += """</script>"""
         return out
 
     def tmpl_page_endaction(self, ln, file, nextPg, startPg, access, curpage, nbPg, nbpages, doctype, act, docname, actname, indir, mainmenu, finished, function_content, next_action):
         """
         Produces the pages after all the fields have been submitted.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The document type
 
           - 'act' *string* - The action
 
           - 'docname' *string* - The document type name
 
           - 'actname' *string* - The action name
 
           - 'curpage' *int* - The current page of submitting engine
 
           - 'startPg' *int* - The start page
 
           - 'nextPg' *int* - The next page
 
           - 'access' *string* - The submission number
 
           - 'nbPg' *string* - total number of pages
 
           - 'nbpages' *string* - number of pages (?)
 
           - 'indir' *string* - the directory of submitting
 
           - 'file' *string* - ??
 
           - 'mainmenu' *string* - the url of the main menu
 
           - 'finished' *bool* - if the submission is finished
 
           - 'function_content' *string* - HTML code produced by some function executed
 
           - 'next_action' *string* - if there is another action to be completed, the HTML code for linking to it
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """
           <form ENCTYPE="multipart/form-data" action="/submit" method="post">
           <input type="hidden" name="file" value="%(file)s" />
           <input type="hidden" name="nextPg" value="%(nextPg)s" />
           <input type="hidden" name="startPg" value="%(startPg)s" />
           <input type="hidden" name="access" value="%(access)s" />
           <input type="hidden" name="curpage" value="%(curpage)s" />
           <input type="hidden" name="nbPg" value="%(nbPg)s" />
           <input type="hidden" name="doctype" value="%(doctype)s" />
           <input type="hidden" name="act" value="%(act)s" />
           <input type="hidden" name="indir" value="%(indir)s" />
           <input type="hidden" name="fromdir" value="" />
           <input type="hidden" name="mainmenu" value="%(mainmenu)s" />
 
           <input type="hidden" name="mode" value="U" />
           <input type="hidden" name="step" value="1" />
           <input type="hidden" name="deleted" value="no" />
           <input type="hidden" name="file_path" value="" />
           <input type="hidden" name="userfile_name" value="" />
 
           <input type="hidden" name="ln" value="%(ln)s" />
           <center><table cellspacing="0" cellpadding="0" border="0"><tr>
              <td class="submitHeader"><b>%(docname)s&nbsp;</b></td>
              <td class="submitHeader"><small>&nbsp;%(actname)s&nbsp;</small></td>
              <td valign="bottom">
                  <table cellspacing="0" cellpadding="0" border="0" width="100%%">
                  <tr><td class="submitEmptyPage">&nbsp;&nbsp;</td>
               """ % {
                 'file' : file,
                 'nextPg' : nextPg,
                 'startPg' : startPg,
                 'access' : access,
                 'curpage' : curpage,
                 'nbPg' : nbPg,
                 'doctype' : doctype,
                 'act' : act,
                 'docname' : docname,
                 'actname' : actname,
                 'indir' : indir,
                 'mainmenu' : mainmenu,
                 'ln' : ln,
               }
 
         if finished == 1:
             out += """<td class="submitCurrentPage">%(finished)s</td>
                       <td class="submitEmptyPage">&nbsp;&nbsp;</td>
                      </tr></table>
                     </td>
                     <td class="submitEmptyPage" align="right">&nbsp;</td>
                    """ % {
                      'finished' : _("finished!"),
                    }
         else:
             for i in range(1, nbpages + 1):
                 out += """<td class="submitPage"><small>&nbsp;
                             <a href='' onclick="document.forms[0].curpage.value=%s;document.forms[0].action='/submit';document.forms[0].step.value=0;document.forms[0].submit();return false;">%s</a>&nbsp;</small></td>""" % (i,i)
             out += """<td class="submitCurrentPage">%(end_action)s</td><td class="submitEmptyPage">&nbsp;&nbsp;</td></tr></table></td>
                       <td class="submitHeader" align="right">&nbsp;<a href='' onclick="window.open('/submit/summary?doctype=%(doctype)s&amp;act=%(act)s&amp;access=%(access)s&amp;indir=%(indir)s&amp;ln=%(ln)s','summary','scrollbars=yes,menubar=no,width=500,height=250');return false;"><font color="white"><small>%(summary)s(2)</small></font></a>&nbsp;</td>""" % {
                         'end_action' : _("end of action"),
                         'summary' : _("SUMMARY"),
                         'doctype' : doctype,
                         'act' : act,
                         'access' : access,
                         'indir' : indir,
                         'ln' : ln,
                       }
         out += """</tr>
                   <tr>
                     <td colspan="5" class="submitBody">
                       <small><br /><br />
                       %(function_content)s
                       %(next_action)s
                       <br /><br />
                     </td>
                 </tr>
                 <tr class="submitHeader">
                     <td class="submitHeader" colspan="5" align="center">""" % {
                        'function_content' : function_content,
                        'next_action' : next_action,
                      }
         if finished == 0:
             out += """<small>%(submission)s</small>&sup2;:
                       <small>%(access)s</small>""" % {
                         'submission' : _("Submission no"),
                         'access' : access,
                       }
         else:
             out += "&nbsp;\n"
         out += """
             </td>
         </tr>
         </table>
         </center>
         </form>
         <br />
         <br />"""
         # Add the "back to main menu" button
         if finished == 0:
             out += """ <a href="%(mainmenu)s" onclick="return confirm('%(surequit)s')">
                        <img src="%(images)s/mainmenu.gif" border="0" alt="%(back)s" align="right" /></a>
                        <br /><br />""" % {
                            'surequit' : _("Are you sure you want to quit this submission?"),
                            'back' : _("Back to main menu"),
                            'images' : CFG_SITE_URL + '/img',
                            'mainmenu' : mainmenu
                            }
         else:
             out += """ <a href="%(mainmenu)s">
                        <img src="%(images)s/mainmenu.gif" border="0" alt="%(back)s" align="right" /></a>
                        <br /><br />""" % {
                      'back' : _("Back to main menu"),
                      'images' : CFG_SITE_URL + '/img',
                      'mainmenu' : mainmenu,
                    }
 
         return out
 
     def tmpl_function_output(self, ln, display_on, action, doctype, step, functions):
         """
         Produces the output of the functions.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'display_on' *bool* - If debug information should be displayed
 
           - 'doctype' *string* - The document type
 
           - 'action' *string* - The action
 
           - 'step' *int* - The current step in submission
 
           - 'functions' *aray* - HTML code produced by functions executed and informations about the functions
 
               - 'name' *string* - the name of the function
 
               - 'score' *string* - the score of the function
 
               - 'error' *bool* - if the function execution produced errors
 
               - 'text' *string* - the HTML code produced by the function
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = ""
         if display_on:
             out += """<br /><br />%(function_list)s<P>
                       <table border="1" cellpadding="15">
                         <tr><th>%(function)s</th><th>%(score)s</th><th>%(running)s</th></tr>
                    """ % {
                      'function_list' : _("Here is the %(x_action)s function list for %(x_doctype)s documents at level %(x_step)s") % {
                                          'x_action' : action,
                                          'x_doctype' : doctype,
                                          'x_step' : step,
                                        },
                      'function' : _("Function"),
                      'score' : _("Score"),
                      'running' : _("Running function"),
                    }
             for function in functions:
                 out += """<tr><td>%(name)s</td><td>%(score)s</td><td>%(result)s</td></tr>""" % {
                           'name' : function['name'],
                           'score' : function['score'],
                           'result' : function['error'] and (_("Function %s does not exist.") % function['name'] + "<br />") or function['text']
                         }
             out += "</table>"
         else:
             for function in functions:
                 if not function['error']:
                     out += function['text']
 
         return out
 
     def tmpl_next_action(self, ln, actions):
         """
         Produces the output of the functions.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'actions' *array* - The actions to display, in the structure
 
               - 'page' *string* - the starting page
 
               - 'action' *string* - the action (in terms of submission)
 
               - 'doctype' *string* - the doctype
 
               - 'nextdir' *string* - the path to the submission data
 
               - 'access' *string* - the submission number
 
               - 'indir' *string* - ??
 
               - 'name' *string* - the name of the action
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = "<br /><br />%(haveto)s<ul>" % {
                 'haveto' : _("You must now"),
               }
         i = 0
         for action in actions:
             if i > 0:
                 out += " <b>" + _("or") + "</b> "
             i += 1
             out += """<li><a href="" onclick="document.forms[0].action='/submit';document.forms[0].curpage.value='%(page)s';document.forms[0].startPg.value='%(page)s';document.forms[0].act.value='%(action)s';document.forms[0].doctype.value='%(doctype)s';document.forms[0].indir.value='%(nextdir)s';document.forms[0].access.value='%(access)s';document.forms[0].fromdir.value='%(indir)s';document.forms[0].submit();return false;"> %(name)s </a></li>""" % action
 
         out += "</ul>"
         return out
 
     def tmpl_filelist(self, ln, filelist='', recid='', docname='', version=''):
         """
         Displays the file list for a record.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'recid' *int* - The record id
 
           - 'docname' *string* - The document name
 
           - 'version' *int* - The version of the document
 
           - 'filelist' *string* - The HTML string of the filelist (produced by the BibDoc classes)
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         title = _("record") + ' #' + '<a href="%s/record/%s">%s</a>' % (CFG_SITE_URL, recid, recid)
         if docname != "":
             title += ' ' + _("document") + ' #' + str(docname)
         if version != "":
             title += ' ' + _("version") + ' #' + str(version)
 
         out = """<div style="width:90%%;margin:auto;min-height:100px;margin-top:10px">
                 <!--start file list-->
                   %s
                 <!--end file list--></div>
               """ % (filelist)
 
         return out
 
     def tmpl_bibrecdoc_filelist(self, ln, types, verbose_files=''):
         """
         Displays the file list for a record.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'types' *array* - The different types to display, each record in the format:
 
                - 'name' *string* - The name of the format
 
                - 'content' *array of string* - The HTML code produced by tmpl_bibdoc_filelist, for the right files
 
           - 'verbose_files' - A string representing in a verbose way the
           file information.
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = ""
         for mytype in types:
             out += "<small><b>%s</b> %s:</small>" % (mytype['name'], _("file(s)"))
             out += "<ul>"
             for content in mytype['content']:
                 out += content
             out += "</ul>"
             if verbose_files:
                 out += "<pre>%s</pre>" % verbose_files
         return out
 
     def tmpl_bibdoc_filelist(self, ln, versions=[], imageurl='', recid='', docname=''):
         """
         Displays the file list for a record.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'versions' *array* - The different versions to display, each record in the format:
 
                - 'version' *string* - The version
 
                - 'content' *string* - The HTML code produced by tmpl_bibdocfile_filelist, for the right file
 
                - 'previous' *bool* - If the file has previous versions
 
           - 'imageurl' *string* - The URL to the file image
 
          - 'recid' *int* - The record id
 
          - 'docname' *string* - The name of the document
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """<table border="0" cellspacing="1" class="searchbox">
                    <tr>
                      <td align="left" colspan="2" class="portalboxheader">
                        <img src='%(imageurl)s' border="0" />&nbsp;&nbsp;%(docname)s
                      </td>
                    </tr>""" % {
                      'imageurl' : imageurl,
                      'docname' : docname
                    }
         for version in versions:
             if version['previous']:
                 versiontext =  """<br />(%(see)s <a href="%(siteurl)s/record/%(recID)s/files/?docname=%(docname)s&amp;version=all%(ln_link)s">%(previous)s</a>)""" % {
                                  'see' : _("see"),
                                  'siteurl' : CFG_SITE_URL,
                                  'docname' : urllib.quote(docname),
                                  'recID': recid,
                                  'previous': _("previous"),
                                  'ln_link': (ln != CFG_SITE_LANG and '&amp;ln=' + ln) or '',
                                }
             else:
                 versiontext = ""
             out += """<tr>
                         <td class="portalboxheader">
                           <font size="-2">%(version)s %(ver)s%(text)s</font>
                         </td>
                         <td>
                           <table>
                         """ % {
                           'version' : _("version"),
                           'ver' : version['version'],
                           'text' : versiontext,
                         }
             for content in version['content']:
                 out += content
             out += "</table></td></tr>"
         out += "</table>"
         return out
 
     def tmpl_bibdocfile_filelist(self, ln, recid, name, version, format, size):
         """
         Displays a file in the file list.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'recid' *int* - The id of the record
 
           - 'name' *string* - The name of the file
 
           - 'version' *string* - The version
 
           - 'format' *string* - The display format
 
           - 'size' *string* - The size of the file
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         return """<tr>
                     <td valign="top">
                       <small><a href="%(siteurl)s/record/%(recid)s/files/%(quoted_name)s%(quoted_format)s?version=%(version)s">
                         %(name)s%(format)s
                       </a></small>
                     </td>
                     <td valign="top">
                       <font size="-2" color="green">[%(size)s&nbsp;B]</font>
                     </td></tr>""" % {
                       'siteurl' : CFG_SITE_URL,
                       'recid' : recid,
                       'quoted_name' : urllib.quote(name),
                       'name' : name,
                       'version' : version,
                       'name' : name,
                       'quoted_format' : urllib.quote(format),
                       'format' : format,
                       'size' : size
                     }
 
     def tmpl_submit_summary (self, ln, values):
         """
         Displays the summary for the submit procedure.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'values' *array* - The values of submit. Each of the records contain the following fields:
 
                 - 'name' *string* - The name of the field
 
                 - 'mandatory' *bool* - If the field is mandatory or not
 
                 - 'value' *string* - The inserted value
 
                 - 'page' *int* - The submit page on which the field is entered
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """<body style="background-image: url(%(images)s/header_background.gif);"><table border="0">""" % \
               { 'images' : CFG_SITE_URL + '/img' }
 
         for value in values:
             if value['mandatory']:
                 color = "red"
             else:
                 color = ""
             out += """<tr>
                         <td align="right">
                           <small>
                             <a href='' onclick="window.opener.document.forms[0].curpage.value='%(page)s';window.opener.document.forms[0].action='/submit?ln=%(ln)s';window.opener.document.forms[0].submit();return false;">
                               <font color="%(color)s">%(name)s</font>
                             </a>
                           </small>
                         </td>
                         <td>
                           <i><small><font color="black">%(value)s</font></small></i>
                         </td>
                       </tr>""" % {
                         'color' : color,
                         'name' : value['name'],
                         'value' : value['value'],
                         'page' : value['page'],
                         'ln' : ln
                       }
         out += "</table>"
         return out
 
     def tmpl_yoursubmissions(self, ln, order, doctypes, submissions):
         """
         Displays the list of the user's submissions.
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'order' *string* - The ordering parameter
 
           - 'doctypes' *array* - All the available doctypes, in structures:
 
               - 'id' *string* - The doctype id
 
               - 'name' *string* - The display name of the doctype
 
               - 'selected' *bool* - If the doctype should be selected
 
           - 'submissions' *array* - The available submissions, in structures:
 
               - 'docname' *string* - The document name
 
               - 'actname' *string* - The action name
 
               - 'status' *string* - The status of the document
 
               - 'cdate' *string* - Creation date
 
               - 'mdate' *string* - Modification date
 
               - 'id' *string* - The id of the submission
 
               - 'reference' *string* - The display name of the doctype
 
               - 'pending' *bool* - If the submission is pending
 
               - 'act' *string* - The action code
 
               - 'doctype' *string* - The doctype code
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
 
         out = ""
         out += """
                   <br />
                   <form action="">
                   <input type="hidden" value="%(order)s" name="order" />
                   <input type="hidden" name="deletedId" />
                   <input type="hidden" name="deletedDoctype" />
                   <input type="hidden" name="deletedAction" />
                   <input type="hidden" name="ln" value="%(ln)s"/>
                   <table class="searchbox" width="100%%" summary="" >
                     <tr>
                       <th class="portalboxheader"><small>%(for)s</small>&nbsp;
                         <select name="doctype" onchange="document.forms[0].submit();">
                           <option value="">%(alltype)s</option>
                   """ % {
                     'order' : order,
                     'for' : _("For"),
                     'alltype' : _("all types of document"),
                     'ln' : ln,
                   }
         for doctype in doctypes:
             out += """<option value="%(id)s" %(sel)s>%(name)s</option>""" % {
                      'id' : doctype['id'],
                      'name' : doctype['name'],
                      'sel' : doctype['selected'] and "selected=\"selected\"" or ""
                    }
         out += """     </select>
                       </th>
                     </tr>
                     <tr>
                      <td class="portalboxbody">
                       <table>
                         <tr>
                           <td></td>
                         </tr>
                """
 
         num = 0
         docname = ""
         for submission in submissions:
             if submission['docname'] != docname:
                 docname = submission['docname']
                 out += """</table>
                           %(docname)s<br />
                           <table border="0" class="searchbox" align="left" width="100%%">
                             <tr>
                               <th class="headerselected">%(action)s&nbsp;&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="actiondown";document.forms[0].submit();return false;'><img src="%(images)s/smalldown.gif" alt="down" border="0" /></a>&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="actionup";document.forms[0].submit();return false;'><img src="%(images)s/smallup.gif" alt="up" border="0" /></a>
                               </th>
                               <th class="headerselected">%(status)s&nbsp;&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="statusdown";document.forms[0].submit();return false;'><img src="%(images)s/smalldown.gif" alt="down" border="0" /></a>&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="statusup";document.forms[0].submit();return false;'><img src="%(images)s/smallup.gif" alt="up" border="0" /></a>
                               </th>
                               <th class="headerselected">%(id)s</th>
                               <th class="headerselected">%(reference)s&nbsp;&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="refdown";document.forms[0].submit();return false;'><img src="%(images)s/smalldown.gif" alt="down" border="0" /></a>&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="refup";document.forms[0].submit();return false;'><img src="%(images)s/smallup.gif" alt="up" border="0" /></a>
                               </th>
                               <th class="headerselected">%(first)s&nbsp;&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="cddown";document.forms[0].submit();return false;'><img src="%(images)s/smalldown.gif" alt="down" border="0" /></a>&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="cdup";document.forms[0].submit();return false;'><img src="%(images)s/smallup.gif" alt="up" border="0" /></a>
                               </th>
                               <th class="headerselected">%(last)s&nbsp;&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="mddown";document.forms[0].submit();return false;'><img src="%(images)s/smalldown.gif" alt="down" border="0" /></a>&nbsp;
                                 <a href='' onclick='document.forms[0].order.value="mdup";document.forms[0].submit();return false;'><img src="%(images)s/smallup.gif" alt="up" border="0" /></a>
                               </th>
                             </tr>
                        """ % {
                          'docname' : submission['docname'],
                          'action' : _("Action"),
                          'status' : _("Status"),
                          'id' : _("Id"),
                          'reference' : _("Reference"),
                          'images' : CFG_SITE_URL + '/img',
                          'first' : _("First access"),
                          'last' : _("Last access"),
                        }
             if submission['pending']:
                 idtext = """<a href="submit/sub?access=%(id)s@%(action)s%(doctype)s%(ln_link)s">%(id)s</a>
                             &nbsp;<a onclick='if (confirm("%(sure)s")){document.forms[0].deletedId.value="%(id)s";document.forms[0].deletedDoctype.value="%(doctype)s";document.forms[0].deletedAction.value="%(action)s";document.forms[0].submit();return true;}else{return false;}' href=''><img src="%(images)s/smallbin.gif" border="0" alt='%(delete)s' /></a>
                          """ % {
                            'images' : CFG_SITE_URL + '/img',
                            'id' : submission['id'],
                            'action' : submission['act'],
                            'doctype' : submission['doctype'],
                            'sure' : _("Are you sure you want to delete this submission?"),
                            'delete' : _("Delete submission %(x_id)s in %(x_docname)s") % {
                                         'x_id' : str(submission['id']),
                                         'x_docname' : str(submission['docname'])
                                       },
                            'ln_link': (ln != CFG_SITE_LANG and '&amp;ln=' + ln) or ''
                          }
             else:
                 idtext = submission['id']
 
             if operator.mod(num,2) == 0:
                 color = "#e0e0e0"
             else:
                 color = "#eeeeee"
 
             if submission['reference']:
                 reference = submission['reference']
             else:
                 reference = """<font color="red">%s</font>""" % _("Reference not yet given")
 
             cdate = str(submission['cdate']).replace(" ","&nbsp;")
             mdate= str(submission['mdate']).replace(" ","&nbsp;")
 
             out += """
                      <tr bgcolor="%(color)s">
                        <td align="center" class="mycdscell">
                          <small>%(actname)s</small>
                        </td>
                        <td align="center" class="mycdscell">
                          <small>%(status)s</small>
                        </td>
                        <td class="mycdscell">
                          <small>%(idtext)s</small>
                        </td>
                        <td class="mycdscell">
                          <small>&nbsp;%(reference)s</small>
                        </td>
                        <td class="mycdscell">
                          <small>%(cdate)s</small>
                        </td>
                        <td class="mycdscell">
                          <small>%(mdate)s</small>
                        </td>
                      </tr>
                    """ % {
                      'color' : color,
                      'actname' : submission['actname'],
                      'status' : submission['status'],
                      'idtext' : idtext,
                      'reference' : reference,
                      'cdate' : cdate,
                      'mdate' : mdate,
                    }
             num += 1
 
         out += "</table></td></tr></table></form>"
         return out
 
 
     def tmpl_yourapprovals(self, ln, referees):
         """
         Displays the doctypes and categories for which the user is referee
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'referees' *array* - All the doctypes for which the user is referee:
 
               - 'doctype' *string* - The doctype
 
               - 'docname' *string* - The display name of the doctype
 
               - 'categories' *array* - The specific categories for which the user is referee:
 
                     - 'id' *string* - The category id
 
                     - 'name' *string* - The display name of the category
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """ <table class="searchbox" width="100%%" summary="">
                     <tr>
                         <th class="portalboxheader">%(refdocs)s</th>
                     </tr>
                     <tr>
                     <td class="portalboxbody">""" % {
                       'refdocs' : _("Refereed Documents"),
                     }
 
         for doctype in referees:
             out += """<ul><li><b>%(docname)s</b><ul>""" % doctype
 
             if doctype ['categories'] is None:
                 out += '''<li><a href="publiline.py?doctype=%(doctype)s%(ln_link)s">%(generalref)s</a></li>''' % {
                     'docname' : doctype['docname'],
                     'doctype' : doctype['doctype'],
                     'generalref' : _("You are a general referee"),
-                    'ln_link': (ln != CFG_SITE_LANG and '&amp;ln=' + ln) or ''}
+                    'ln_link': '&amp;ln=' + ln}
 
             else:
                 for category in doctype['categories']:
                     out += """<li><a href="publiline.py?doctype=%(doctype)s&amp;categ=%(categ)s%(ln_link)s">%(referee)s</a></li>""" % {
                         'referee' : _("You are a referee for category:") + ' ' + str(category['name']) + ' (' + str(category['id']) + ')',
 			'doctype' : doctype['doctype'],
                         'categ' : category['id'],
-                        'ln_link': (ln != CFG_SITE_LANG and '&amp;ln=' + ln) or ''}
+                        'ln_link': '&amp;ln=' + ln}
 
             out += "</ul><br /></li></ul>"
 
         out += "</td></tr></table>"
         out += '''<p>To see the status of documents for which approval has been requested, click <a href=\"%(url)s/publiline.py?flow=cplx\">here</a></p>''' % {'url' : CFG_SITE_URL}
         return out
 
     def tmpl_publiline_selectdoctype(self, ln, docs):
         """
         Displays the doctypes that the user can select
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'docs' *array* - All the doctypes that the user can select:
 
               - 'doctype' *string* - The doctype
 
               - 'docname' *string* - The display name of the doctype
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """
                <table class="searchbox" width="100%%" summary="">
                   <tr>
                       <th class="portalboxheader">%(list)s</th>
                   </tr>
                   <tr>
                       <td class="portalboxbody">
               %(select)s:
             </small>
             <blockquote>""" % {
               'list' : _("List of refereed types of documents"),
               'select' : _("Select one of the following types of documents to check the documents status"),
             }
 
         for doc in docs:
             params = {'ln' : ln}
             params.update(doc)
             out += '<li><a href="publiline.py?doctype=%(doctype)s&amp;ln=%(ln)s">%(docname)s</a></li><br />' % params
 
         out += """</blockquote>
                 </td>
             </tr>
         </table>
 
         <a href="publiline.py?flow=cplx&amp;ln=%s">%s</a>""" % (ln, _("Go to specific approval workflow"))
         return out
 
     def tmpl_publiline_selectcplxdoctype(self, ln, docs):
         """
         Displays the doctypes that the user can select in a complex workflow
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'docs' *array* - All the doctypes that the user can select:
 
               - 'doctype' *string* - The doctype
 
               - 'docname' *string* - The display name of the doctype
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """
                <table class="searchbox" width="100%%" summary="">
                   <tr>
                       <th class="portalboxheader">%(list)s</th>
                   </tr>
                   <tr>
                       <td class="portalboxbody">
               %(select)s:
             </small>
             <blockquote>""" % {
               'list' : _("List of refereed types of documents"),
               'select' : _("Select one of the following types of documents to check the documents status"),
             }
 
         for doc in docs:
             params = {'ln' : ln}
             params.update(doc)
             out += '<li><a href="publiline.py?flow=cplx&doctype=%(doctype)s&amp;ln=%(ln)s">%(docname)s</a></li><br />' % params
 
         out += """</blockquote> </td> </tr> </table> </li><br/>"""
         return out
 
     def tmpl_publiline_selectcateg(self, ln, doctype, title, categories):
         """
         Displays the categories from a doctype that the user can select
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The doctype
 
           - 'title' *string* - The doctype name
 
           - 'categories' *array* - All the categories that the user can select:
 
               - 'id' *string* - The id of the category
 
               - 'waiting' *int* - The number of documents waiting
 
               - 'approved' *int* - The number of approved documents
 
               - 'rejected' *int* - The number of rejected documents
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """
                <table class="searchbox" width="100%%" summary="">
                   <tr>
                     <th class="portalboxheader">%(title)s: %(list_categ)s</th>
                   </tr>
                   <tr>
                       <td class="portalboxbody">
                       %(choose_categ)s
                       <blockquote>
                       <form action="publiline.py" method="get">
                           <input type="hidden" name="doctype" value="%(doctype)s" />
                           <input type="hidden" name="categ" value="" />
                           <input type="hidden" name="ln" value="%(ln)s" />
                           </form>
                <table>
                  <tr>
                  <td align="left">""" % {
                  'title' : title,
                  'doctype' : doctype,
                  'list_categ' : _("List of refereed categories"),
                  'choose_categ' : _("Please choose a category"),
                  'ln' : ln,
                }
 
         for categ in categories:
             num = categ['waiting'] + categ['approved'] + categ['rejected']
 
             if categ['waiting'] != 0:
                 classtext = "class=\"blocknote\""
             else:
                 classtext = ""
 
             out += """<a href="" onclick="document.forms[0].categ.value='%(id)s';document.forms[0].submit();return false;"><small %(classtext)s>%(id)s</small></a><small> (%(num)s document(s)""" % {
                      'id' : categ['id'],
                      'classtext' : classtext,
                      'num' : num,
                    }
             if categ['waiting'] != 0:
                 out += """| %(waiting)s <img alt="%(pending)s" src="%(images)s/waiting_or.gif" border="0" />""" % {
                           'waiting' : categ['waiting'],
                           'pending' : _("Pending"),
                           'images' : CFG_SITE_URL + '/img',
                         }
             if categ['approved'] != 0:
                 out += """| %(approved)s<img alt="%(approved_text)s" src="%(images)s/smchk_gr.gif" border="0" />""" % {
                           'approved' : categ['approved'],
                           'approved_text' : _("Approved"),
                           'images' : CFG_SITE_URL + '/img',
                         }
             if categ['rejected'] != 0:
                 out += """| %(rejected)s<img alt="%(rejected_text)s" src="%(images)s/cross_red.gif" border="0" />""" % {
                           'rejected' : categ['rejected'],
                           'rejected_text' : _("Rejected"),
                           'images' : CFG_SITE_URL + '/img',
                         }
             out += ")</small><br />"
 
         out += """
                     </td>
                     <td>
                      <table class="searchbox" width="100%%" summary="">
                         <tr>
                             <th class="portalboxheader">%(key)s:</th>
                         </tr>
                         <tr>
                             <td>
                               <img alt="%(pending)s" src="%(images)s/waiting_or.gif" border="0" /> %(waiting)s<br />
                               <img alt="%(approved)s" src="%(images)s/smchk_gr.gif" border="0" /> %(already_approved)s<br />
                               <img alt="%(rejected)s" src="%(images)s/cross_red.gif" border="0" /> %(rejected_text)s<br /><br />
                               <small class="blocknote">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small> %(somepending)s<br />
                             </td>
                         </tr>
                     </table>
                   </td>
                 </tr>
                 </table>
               </blockquote>
               </td>
              </tr>
             </table>""" % {
               'key' : _("Key"),
               'pending' : _("Pending"),
               'images' : CFG_SITE_URL + '/img',
               'waiting' : _("Waiting for approval"),
               'approved' : _("Approved"),
               'already_approved' : _("Already approved"),
               'rejected' : _("Rejected"),
               'rejected_text' : _("Rejected"),
               'somepending' : _("Some documents are pending."),
             }
         return out
 
     def tmpl_publiline_selectcplxcateg(self, ln, doctype, title, types):
         """
         Displays the categories from a doctype that the user can select
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The doctype
 
           - 'title' *string* - The doctype name
 
           - 'categories' *array* - All the categories that the user can select:
 
               - 'id' *string* - The id of the category
 
               - 'waiting' *int* - The number of documents waiting
 
               - 'approved' *int* - The number of approved documents
 
               - 'rejected' *int* - The number of rejected documents
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = ""
         #out = """
         #       <table class="searchbox" width="100%%" summary="">
         #          <tr>
         #            <th class="portalboxheader">%(title)s: %(list_type)s</th>
         #          </tr>
         #       </table><br />
         #       <table class="searchbox" width="100%%" summary="">
         #          <tr>""" % {
         #          'title' : title,
         #          'list_type' : _("List of specific approvals"),
         #      }
 
         columns = []
         columns.append ({'apptype' : 'RRP',
                          'list_categ' : _("List of refereing categories"),
                          'id_form' : 0,
                        })
         #columns.append ({'apptype' : 'RPB',
         #                 'list_categ' : _("List of publication categories"),
         #                 'id_form' : 1,
         #               })
         #columns.append ({'apptype' : 'RDA',
         #                 'list_categ' : _("List of direct approval categories"),
         #                 'id_form' : 2,
         #               })
 
         for column in columns:
             out += """
                       <td>
                            <table class="searchbox" width="100%%" summary="">
                               <tr>
                                 <th class="portalboxheader">%(list_categ)s</th>
                               </tr>
                               <tr>
                                   <td class="portalboxbody">
                                   %(choose_categ)s
                                   <blockquote>
                                   <form action="publiline.py" method="get">
                                       <input type="hidden" name="flow" value="cplx" />
                                       <input type="hidden" name="doctype" value="%(doctype)s" />
                                       <input type="hidden" name="categ" value="" />
                                       <input type="hidden" name="apptype" value="%(apptype)s" />
                                       <input type="hidden" name="ln" value="%(ln)s" />
                                       </form>
                            <table>
                              <tr>
                              <td align="left">""" % {
                              'doctype' : doctype,
                              'apptype' : column['apptype'],
                              'list_categ' : column['list_categ'],
                              'choose_categ' : _("Please choose a category"),
                              'ln' : ln,
                    }
 
             for categ in types[column['apptype']]:
                 num = categ['waiting'] + categ['approved'] + categ['rejected'] + categ['cancelled']
 
                 if categ['waiting'] != 0:
                     classtext = "class=\"blocknote\""
                 else:
                     classtext = ""
 
                 out += """<table><tr><td width="200px">*&nbsp<a href="" onclick="document.forms[%(id_form)s].categ.value='%(id)s';document.forms[%(id_form)s].submit();return false;"><small %(classtext)s>%(desc)s</small></td><td width="150px"></a><small> Total document(s) : %(num)s """ % {
                          'id' : categ['id'],
                          'id_form' : column['id_form'],
                          'classtext' : classtext,
                          'num' : num,
                          'desc' : categ['desc'],
                        }
                 out += """<td width="100px">"""
                 #if categ['waiting'] != 0:
                 out += """ %(waiting)s &nbsp&nbsp<img alt="%(pending)s" src="%(images)s/waiting_or.gif" border="0" /></td>""" % {
                               'waiting' : categ['waiting'],
                               'pending' : _("Pending"),
                               'images' : CFG_SITE_URL + '/img',
                             }
                 out += """<td width="100px">"""
                 #if categ['approved'] != 0:
                 out += """ %(approved)s &nbsp&nbsp<img alt="%(approved_text)s" src="%(images)s/smchk_gr.gif" border="0" /></td>""" % {
                               'approved' : categ['approved'],
                               'approved_text' : _("Approved"),
                               'images' : CFG_SITE_URL + '/img',
                             }
                 out += """<td width="100px">"""
                 #if categ['rejected'] != 0:
                 out += """ %(rejected)s&nbsp&nbsp<img alt="%(rejected_text)s" src="%(images)s/cross_red.gif" border="0" /></td>""" % {
                               'rejected' : categ['rejected'],
                               'rejected_text' : _("Rejected"),
                               'images' : CFG_SITE_URL + '/img',
                             }
                 out += """<td width="100px">"""
                 #if categ['cancelled'] != 0:
                 out += """ %(cancelled)s&nbsp&nbsp<img alt="%(cancelled_text)s" src="%(images)s/smchk_rd.gif" border="0" /></td>""" % {
                               'cancelled' : categ['cancelled'],
                               'cancelled_text' : _("Cancelled"),
                               'images' : CFG_SITE_URL + '/img',
                             }
                 out += "</small></td></tr>"
 
             out += """
 				</table>
                                 </td>
                             </tr>
                             </table>
                           </blockquote>
                           </td>
                          </tr>
                         </table>
                       </td>"""
 
         # Key
         out += """
                <table class="searchbox" width="100%%" summary="">
                         <tr>
                             <th class="portalboxheader">%(key)s:</th>
                         </tr>
                         <tr>
                             <td>
                               <img alt="%(pending)s" src="%(images)s/waiting_or.gif" border="0" /> %(waiting)s<br />
                               <img alt="%(approved)s" src="%(images)s/smchk_gr.gif" border="0" /> %(already_approved)s<br />
                               <img alt="%(rejected)s" src="%(images)s/cross_red.gif" border="0" /> %(rejected_text)s<br />
                               <img alt="%(cancelled)s" src="%(images)s/smchk_rd.gif" border="0" /> %(cancelled_text)s<br /><br />
                               <small class="blocknote">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small> %(somepending)s<br />
                             </td>
                         </tr>
                 </table>
               </blockquote>
               </td>
              </tr>
             </table>""" % {
               'key' : _("Key"),
               'pending' : _("Pending"),
               'images' : CFG_SITE_URL + '/img',
               'waiting' : _("Waiting for approval"),
               'approved' : _("Approved"),
               'already_approved' : _("Already approved"),
               'rejected' : _("Rejected"),
               'rejected_text' : _("Rejected"),
               'cancelled' : _("Cancelled"),
               'cancelled_text' : _("Cancelled"),
               'somepending' : _("Some documents are pending."),
             }
         return out
 
     def tmpl_publiline_selectdocument(self, ln, doctype, title, categ, docs):
         """
         Displays the documents that the user can select in the specified category
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The doctype
 
           - 'title' *string* - The doctype name
 
           - 'categ' *string* - the category
 
           - 'docs' *array* - All the categories that the user can select:
 
               - 'RN' *string* - The id of the document
 
               - 'status' *string* - The status of the document
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         out = """
                <table class="searchbox" width="100%%" summary="">
                   <tr>
                     <th class="portalboxheader">%(title)s - %(categ)s: %(list)s</th>
                   </tr>
                   <tr>
                     <td class="portalboxbody">
                     %(choose_report)s
                     <blockquote>
                       <form action="publiline.py" method="get">
                         <input type="hidden" name="doctype" value="%(doctype)s" />
                         <input type="hidden" name="categ" value="%(categ)s" />
                         <input type="hidden" name="RN" value="" />
                         <input type="hidden" name="ln" value="%(ln)s">
                         </form>
                   <table class="searchbox">
                     <tr>
                       <th class="portalboxheader">%(report_no)s</th>
                       <th class="portalboxheader">%(pending)s</th>
                       <th class="portalboxheader">%(approved)s</th>
                       <th class="portalboxheader">%(rejected)s</th>
                     </tr>
               """ % {
                 'doctype' : doctype,
                 'title' : title,
                 'categ' : categ,
                 'list' : _("List of refereed documents"),
                 'choose_report' : _("Click on a report number for more information."),
                 'report_no' : _("Report Number"),
                 'pending' : _("Pending"),
                 'approved' : _("Approved"),
                 'rejected' : _("Rejected"),
                 'ln': ln,
               }
 
         for doc in docs:
             status = doc ['status']
 
             if status == "waiting":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">
                               <img alt="check" src="%(images)s/waiting_or.gif" />
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
             elif status == "rejected":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                             <td align="center"><img alt="check" src="%(images)s/cross_red.gif" /></td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
             elif status == "approved":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center"><img alt="check" src="%(images)s/smchk_gr.gif" /></td>
                             <td align="center">&nbsp;</td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
         out += """  </table>
                     </blockquote>
                    </td>
                   </tr>
                  </table>"""
         return out
 
     def tmpl_publiline_selectcplxdocument(self, ln, doctype, title, categ, categname, docs, apptype):
         """
         Displays the documents that the user can select in the specified category
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The doctype
 
           - 'title' *string* - The doctype name
 
           - 'categ' *string* - the category
 
           - 'docs' *array* - All the categories that the user can select:
 
               - 'RN' *string* - The id of the document
 
               - 'status' *string* - The status of the document
 
           - 'apptype' *string* - the approval type
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         listtype = ""
         if apptype == "RRP":
             listtype = _("List of refereed documents")
         elif apptype == "RPB":
             listtype = _("List of publication documents")
         elif apptype == "RDA":
             listtype = _("List of direct approval documents")
 
         out = """
                <table class="searchbox" width="100%%" summary="">
                   <tr>
                     <th class="portalboxheader">%(title)s - %(categname)s: %(list)s</th>
                   </tr>
                   <tr>
                     <td class="portalboxbody">
                     %(choose_report)s
                     <blockquote>
                       <form action="publiline.py" method="get">
                         <input type="hidden" name="flow" value="cplx" />
                         <input type="hidden" name="doctype" value="%(doctype)s" />
                         <input type="hidden" name="categ" value="%(categ)s" />
                         <input type="hidden" name="RN" value="" />
                         <input type="hidden" name="apptype" value="%(apptype)s" />
                         <input type="hidden" name="ln" value="%(ln)s" />
                         </form>
                   <table class="searchbox">
                     <tr>
                       <th class="portalboxheader">%(report_no)s</th>
                       <th class="portalboxheader">%(pending)s</th>
                       <th class="portalboxheader">%(approved)s</th>
                       <th class="portalboxheader">%(rejected)s</th>
                       <th class="portalboxheader">%(cancelled)s</th>
                     </tr>
               """ % {
                 'doctype' : doctype,
                 'title' : title,
                 'categname' : categname,
                 'categ' : categ,
                 'list' : listtype,
                 'choose_report' : _("Click on a report number for more information."),
                 'apptype' : apptype,
                 'report_no' : _("Report Number"),
                 'pending' : _("Pending"),
                 'approved' : _("Approved"),
                 'rejected' : _("Rejected"),
                 'cancelled' : _("Cancelled"),
                 'ln': ln,
               }
 
         for doc in docs:
             status = doc ['status']
 
             if status == "waiting":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center"><img alt="check" src="%(images)s/waiting_or.gif" /></td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
             elif status == "rejected":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                             <td align="center"><img alt="check" src="%(images)s/cross_red.gif" /></td>
                             <td align="center">&nbsp;</td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
             elif status == "approved":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center"><img alt="check" src="%(images)s/smchk_gr.gif" /></td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
             elif status == "cancelled":
                 out += """<tr>
                             <td align="center">
                               <a href="" onclick="document.forms[0].RN.value='%(rn)s';document.forms[0].submit();return false;">%(rn)s</a>
                             </td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                             <td align="center">&nbsp;</td>
                             <td align="center"><img alt="check" src="%(images)s/smchk_rd.gif" /></td>
                           </tr>
                        """ % {
                          'rn' : doc['RN'],
                          'images' : CFG_SITE_URL + '/img',
                        }
         out += """  </table>
                     </blockquote>
                    </td>
                   </tr>
                  </table>"""
         return out
 
     def tmpl_publiline_displaydoc(self, ln, doctype, docname, categ, rn, status, dFirstReq, dLastReq, dAction, access, confirm_send, auth_code, auth_message, authors, title, sysno, newrn):
         """
         Displays the categories from a doctype that the user can select
 
         Parameters:
 
           - 'ln' *string* - The language to display the interface in
 
           - 'doctype' *string* - The doctype
 
           - 'docname' *string* - The doctype name
 
           - 'categ' *string* - the category
 
           - 'rn' *string* - The document RN (id number)
 
           - 'status' *string* - The status of the document
 
           - 'dFirstReq' *string* - The date of the first approval request
 
           - 'dLastReq' *string* - The date of the last approval request
 
           - 'dAction' *string* - The date of the last action (approval or rejection)
 
           - 'confirm_send' *bool* - must display a confirmation message about sending approval email
 
           - 'auth_code' *bool* - authorised to referee this document
 
           - 'auth_message' *string* - ???
 
           - 'authors' *string* - the authors of the submission
 
           - 'title' *string* - the title of the submission
 
           - 'sysno' *string* - the unique database id for the record
 
           - 'newrn' *string* - the record number assigned to the submission
         """
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         if status == "waiting":
             image = """<img src="%s/waiting_or.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "approved":
             image = """<img src="%s/smchk_gr.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "rejected":
             image = """<img src="%s/iconcross.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         else:
             image = ""
         out = """
                 <table class="searchbox" summary="">
                  <tr>
                   <th class="portalboxheader">%(image)s %(rn)s</th>
                  </tr>
                  <tr>
                    <td class="portalboxbody">""" % {
                    'image' : image,
                    'rn' : rn,
                  }
         if confirm_send:
             out += """<i><strong class="headline">%(requestsent)s</strong></i><br /><br />""" % {
                      'requestsent' : _("Your request has been sent to the referee."),
                    }
 
         out += """<form action="publiline.py">
                     <input type="hidden" name="RN" value="%(rn)s" />
                     <input type="hidden" name="categ" value="%(categ)s" />
                     <input type="hidden" name="doctype" value="%(doctype)s" />
                     <input type="hidden" name="ln" value="%(ln)s" />
                   <small>""" % {
                  'rn' : rn,
                  'categ' : categ,
                  'doctype' : doctype,
                  'ln' : ln,
                }
         if title != "unknown":
             out += """<strong class="headline">%(title_text)s</strong>%(title)s<br /><br />""" % {
                      'title_text' : _("Title:"),
                      'title' : title,
                    }
 
         if authors != "":
             out += """<strong class="headline">%(author_text)s</strong>%(authors)s<br /><br />""" % {
                      'author_text' : _("Author:"),
                      'authors' : authors,
                    }
         if sysno != "":
             out += """<strong class="headline">%(more)s</strong>
                         <a href="%(siteurl)s/record/%(sysno)s?ln=%(ln)s">%(click)s</a>
                         <br /><br />
                    """ % {
                      'more' : _("More information:"),
                      'click' : _("Click here"),
                      'siteurl' : CFG_SITE_URL,
                      'sysno' : sysno,
                      'ln' : ln,
                    }
 
         if status == "waiting":
             out += _("This document is still %(x_fmt_open)swaiting for approval%(x_fmt_close)s.") % {'x_fmt_open': '<strong class="headline">',
                                                                                                      'x_fmt_close': '</strong>'}
             out += "<br /><br />"
             out += _("It was first sent for approval on:") + ' <strong class="headline">' + str(dFirstReq) + '</strong><br />'
             if dLastReq == "0000-00-00 00:00:00":
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dFirstReq) + '</strong><br />'
             else:
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dLastReq) + '</strong><br />'
             out += "<br />" + _("You can send an approval request email again by clicking the following button:") + " <br />" +\
                    """<input class="adminbutton" type="submit" name="send" value="%(send)s" onclick="return confirm('%(warning)s')" />""" % {
                      'send' : _("Send Again"),
                      'warning' : _("WARNING! Upon confirmation, an email will be sent to the referee.")
                    }
             if auth_code == 0:
                 out += "<br />" + _("As a referee for this document, you may click this button to approve or reject it") + ":<br />" +\
                        """<input class="adminbutton" type="submit" name="approval" value="%(approve)s" onclick="window.location='approve.py?%(access)s&amp;ln=%(ln)s';return false;" />""" % {
                          'approve' : _("Approve/Reject"),
                          'access' : access,
                          'ln' : ln
                        }
         if status == "approved":
             out += _("This document has been %(x_fmt_open)sapproved%(x_fmt_close)s.") % {'x_fmt_open': '<strong class="headline">',
                                                                                          'x_fmt_close': '</strong>'}
             out += '<br />' + _("Its approved reference is:") + ' <strong class="headline">' + str(newrn) + '</strong><br /><br />'
             out += _("It was first sent for approval on:") + ' <strong class="headline">' + str(dFirstReq) + '</strong><br />'
             if dLastReq == "0000-00-00 00:00:00":
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dFirstReq) + '</strong><br />'
             else:
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dLastReq) + '</strong><br />' +\
                        _("It was approved on:") + ' <strong class="headline">' + str(dAction) + '</strong><br />'
         if status == "rejected":
             out += _("This document has been %(x_fmt_open)srejected%(x_fmt_close)s.") % {'x_fmt_open': '<strong class="headline">',
                                                                                          'x_fmt_close': '</strong>'}
             out += "<br /><br />"
             out += _("It was first sent for approval on:") + ' <strong class="headline">' + str(dFirstReq) +'</strong><br />'
             if dLastReq == "0000-00-00 00:00:00":
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dFirstReq) + '</strong><br />'
             else:
                 out += _("Last approval email was sent on:") + ' <strong class="headline">' + str(dLastReq) +'</strong><br />'
             out += _("It was rejected on:") + ' <strong class="headline">' + str(dAction) + '</strong><br />'
 
         out += """    </small></form>
                       <br />
                     </td>
                    </tr>
                   </table>"""
         return out
 
     def tmpl_publiline_displaycplxdoc(self, ln, doctype, docname, categ, rn, apptype, status, dates, isPubCom, isEdBoard, isReferee, isProjectLeader, isAuthor, authors, title, sysno, newrn):
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         if status == "waiting":
             image = """<img src="%s/waiting_or.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "approved":
             image = """<img src="%s/smchk_gr.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "rejected":
             image = """<img src="%s/iconcross.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "cancelled":
             image = """<img src="%s/smchk_rd.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         else:
             image = ""
         out = """
                 <table class="searchbox" summary="">
                  <tr>
                   <th class="portalboxheader">%(image)s %(rn)s</th>
                  </tr>
                  <tr>
                    <td class="portalboxbody">""" % {
                    'image' : image,
                    'rn' : rn,
                  }
 
         out += """<form action="publiline.py">
                     <input type="hidden" name="flow" value="cplx" />
                     <input type="hidden" name="doctype" value="%(doctype)s" />
                     <input type="hidden" name="categ" value="%(categ)s" />
                     <input type="hidden" name="RN" value="%(rn)s" />
                     <input type="hidden" name="apptype" value="%(apptype)s" />
                     <input type="hidden" name="action" value="" />
                     <input type="hidden" name="ln" value="%(ln)s" />
                   <small>""" % {
                  'rn' : rn,
                  'categ' : categ,
                  'doctype' : doctype,
                  'apptype' : apptype,
                  'ln': ln,
                }
 
         out += "<table><tr height='30px'><td width='120px'>"
 
         if title != "unknown":
             out += """<strong class="headline">%(title_text)s</strong></td><td>%(title)s</td></tr>""" % {
                      'title_text' : _("Title:"),
                      'title' : title,
                    }
 
         out += "<tr height='30px'><td width='120px'>"
         if authors != "":
             out += """<strong class="headline">%(author_text)s</strong></td><td>%(authors)s</td></tr>""" % {
                      'author_text' : _("Author:"),
                      'authors' : authors,
                    }
         out += "<tr height='30px'><td width='120px'>"
         if sysno != "":
             out += """<strong class="headline">%(more)s</strong>
                         </td><td><a href="%(siteurl)s/record/%(sysno)s?ln=%(ln)s">%(click)s</a>
                         </td></tr>
                    """ % {
                      'more' : _("More information:"),
                      'click' : _("Click here"),
                      'siteurl' : CFG_SITE_URL,
                      'sysno' : sysno,
                      'ln' : ln,
                    }
 
         out += "</table>"
         out += "<br /><br />"
 
         if apptype == "RRP":
             out += "<table><tr><td width='400px'>"
             out += _("It has first been asked for refereing process on the ") + "</td><td>" + ' <strong class="headline">' + str(dates['dFirstReq']) + '</strong><br /></td></tr>'
 
             out += "<tr><td width='400px'>"
             out += _("Last request e-mail was sent to the publication committee chair on the ") + "</td><td>" + ' <strong class="headline">' + str(dates['dLastReq']) + '</strong><br /></td></tr>'
 
             if dates['dRefereeSel'] != None:
                 out += "<tr><td width='400px'>"
                 out += _("A referee has been selected by the publication committee on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dRefereeSel']) + '</strong><br /></td></tr>'
             else:
                 out += "<tr><td width='400px'>"
                 out += _("No referee has been selected yet.") + "</td><td>"
                 if (status != "cancelled") and (isPubCom == 0):
                     out += displaycplxdoc_displayauthaction (action="RefereeSel", linkText=_("Select a referee"))
                 out += '<br /></td></tr>'
 
             if dates['dRefereeRecom'] != None:
                 out += "<tr><td width='400px'>"
                 out += _("The referee has sent his final recommendations to the publication committee on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dRefereeRecom']) + '</strong><br /></td></tr>'
             else:
                 out += "<tr><td width='400px'>"
                 out += _("No recommendation from the referee yet.") + "</td><td>"
                 if (status != "cancelled") and (dates['dRefereeSel'] != None) and (isReferee == 0):
                     out += displaycplxdoc_displayauthaction (action="RefereeRecom", linkText=_("Send a recommendation"))
                 out += '<br /></td></tr>'
 
             if dates['dPubComRecom'] != None:
                 out += "<tr><td width='400px'>"
                 out += _("The publication committee has sent his final recommendations to the project leader on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dPubComRecom']) + '</strong><br /></td></tr>'
             else:
                 out += "<tr><td width='400px'>"
                 out += _("No recommendation from the publication committee yet.") + "</td><td>"
                 if (status != "cancelled") and (dates['dRefereeRecom'] != None) and (isPubCom == 0):
                     out += displaycplxdoc_displayauthaction (action="PubComRecom", linkText=_("Send a recommendation"))
                 out += '<br /></td></tr>'
 
             if status == "cancelled":
                 out += "<tr><td width='400px'>"
                 out += _("It has been cancelled by the author on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br /></td></tr>'
             elif dates['dProjectLeaderAction'] != None:
                 if status == "approved":
                     out += "<tr><td width='400px'>"
                     out += _("It has been approved by the project leader on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br /></td></tr>'
                 elif status == "rejected":
                     out += "<tr><td width='400px'>"
                     out += _("It has been rejected by the project leader on the ") + "</td><td>" +  ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br /></td></tr>'
             else:
                 out += "<tr><td width='400px'>"
                 out += _("No final decision taken yet.") + "</td><td>"
                 if (dates['dPubComRecom'] != None) and (isProjectLeader == 0):
                     out += displaycplxdoc_displayauthaction (action="ProjectLeaderDecision", linkText=_("Take a decision"))
                 if isAuthor == 0:
                     out += displaycplxdoc_displayauthaction (action="AuthorCancel", linkText=_("Cancel"))
                 out += '<br /></table>'
 
         elif apptype == "RPB":
             out += _("It has first been asked for refereing process on the ") + ' <strong class="headline">' + str(dates['dFirstReq']) + '</strong><br />'
 
             out += _("Last request e-mail was sent to the publication committee chair on the ") + ' <strong class="headline">' + str(dates['dLastReq']) + '</strong><br />'
 
             if dates['dEdBoardSel'] != None:
                 out += _("An editorial board has been selected by the publication committee on the ") + ' <strong class="headline">' + str(dates['dEdBoardSel']) + '</strong>'
                 if (status != "cancelled") and (isEdBoard == 0):
                     out += displaycplxdoc_displayauthaction (action="AddAuthorList", linkText=_("Add an author list"))
                 out += '<br />'
             else:
                 out += _("No editorial board has been selected yet.")
                 if (status != "cancelled") and (isPubCom == 0):
                     out += displaycplxdoc_displayauthaction (action="EdBoardSel", linkText=_("Select an editorial board"))
                 out += '<br />'
 
             if dates['dRefereeSel'] != None:
                 out += _("A referee has been selected by the editorial board on the ") + ' <strong class="headline">' + str(dates['dRefereeSel']) + '</strong><br />'
             else:
                 out += _("No referee has been selected yet.")
                 if (status != "cancelled") and (dates['dEdBoardSel'] != None) and (isEdBoard == 0):
                     out += displaycplxdoc_displayauthaction (action="RefereeSel", linkText=_("Select a referee"))
                 out += '<br />'
 
             if dates['dRefereeRecom'] != None:
                 out += _("The referee has sent his final recommendations to the editorial board on the ") + ' <strong class="headline">' + str(dates['dRefereeRecom']) + '</strong><br />'
             else:
                 out += _("No recommendation from the referee yet.")
                 if (status != "cancelled") and (dates['dRefereeSel'] != None) and (isReferee == 0):
                     out += displaycplxdoc_displayauthaction (action="RefereeRecom", linkText=_("Send a recommendation"))
                 out += '<br />'
 
             if dates['dEdBoardRecom'] != None:
                 out += _("The editorial board has sent his final recommendations to the publication committee on the ") + ' <strong class="headline">' + str(dates['dRefereeRecom']) + '</strong><br />'
             else:
                 out += _("No recommendation from the editorial board yet.")
                 if (status != "cancelled") and (dates['dRefereeRecom'] != None) and (isEdBoard == 0):
                     out += displaycplxdoc_displayauthaction (action="EdBoardRecom", linkText=_("Send a recommendation"))
                 out += '<br />'
 
             if dates['dPubComRecom'] != None:
                 out += _("The publication committee has sent his final recommendations to the project leader on the ") + ' <strong class="headline">' + str(dates['dPubComRecom']) + '</strong><br />'
             else:
                 out += _("No recommendation from the publication committee yet.")
                 if (status != "cancelled") and (dates['dEdBoardRecom'] != None) and (isPubCom == 0):
                     out += displaycplxdoc_displayauthaction (action="PubComRecom", linkText=_("Send a recommendation"))
                 out += '<br />'
 
             if status == "cancelled":
                 out += _("It has been cancelled by the author on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
             elif dates['dProjectLeaderAction'] != None:
                 if status == "approved":
                     out += _("It has been approved by the project leader on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
                 elif status == "rejected":
                     out += _("It has been rejected by the project leader on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
             else:
                 out += _("No final decision taken yet.")
                 if (dates['dPubComRecom'] != None) and (isProjectLeader == 0):
                     out += displaycplxdoc_displayauthaction (action="ProjectLeaderDecision", linkText=_("Take a decision"))
                 if isAuthor == 0:
                     out += displaycplxdoc_displayauthaction (action="AuthorCancel", linkText=_("Cancel"))
                 out += '<br />'
 
         elif apptype == "RDA":
             out += _("It has first been asked for refereing process on the ") + ' <strong class="headline">' + str(dates['dFirstReq']) + '</strong><br />'
 
             out += _("Last request e-mail was sent to the project leader on the ") + ' <strong class="headline">' + str(dates['dLastReq']) + '</strong><br />'
 
             if status == "cancelled":
                 out += _("It has been cancelled by the author on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
             elif dates['dProjectLeaderAction'] != None:
                 if status == "approved":
                     out += _("It has been approved by the project leader on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
                 elif status == "rejected":
                     out += _("It has been rejected by the project leader on the ") + ' <strong class="headline">' + str(dates['dProjectLeaderAction']) + '</strong><br />'
             else:
                 out += _("No final decision taken yet.")
                 if isProjectLeader == 0:
                     out += displaycplxdoc_displayauthaction (action="ProjectLeaderDecision", linkText=_("Take a decision"))
                 if isAuthor == 0:
                     out += displaycplxdoc_displayauthaction (action="AuthorCancel", linkText=_("Cancel"))
                 out += '<br />'
 
         out += """    </small></form>
                       <br />
                     </td>
                    </tr>
                   </table>"""
         return out
 
     def tmpl_publiline_displaycplxdocitem(self,
                                           doctype, categ, rn, apptype, action,
                                           comments,
                                           (user_can_view_comments, user_can_add_comment, user_can_delete_comment),
                                           selected_category,
                                           selected_topic, selected_group_id, comment_subject, comment_body, ln):
         _ = gettext_set_language(ln)
 
         if comments and user_can_view_comments:
 
             comments_text = ''
             comments_overview = '<ul>'
             for comment in comments:
                 (cmt_uid, cmt_nickname, cmt_title, cmt_body, cmt_date, cmt_priority, cmtid) = comment
 
                 comments_overview += '<li><a href="#%s">%s - %s</a> (%s)</li>' % (cmtid, cmt_nickname, cmt_title, convert_datetext_to_dategui (cmt_date))
 
                 comments_text += """
 <table class="bskbasket">
   <thead class="bskbasketheader">
     <tr><td class="bsktitle"><a name="%s"></a>%s - %s (%s)</td><td><a href=%s/publiline.py?flow=cplx&doctype=%s&apptype=%s&categ=%s&RN=%s&reply=true&commentId=%s&ln=%s#add_comment>Reply</a></td><td><a href="#top">Top</a></td></tr>
   </thead>
   <tbody>
     <tr><td colspan="2">%s</td></tr>
   </tbody>
 </table>""" % (cmtid, cmt_nickname, cmt_title, convert_datetext_to_dategui (cmt_date), CFG_SITE_URL, doctype, apptype, categ, rn, cmt_uid, ln, email_quoted_txt2html(cmt_body))
 
             comments_overview += '</ul>'
         else:
             comments_text = ''
             comments_overview = 'None.'
 
         body = ''
         if user_can_view_comments:
             body += """<h4>%(comments_label)s</h4>"""
         if user_can_view_comments:
             body += """%(comments)s"""
         if user_can_add_comment:
             validation = """
     <input type="hidden" name="validate" value="go" />
     <input type="submit" class="formbutton" value="%(button_label)s" />""" % {'button_label': _("Add Comment")}
             body += self.tmpl_publiline_displaywritecomment (doctype, categ, rn, apptype, action, _("Add Comment"), comment_subject, validation, comment_body, ln)
 
         body %= {
                 'comments_label': _("Comments"),
                 'action': action,
                 'button_label': _("Write a comment"),
                 'comments': comments_text}
         content = '<br />'
 
         out = """
 <table class="bskbasket">
   <thead class="bskbasketheader">
     <tr>
       <td class="bsktitle">
         <a name="top"></a>
         <h4>%(comments_overview_label)s</h4>
         %(comments_overview)s
       </td>
       <td class="bskcmtcol"></td>
     </tr>
   </thead>
   <tbody>
     <tr>
       <td colspan="2" style="padding: 5px;">
 %(body)s
       </td>
     </tr>
   </tbody>
 </table>""" % {
                'comments_overview_label' : _('Comments overview'),
                'comments_overview' : comments_overview,
                'body' : body,}
 
         return out
 
     def tmpl_publiline_displaywritecomment(self, doctype, categ, rn, apptype, action, write_label, title, validation, reply_message, ln):
         _ = gettext_set_language(ln)
         return """
 <div style="width:100%%%%">
   <hr />
   <h2>%(write_label)s</h2>
   <form action="publiline.py">
     <input type="hidden" name="flow" value="cplx" />
     <input type="hidden" name="doctype" value="%(doctype)s" />
     <input type="hidden" name="categ" value="%(categ)s" />
     <input type="hidden" name="RN" value="%(rn)s" />
     <input type="hidden" name="apptype" value="%(apptype)s" />
     <input type="hidden" name="action" value="%(action)s" />
     <input type="hidden" name="ln" value="%(ln)s" />
     <p class="bsklabel">%(title_label)s:</p>
     <a name="add_comment"></a>
     <input type="text" name="msg_subject" size="80" value="%(title)s"/>
     <p class="bsklabel">%(comment_label)s:</p>
     <textarea name="msg_body" rows="20" cols="80">%(reply_message)s</textarea><br />
     %(validation)s
   </form>
 </div>""" % {'write_label': write_label,
              'title_label': _("Title"),
              'title': title,
              'comment_label': _("Comment"),
              'rn' : rn,
              'categ' : categ,
              'doctype' : doctype,
              'apptype' : apptype,
              'action' : action,
              'validation' : validation,
              'reply_message' : reply_message,
              'ln' : ln,
             }
 
     def tmpl_publiline_displaydocplxaction(self, ln, doctype, categ, rn, apptype, action, status, authors, title, sysno, subtitle1, email_user_pattern, stopon1, users, extrausers, stopon2, subtitle2, usersremove, stopon3, validate_btn):
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         if status == "waiting":
             image = """<img src="%s/waiting_or.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "approved":
             image = """<img src="%s/smchk_gr.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "rejected":
             image = """<img src="%s/iconcross.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         else:
             image = ""
         out = """
                 <table class="searchbox" summary="">
                  <tr>
                   <th class="portalboxheader">%(image)s %(rn)s</th>
                  </tr>
                  <tr>
                    <td class="portalboxbody">
                      <small>""" % {
                    'image' : image,
                    'rn' : rn,
                  }
 
         if title != "unknown":
             out += """<strong class="headline">%(title_text)s</strong>%(title)s<br /><br />""" % {
                      'title_text' : _("Title:"),
                      'title' : title,
                    }
 
         if authors != "":
             out += """<strong class="headline">%(author_text)s</strong>%(authors)s<br /><br />""" % {
                      'author_text' : _("Author:"),
                      'authors' : authors,
                    }
         if sysno != "":
             out += """<strong class="headline">%(more)s</strong>
                         <a href="%(siteurl)s/record/%(sysno)s?ln=%(ln)s">%(click)s</a>
                         <br /><br />
                    """ % {
                      'more' : _("More information:"),
                      'click' : _("Click here"),
                      'siteurl' : CFG_SITE_URL,
                      'sysno' : sysno,
                      'ln' : ln,
                    }
 
         out += """      </small>
                       <br />
                     </td>
                    </tr>
                  </table>"""
 
         if ((apptype == "RRP") or (apptype == "RPB")) and ((action == "EdBoardSel") or (action == "RefereeSel")):
             out += """
                     <table class="searchbox" summary="">
                      <tr>
                       <th class="portalboxheader">%(subtitle)s</th>
                      </tr>
                      <tr>
                        <td class="portalboxbody">""" % {
                        'subtitle' : subtitle1,
                      }
 
             out += """<form action="publiline.py">
                         <input type="hidden" name="flow" value="cplx" />
                         <input type="hidden" name="doctype" value="%(doctype)s" />
                         <input type="hidden" name="categ" value="%(categ)s" />
                         <input type="hidden" name="RN" value="%(rn)s" />
                         <input type="hidden" name="apptype" value="%(apptype)s" />
                         <input type="hidden" name="action" value="%(action)s" />
                         <input type="hidden" name="ln" value="%(ln)s" />""" % {
                      'rn' : rn,
                      'categ' : categ,
                      'doctype' : doctype,
                      'apptype' : apptype,
                      'action' : action,
                      'ln': ln,
                    }
 
             out += ' <span class="adminlabel">1. %s </span>\n' % _("search for user")
             out += ' <input class="admin_wvar" type="text" name="email_user_pattern" value="%s" />\n' % (email_user_pattern, )
             out += ' <input class="adminbutton" type="submit" value="%s"/>\n' % (_("search for users"), )
 
             if (stopon1 == "") and (email_user_pattern != ""):
                 out += ' <br /><span class="adminlabel">2. %s </span>\n' % _("select user")
                 out += ' <select name="id_user" class="admin_w200">\n'
                 out += '  <option value="0">*** %s ***</option>\n' % _("select user")
                 for elem in users:
                     elem_id = elem[0]
                     email = elem[1]
                     out += '  <option value="%s">%s</option>\n' % (elem_id, email)
 
                 for elem in extrausers:
                     elem_id = elem[0]
                     email = elem[1]
                     out += '  <option value="%s">%s %s</option>\n' % (elem_id, email, _("connected"))
 
                 out += ' </select>\n'
                 out += ' <input class="adminbutton" type="submit" value="%s" />\n' % (_("add this user"), )
 
                 out += stopon2
 
             elif stopon1 != "":
                 out += stopon1
 
             out += """
                             </form>
                           <br />
                         </td>
                        </tr>
                      </table>"""
 
             if action == "EdBoardSel":
                 out += """
                         <table class="searchbox" summary="">
                          <tr>
                           <th class="portalboxheader">%(subtitle)s</th>
                          </tr>
                          <tr>
                            <td class="portalboxbody">""" % {
                            'subtitle' : subtitle2,
                          }
 
                 out += """<form action="publiline.py">
                             <input type="hidden" name="flow" value="cplx" />
                             <input type="hidden" name="doctype" value="%(doctype)s" />
                             <input type="hidden" name="categ" value="%(categ)s" />
                             <input type="hidden" name="RN" value="%(rn)s" />
                             <input type="hidden" name="apptype" value="%(apptype)s" />
                             <input type="hidden" name="action" value="%(action)s" />
                             <input type="hidden" name="ln" value="%(ln)s" />""" % {
                          'rn' : rn,
                          'categ' : categ,
                          'doctype' : doctype,
                          'apptype' : apptype,
                          'action' : action,
                          'ln': ln,
                        }
 
                 out += ' <span class="adminlabel">1. %s </span>\n' % _("select user")
                 out += ' <select name="id_user_remove" class="admin_w200">\n'
                 out += '  <option value="0">*** %s ***</option>\n' % _("select user")
                 for elem in usersremove:
                     elem_id = elem[0]
                     email = elem[1]
                     out += '  <option value="%s">%s</option>\n' % (elem_id, email)
 
                 out += ' </select>\n'
                 out += ' <input class="adminbutton" type="submit" value="%s" />\n' % (_("remove this user"), )
 
                 out += stopon3
 
                 out += """
                                 </form>
                               <br />
                             </td>
                            </tr>
                          </table>"""
 
             if validate_btn != "":
                 out += """<form action="publiline.py">
                             <input type="hidden" name="flow" value="cplx" />
                             <input type="hidden" name="doctype" value="%(doctype)s" />
                             <input type="hidden" name="categ" value="%(categ)s" />
                             <input type="hidden" name="RN" value="%(rn)s" />
                             <input type="hidden" name="apptype" value="%(apptype)s" />
                             <input type="hidden" name="action" value="%(action)s" />
                             <input type="hidden" name="validate" value="go" />
                             <input type="hidden" name="ln" value="%(ln)s" />
                             <input class="adminbutton" type="submit" value="%(validate_btn)s" />
                           </form>""" % {
                          'rn' : rn,
                          'categ' : categ,
                          'doctype' : doctype,
                          'apptype' : apptype,
                          'action' : action,
                          'validate_btn' : validate_btn,
                          'ln': ln,
                        }
 
         return out
 
     def tmpl_publiline_displaycplxrecom(self, ln, doctype, categ, rn, apptype, action, status, authors, title, sysno,  msg_to, msg_to_group, msg_subject):
 
         # load the right message language
         _ = gettext_set_language(ln)
 
         if status == "waiting":
             image = """<img src="%s/waiting_or.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "approved":
             image = """<img src="%s/smchk_gr.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         elif status == "rejected":
             image = """<img src="%s/iconcross.gif" alt="" align="right" />""" % (CFG_SITE_URL + '/img')
         else:
             image = ""
         out = """
                 <table class="searchbox" summary="">
                  <tr>
                   <th class="portalboxheader">%(image)s %(rn)s</th>
                  </tr>
                  <tr>
                    <td class="portalboxbody">
                      <small>""" % {
                    'image' : image,
                    'rn' : rn,
                  }
 
         if title != "unknown":
             out += """<strong class="headline">%(title_text)s</strong>%(title)s<br /><br />""" % {
                      'title_text' : _("Title:"),
                      'title' : title,
                    }
 
         if authors != "":
             out += """<strong class="headline">%(author_text)s</strong>%(authors)s<br /><br />""" % {
                      'author_text' : _("Author:"),
                      'authors' : authors,
                    }
         if sysno != "":
             out += """<strong class="headline">%(more)s</strong>
                         <a href="%(siteurl)s/record/%(sysno)s?ln=%(ln)s">%(click)s</a>
                         <br /><br />
                    """ % {
                      'more' : _("More information:"),
                      'click' : _("Click here"),
                      'siteurl' : CFG_SITE_URL,
                      'sysno' : sysno,
                      'ln' : ln,
                    }
 
         out += """      </small>
                       <br />
                     </td>
                    </tr>
                  </table>"""
 
         # escape forbidden character
         msg_to = escape_html(msg_to)
         msg_to_group = escape_html(msg_to_group)
         msg_subject = escape_html(msg_subject)
 
         write_box = """
 <form action="publiline.py" method="post">
   <input type="hidden" name="flow" value="cplx" />
   <input type="hidden" name="doctype" value="%(doctype)s" />
   <input type="hidden" name="categ" value="%(categ)s" />
   <input type="hidden" name="RN" value="%(rn)s" />
   <input type="hidden" name="apptype" value="%(apptype)s" />
   <input type="hidden" name="action" value="%(action)s" />
   <input type="hidden" name="ln" value="%(ln)s" />
   <div style="float: left; vertical-align:text-top; margin-right: 10px;">
     <table class="mailbox">
       <thead class="mailboxheader">
         <tr>
           <td class="inboxheader" colspan="2">
             <table class="messageheader">
               <tr>
                 <td class="mailboxlabel">%(to_label)s</td>"""
 
         if msg_to != "":
             addr_box = """
                 <td class="mailboxlabel">%(users_label)s</td>
                 <td style="width:100%%%%;" class="mailboxlabel">%(to_users)s</td>""" % {'users_label': _("User"),
                                                                                         'to_users' : msg_to,
                                                                                        }
             if msg_to_group != "":
                 addr_box += """
               </tr>
               <tr>
                 <td class="mailboxlabel">&nbsp;</td>
                 <td class="mailboxlabel">%(groups_label)s</td>
                 <td style="width:100%%%%;" class="mailboxlabel">%(to_groups)s</td>""" % {'groups_label': _("Group"),
                                                                                          'to_groups': msg_to_group,
                                                                                         }
         elif msg_to_group != "":
             addr_box = """
                 <td class="mailboxlabel">%(groups_label)s</td>
                 <td style="width:100%%%%;" class="mailboxlabel">%(to_groups)s</td>""" % {'groups_label': _("Group"),
                                                                                          'to_groups': msg_to_group,
                                                                                         }
         else:
             addr_box = """
                 <td class="mailboxlabel">&nbsp;</td>
                 <td class="mailboxlabel">&nbsp;</td>"""
 
         write_box += addr_box
         write_box += """
               </tr>
               <tr>
                 <td class="mailboxlabel">&nbsp;</td>
                 <td>&nbsp;</td>
                 <td>&nbsp;</td>
               </tr>
               <tr>
                 <td class="mailboxlabel">%(subject_label)s</td>
                 <td colspan="2">
                   <input class="mailboxinput" type="text" name="msg_subject" value="%(subject)s" />
                 </td>
               </tr>
             </table>
           </td>
         </tr>
       </thead>
       <tfoot>
         <tr>
           <td style="height:0px" colspan="2"></td>
         </tr>
       </tfoot>
       <tbody class="mailboxbody">
         <tr>
           <td class="mailboxlabel">%(message_label)s</td>
           <td>
             <textarea name="msg_body" rows="10" cols="50"></textarea>
           </td>
         </tr>
         <tr class="mailboxfooter">
          <td>
              <select name="validate">
                  <option> %(select)s</option>
                  <option value="approve">%(approve)s</option>
                  <option value="reject">%(reject)s</option>
              </select>
           </td>
 
           <td colspan="2" class="mailboxfoot">
             <input type="submit" name="send_button" value="%(send_label)s" class="formbutton"/>
           </td>
         </tr>
       </tbody>
     </table>
   </div>
 </form>
 """
         write_box = write_box % {'rn' : rn,
                                  'categ' : categ,
                                  'doctype' : doctype,
                                  'apptype' : apptype,
                                  'action' : action,
                                  'subject' : msg_subject,
                                  'to_label': _("To:"),
                                  'subject_label': _("Subject:"),
                                  'message_label': _("Message:"),
                                  'send_label': _("SEND"),
                                  'select' : _("Select:"),
                                  'approve' : _("approve"),
                                  'reject' : _("reject"),
                                  'ln': ln,
                                 }
 
         out += write_box
 
         return out
 
 def displaycplxdoc_displayauthaction(action, linkText):
     return """ <strong class="headline">(<a href="" onclick="document.forms[0].action.value='%(action)s';document.forms[0].submit();return false;">%(linkText)s</a>)</strong>""" % {
         "action" : action,
         "linkText" : linkText
         }
diff --git a/modules/websubmit/lib/websubmit_webinterface.py b/modules/websubmit/lib/websubmit_webinterface.py
index 43265945b..67e0f4fbf 100644
--- a/modules/websubmit/lib/websubmit_webinterface.py
+++ b/modules/websubmit/lib/websubmit_webinterface.py
@@ -1,549 +1,549 @@
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 __lastupdated__ = """$Date$"""
 
 __revision__ = "$Id$"
 
 import string
 import os
 import time
 import types
 import re
 try:
     from mod_python import apache
 except ImportError:
     pass
 
 import sys
-from urllib import quote, unquote
+from urllib import quote, unquote, urlencode
 
 from invenio.config import \
      CFG_ACCESS_CONTROL_LEVEL_SITE, \
      CFG_SITE_LANG, \
      CFG_SITE_NAME, \
      CFG_SITE_NAME_INTL, \
      CFG_SITE_URL, \
      CFG_WEBSUBMIT_STORAGEDIR, \
      CFG_VERSION, \
      CFG_SITE_URL
 from invenio.dbquery import run_sql, Error
 from invenio.access_control_config import VIEWRESTRCOLL
 from invenio.access_control_mailcookie import mail_cookie_create_authorize_action
 from invenio.access_control_engine import acc_authorize_action
 from invenio.access_control_admin import acc_is_role
 from invenio.webpage import page, create_error_box, pageheaderonly, \
     pagefooteronly
 from invenio.webuser import getUid, get_email, page_not_authorized, collect_user_info, isUserSuperAdmin
 from invenio.websubmit_config import *
 from invenio.webinterface_handler import wash_urlargd, WebInterfaceDirectory
 from invenio.urlutils import make_canonical_urlargd, redirect_to_url
 from invenio.messages import gettext_set_language
 from invenio.search_engine import \
      guess_primary_collection_of_a_record, \
      get_colID, \
      create_navtrail_links, check_user_can_view_record
 from invenio.bibdocfile import BibRecDocs, normalize_format, file_strip_ext, \
     stream_restricted_icon, BibDoc, InvenioWebSubmitFileError
 from invenio.errorlib import register_exception
 
 import invenio.template
 websubmit_templates = invenio.template.load('websubmit')
 from invenio.websearchadminlib import get_detailed_page_tabs
 import invenio.template
 webstyle_templates = invenio.template.load('webstyle')
 websearch_templates = invenio.template.load('websearch')
 
 class WebInterfaceFilesPages(WebInterfaceDirectory):
 
     def __init__(self,recid):
         self.recid = recid
 
     def _lookup(self, component, path):
         # after /record/<recid>/files/ every part is used as the file
         # name
         filename = unquote(component)
 
         def getfile(req, form):
             args = wash_urlargd(form, websubmit_templates.files_default_urlargd)
             ln = args['ln']
 
             _ = gettext_set_language(ln)
 
             uid = getUid(req)
             user_info = collect_user_info(req)
 
             verbose = args['verbose']
             if verbose >= 1 and not isUserSuperAdmin(user_info):
                 # Only SuperUser can see all the details!
                 verbose = 0
 
             if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE > 1:
                 return page_not_authorized(req, "../getfile.py/index",
                                            navmenuid='submit')
 
             (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
             if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
                 cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
                 target = '/youraccount/login' + \
                     make_canonical_urlargd({'action': cookie, 'ln' : ln, 'referer' : \
                     CFG_SITE_URL + user_info['uri']}, {})
                 return redirect_to_url(req, target)
             elif auth_code:
                 return page_not_authorized(req, "../", \
                     text = auth_msg)
 
 
             readonly = CFG_ACCESS_CONTROL_LEVEL_SITE == 1
 
             # From now on: either the user provided a specific file
             # name (and a possible version), or we return a list of
             # all the available files. In no case are the docids
             # visible.
             try:
                 bibarchive = BibRecDocs(self.recid)
             except InvenioWebSubmitFileError, e:
                 register_exception(req=req, alert_admin=True)
                 msg = "<p>%s</p><p>%s</p>" % (
                     _("The system has encountered an error in retrieving the list of files for this document."),
                     _("The error has been logged and will be taken in consideration as soon as possible."))
                 return print_warning(msg)
 
             docname = ''
             format = ''
             version = ''
 
             if filename:
                 # We know the complete file name, guess which docid it
                 # refers to
                 ## TODO: Change the extension system according to ext.py from setlink
                 ##       and have a uniform extension mechanism...
                 docname = file_strip_ext(filename)
                 format = filename[len(docname):]
                 if format and format[0] != '.':
                     format = '.' + format
             else:
                 docname = args['docname']
 
             if not format:
                 format = args['format']
 
             if not version:
                 version = args['version']
 
             # version could be either empty, or all or an integer
             try:
                 int(version)
             except ValueError:
                 if version != 'all':
                     version = ''
 
             if version != 'all':
                 # search this filename in the complete list of files
                 for doc in bibarchive.list_bibdocs():
                     if docname == doc.get_docname():
                         try:
                             docfile = doc.get_file(format, version)
                         except InvenioWebSubmitFileError, msg:
                             register_exception(req=req, alert_admin=True)
                             return warningMsg(_("An error has happened in trying to retrieve the requested file."), req, CFG_SITE_NAME, ln)
 
                         if docfile.get_status() == '':
                             # The file is not resticted, let's check for
                             # collection restriction then.
                             (auth_code, auth_message) = check_user_can_view_record(user_info, self.recid)
                             if auth_code:
                                 return warningMsg(_("The collection to which this file belong is restricted: ") + auth_message, req, CFG_SITE_NAME, ln)
                         else:
                             # The file is probably restricted on its own.
                             # Let's check for proper authorization then
                             (auth_code, auth_message) = docfile.is_restricted(req)
                             if auth_code != 0:
                                 return warningMsg(_("This file is restricted: ") + auth_message, req, CFG_SITE_NAME, ln)
 
                         if not readonly:
                             ip = str(req.get_remote_host(apache.REMOTE_NOLOOKUP))
                             res = doc.register_download(ip, version, format, uid)
                         try:
                             return docfile.stream(req)
                         except InvenioWebSubmitFileError, msg:
                             register_exception(req=req, alert_admin=True)
                             return warningMsg(_("An error has happened in trying to stream the request file."), req, CFG_SITE_NAME, ln)
 
                     elif doc.get_icon() is not None and doc.get_icon().docname in filename:
                         icon = doc.get_icon()
                         try:
                             iconfile = icon.get_file('gif', args['version'])
                         except InvenioWebSubmitFileError, msg:
                             register_exception(req=req, alert_admin=True)
                             return warningMsg(_("An error has happened in trying to retrieve the corresponding icon."), req, CFG_SITE_NAME, ln)
 
                         if iconfile.get_status() == '':
                             # The file is not resticted, let's check for
                             # collection restriction then.
                             (auth_code, auth_message) = check_user_can_view_record(user_info, self.recid)
                             if auth_code:
                                 return stream_restricted_icon(req)
                         else:
                             # The file is probably restricted on its own.
                             # Let's check for proper authorization then
                             (auth_code, auth_message) = iconfile.is_restricted(req)
                             if auth_code != 0:
                                 return stream_restricted_icon(req)
 
                         if not readonly:
                             ip = str(req.get_remote_host(apache.REMOTE_NOLOOKUP))
                             res = doc.register_download(ip, version, format, uid)
                         try:
                             return iconfile.stream(req)
                         except InvenioWebSubmitFileError, msg:
                             register_exception(req=req, alert_admin=True)
                             return warningMsg(_("An error has happened in trying to stream the corresponding icon."), req, CFG_SITE_NAME, ln)
 
             if docname and format:
                 req.status = apache.HTTP_NOT_FOUND
                 warn = print_warning(_("Requested file does not seem to exist."))
             else:
                 warn = ''
             filelist = bibarchive.display("", args['version'], ln=ln, verbose=verbose)
 
             t = warn + websubmit_templates.tmpl_filelist(
                 ln=ln,
                 recid=self.recid,
                 docname=args['docname'],
                 version=args['version'],
                 filelist=filelist)
 
             cc = guess_primary_collection_of_a_record(self.recid)
             unordered_tabs = get_detailed_page_tabs(get_colID(cc), self.recid, ln)
             ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
             ordered_tabs_id.sort(lambda x,y: cmp(x[1],y[1]))
             link_ln = ''
             if ln != CFG_SITE_LANG:
                 link_ln = '?ln=%s' % ln
             tabs = [(unordered_tabs[tab_id]['label'], \
                      '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                      tab_id == 'files',
                      unordered_tabs[tab_id]['enabled']) \
                     for (tab_id, order) in ordered_tabs_id
                     if unordered_tabs[tab_id]['visible'] == True]
             top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                    tabs,
                                                                    args['ln'])
             bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                          tabs,
                                                                          args['ln'])
             title, description, keywords = websearch_templates.tmpl_record_page_header_content(req, self.recid, args['ln'])
             return pageheaderonly(title=title,
                         navtrail=create_navtrail_links(cc=cc, as=0, ln=ln) + \
                                         ''' &gt; <a class="navtrail" href="%s/record/%s">%s</a>
                                         &gt; %s''' % \
                         (CFG_SITE_URL, self.recid, title, _("Access to Fulltext")),
 
                         description="",
                         keywords="keywords",
                         uid=uid,
                         language=ln,
                         req=req,
                         navmenuid='search',
                         navtrail_append_title_p=0) + \
                         websearch_templates.tmpl_search_pagestart(ln) + \
                         top + t + bottom + \
                         websearch_templates.tmpl_search_pageend(ln) + \
                         pagefooteronly(lastupdated=__lastupdated__, language=ln, req=req)
         return getfile, []
 
     def __call__(self, req, form):
         """Called in case of URLs like /record/123/files without
            trailing slash.
         """
         args = wash_urlargd(form, websubmit_templates.files_default_urlargd)
         ln = args['ln']
         link_ln = ''
         if ln != CFG_SITE_LANG:
             link_ln = '?ln=%s' % ln
 
         return redirect_to_url(req, '%s/record/%s/files/%s' % (CFG_SITE_URL, self.recid, link_ln))
 
 def websubmit_legacy_getfile(req, form):
     """ Handle legacy /getfile.py URLs """
 
     args = wash_urlargd(form, {
         'recid': (int, 0),
         'docid': (int, 0),
         'version': (str, ''),
         'name': (str, ''),
         'format': (str, ''),
         'ln' : (str, CFG_SITE_LANG)
         })
 
     _ = gettext_set_language(args['ln'])
 
     def _getfile_py(req, recid=0, docid=0, version="", name="", format="", ln=CFG_SITE_LANG):
         if not recid:
             ## Let's obtain the recid from the docid
             if docid:
                 try:
                     bibdoc = BibDoc(docid=docid)
                     recid = bibdoc.get_recid()
                 except InvenioWebSubmitFileError, e:
                     return warningMsg(_("An error has happened in trying to retrieve the requested file."), req, CFG_SITE_NAME, ln)
             else:
                 return warningMsg(_('Not enough information to retrieve the document'), req, CFG_SITE_NAME, ln)
         else:
             if not name and docid:
                 ## Let's obtain the name from the docid
                 try:
                     bibdoc = BibDoc(docid)
                     name = bibdoc.get_docname()
                 except InvenioWebSubmitFileError, e:
                     return warningMsg(_("An error has happened in trying to retrieving the requested file."), req, CFG_SITE_NAME, ln)
 
         format = normalize_format(format)
 
         redirect_to_url(req, '%s/record/%s/files/%s%s?ln=%s%s' % (CFG_SITE_URL, recid, name, format, ln, version and 'version=%s' % version or ''), apache.HTTP_MOVED_PERMANENTLY)
 
     return _getfile_py(req, **args)
 
 
 # --------------------------------------------------
 
 from invenio.websubmit_engine import home, action, interface, endaction
 
 class WebInterfaceSubmitPages(WebInterfaceDirectory):
 
     _exports = ['summary', 'sub', 'direct', '']
 
 
     def direct(self, req, form):
-
+        """Directly redirected to an initialized submission."""
         args = wash_urlargd(form, {'sub': (str, ''),
-                                   'ln': (str, CFG_SITE_LANG)})
+                                   'access' : (str, '')})
+
         sub = args['sub']
+        access = args['access']
         ln = args['ln']
 
+        _ = gettext_set_language(ln)
+
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
-            return page_not_authorized(req, "../direct.py/index",
+            return page_not_authorized(req, "direct",
                                            navmenuid='submit')
 
         myQuery = req.args
-        if sub == "":
-            return warningMsg("Sorry parameter missing...", req)
-        res = run_sql("select docname,actname from sbmIMPLEMENT where subname=%s", (sub,))
-        if len(res)==0:
-            return warningMsg("Sorry. Cannot analyse parameter", req)
+        if not sub:
+            return warningMsg(_("Sorry, 'sub' parameter missing..."), req, ln=ln)
+        res = run_sql("SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s", (sub,))
+        if not res:
+            return warningMsg(_("Sorry. Cannot analyse parameter"), req, ln=ln)
         else:
             # get document type
             doctype = res[0][0]
             # get action name
             action = res[0][1]
         # retrieve other parameter values
-        params = re.sub("sub=[^&]*","",myQuery)
+        params = dict(form)
         # find existing access number
-        result = re.search("access=([^&]*)",params)
-        if result is not None:
-            access = result.group(1)
-            params = re.sub("access=[^&]*","",params)
-        else:
+        if not access:
             # create 'unique' access number
             pid = os.getpid()
             now = time.time()
             access = "%i_%s" % (now,pid)
         # retrieve 'dir' value
-        res = run_sql ("select dir from sbmACTION where sactname=%s",(action,))
+        res = run_sql ("SELECT dir FROM sbmACTION WHERE sactname=%s", (action,))
         dir = res[0][0]
-        try:
-            mainmenu = req.headers_in['Referer']
-        except:
-            mainmenu = ""
-        url = "/submit?doctype=%s&dir=%s&access=%s&act=%s&startPg=1%s&mainmenu=%s&ln=%s" % (
-            doctype,dir,access,action,params,quote(mainmenu), ln)
-        req.err_headers_out.add("Location", url)
-        raise apache.SERVER_RETURN, apache.HTTP_MOVED_PERMANENTLY
-        return ""
 
+        mainmenu = req.headers_in.get('referer')
+
+        params['access'] = access
+        params['act'] = action
+        params['doctype'] = doctype
+        params['startPg'] = '1'
+        params['mainmenu'] = mainmenu
+        params['ln'] = ln
+        params['indir'] = dir
+
+        url = "%s/submit?%s" % (CFG_SITE_URL, urlencode(params))
+        redirect_to_url(req, url)
 
     def sub(self, req, form):
+        args = wash_urlargd(form, {'password': (str, '')})
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../sub/",
                                        navmenuid='submit')
 
-        myQuery = req.args
-        if myQuery:
-            param = ''
-            if re.search("@",myQuery):
-                param = re.sub("@.*","",myQuery)
-                IN = re.sub(".*@","",myQuery)
-            else:
-                IN = myQuery
-            url = "%s/submit/direct?sub=%s&%s" % (CFG_SITE_URL,IN,param)
-            req.err_headers_out.add("Location", url)
-            raise apache.SERVER_RETURN, apache.HTTP_MOVED_PERMANENTLY
-            return ""
+        #DEMOBOO_RN=DEMO-BOOK-2008-001&ln=en&password=1223993532.26572%40APPDEMOBOO
+        params = dict(form)
+        del params['password']
+        password = args['password']
+        if "@" in password:
+            params['access'], params['sub'] = password.split('@', 1)
         else:
-            return "<html>Illegal page access</html>"
+            params['sub'] = password
+        url = "%s/submit/direct?%s" % (CFG_SITE_URL, urlencode(params))
+        redirect_to_url(req, url)
 
 
     def summary(self, req, form):
         args = wash_urlargd(form, {
             'doctype': (str, ''),
             'act': (str, ''),
             'access': (str, ''),
             'indir': (str, '')})
 
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../summary",
                                        navmenuid='submit')
 
         t=""
         curdir  = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, args['indir'], args['doctype'], args['access'])
         try:
             assert(curdir == os.path.abspath(curdir))
         except AssertionError:
-            register_exception(req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype="%s", access="%s"' % (args['indir'], args['doctype'], args['access']))
+            register_exception(req=req, alert_admin=True, prefix='Possible cracking tentative: indir="%s", doctype="%s", access="%s"' % (args['indir'], args['doctype'], args['access']))
             return warningMsg("Invalid parameters")
 
         subname = "%s%s" % (args['act'], args['doctype'])
 
         res = run_sql("select sdesc,fidesc,pagenb,level from sbmFIELD where subname=%s "
                       "order by pagenb,fieldnb", (subname,))
         nbFields = 0
 
         values = []
         for arr in res:
             if arr[0] != "":
                 val = {
                        'mandatory' : (arr[3] == 'M'),
                        'value' : '',
                        'page' : arr[2],
                        'name' : arr[0],
                       }
                 if os.path.exists(os.path.join(curdir, curdir,arr[1])):
                     fd = open(os.path.join(curdir, arr[1]),"r")
                     value = fd.read()
                     fd.close()
                     value = value.replace("\n"," ")
                     value = value.replace("Select:","")
                 else:
                     value = ""
                 val['value'] = value
                 values.append(val)
 
         return websubmit_templates.tmpl_submit_summary(
                  ln = args['ln'],
                  values = values,
                )
 
     def index(self, req, form):
 
         args = wash_urlargd(form, {
             'c': (str, CFG_SITE_NAME),
             'doctype': (str, ''),
             'act': (str, ''),
             'startPg': (str, "1"),
             'indir': (str, ''),
             'access': (str, ''),
             'mainmenu': (str, ''),
             'fromdir': (str, ''),
             'file': (str, ''),
             'nextPg': (str, ''),
             'nbPg': (str, ''),
             'curpage': (str, '1'),
             'step': (str, '0'),
             'mode': (str, 'U'),
             })
 
         req.form = form
         ## Strip whitespace from beginning and end of doctype and action:
         args["doctype"] = args["doctype"].strip()
         args["act"] = args["act"].strip()
 
         def _index(req, c, ln, doctype, act, startPg, indir, access,
                    mainmenu, fromdir, file, nextPg, nbPg, curpage, step,
                    mode):
 
             uid = getUid(req)
             if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
                 return page_not_authorized(req, "../submit",
                                            navmenuid='submit')
 
             if doctype=="":
                 return home(req,c,ln)
             elif act=="":
                 return action(req,c,ln,doctype)
             elif int(step)==0:
                 return interface(req,c,ln, doctype, act, startPg, indir,
                                  access, mainmenu, fromdir, file, nextPg,
                                  nbPg, curpage)
             else:
                 return endaction(req,c,ln, doctype, act, startPg, indir,
                                  access,mainmenu, fromdir, file, nextPg,
                                  nbPg, curpage, step, mode)
 
         return _index(req, **args)
 
     # Answer to both /submit/ and /submit
     __call__ = index
 
 def errorMsg(title, req, c=None, ln=CFG_SITE_LANG):
     # load the right message language
     _ = gettext_set_language(ln)
 
     if c is None:
         c = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)
 
     return page(title = _("Error"),
                 body = create_error_box(req, title=title, verbose=0, ln=ln),
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='submit')
 
 def warningMsg(title, req, c=None, ln=CFG_SITE_LANG):
     # load the right message language
     _ = gettext_set_language(ln)
 
     if c is None:
         c = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)
 
     return page(title = _("Warning"),
                 body = title,
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='submit')
 
 def print_warning(msg, type='', prologue='<br />', epilogue='<br />'):
     """Prints warning message and flushes output."""
     if msg:
         return websubmit_templates.tmpl_print_warning(
                    msg = msg,
                    type = type,
                    prologue = prologue,
                    epilogue = epilogue,
                  )
     else:
         return ''
diff --git a/modules/websubmit/web/approve.py b/modules/websubmit/web/approve.py
index 1fdcf85cc..f11e80f03 100644
--- a/modules/websubmit/web/approve.py
+++ b/modules/websubmit/web/approve.py
@@ -1,84 +1,101 @@
 ## $Id$
 ##
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 __revision__ = "$Id$"
 
 ## import interesting modules:
 import string
 import os
 import sys
 import time
 import types
 import re
+import urllib
 from mod_python import apache
 
 from invenio.config import \
      CFG_ACCESS_CONTROL_LEVEL_SITE, \
      CFG_SITE_LANG, \
      CFG_SITE_NAME, \
      CFG_SITE_URL, \
-     CFG_VERSION
+     CFG_VERSION, \
+     CFG_SITE_NAME_INTL
 from invenio.dbquery import run_sql
 from invenio.access_control_engine import acc_authorize_action
 from invenio.access_control_admin import acc_is_role
 from invenio.websubmit_config import *
 from invenio.webpage import page, create_error_box
 from invenio.webuser import getUid, get_email, page_not_authorized
-from invenio.messages import wash_language
+from invenio.messages import wash_language, gettext_set_language
+from invenio.errorlib import register_exception
+from invenio.urlutils import redirect_to_url
 
-def index(req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG):
+def index(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
+    """Approval web Interface.
+    GET params:
 
+    """
     uid = getUid(req)
     if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
         return page_not_authorized(req, "../approve.py/index",
                                    navmenuid='yourapprovals')
 
     ln = wash_language(ln)
+    _ = gettext_set_language(ln)
     form = req.form
     if form.keys():
         # form keys can be a list of 'access pw' and ln, so remove 'ln':
         for key in form.keys():
             if key != 'ln':
                 access = key
         if access == "":
-            return errorMsg("approve.py: cannot determine document reference",req)
+            return warningMsg(_("approve.py: cannot determine document reference"), req)
         res = run_sql("select doctype,rn from sbmAPPROVAL where access=%s",(access,))
         if len(res) == 0:
-            return errorMsg("approve.py: cannot find document in database",req)
+            return warningMsg(_("approve.py: cannot find document in database"), req)
         else:
             doctype = res[0][0]
             rn = res[0][1]
         res = run_sql("select value from sbmPARAMETERS where name='edsrn' and doctype=%s",(doctype,))
         edsrn = res[0][0]
-        url = "%s/submit/sub?%s=%s&password=%s@APP%s&ln=%s" % (CFG_SITE_URL,edsrn,rn,access,doctype, ln)
-        req.err_headers_out.add("Location", url)
-        raise apache.SERVER_RETURN, apache.HTTP_MOVED_PERMANENTLY
-        return ""
+        url = "%s/submit/sub?%s" % (CFG_SITE_URL, urllib.urlencode({
+            edsrn: rn,
+            'password': '%s@APP%s' % (access, doctype),
+            'ln' : ln
+        }))
+        redirect_to_url(req, url)
     else:
-        return errorMsg("Sorry parameter missing...", req, c, ln)
+        return warningMsg(_("Sorry parameter missing..."), req, c, ln)
 
-def errorMsg(title,req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG):
-    return page(title="error",
-                    body = create_error_box(req, title=title,verbose=0, ln=ln),
-                    description="%s - Internal Error" % c,
-                    keywords="%s, Internal Error" % c,
-                    language=ln,
-                    req=req,
-                    navmenuid='yourapprovals')
+def warningMsg(title, req, c=None, ln=CFG_SITE_LANG):
+    # load the right message language
+    _ = gettext_set_language(ln)
+
+    if c is None:
+        c = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)
+
+    return page(title = _("Warning"),
+                body = title,
+                description="%s - Internal Error" % c,
+                keywords="%s, Internal Error" % c,
+                uid = getUid(req),
+                language=ln,
+                req=req,
+                navmenuid='submit')
 
diff --git a/modules/websubmit/web/publiline.py b/modules/websubmit/web/publiline.py
index 24ef4bd70..9d5516a03 100644
--- a/modules/websubmit/web/publiline.py
+++ b/modules/websubmit/web/publiline.py
@@ -1,1836 +1,1842 @@
 ## $Id$
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 """
 publiline_complex.py --  implementes ...
 
   actors in this process are:
 
         1. author -- subilmts ...
         2. edi
         3; ref
 
 Il ne faut pas oublier de definir les roles...
 """
 
 __revision__ = "$Id$"
 
 ## import interesting modules:
 import string
 import os
 import sys
 import time
 import types
 import re
 import shutil
 
 from invenio.config import \
      CFG_ACCESS_CONTROL_LEVEL_SITE, \
      CFG_SITE_ADMIN_EMAIL, \
      CFG_SITE_LANG, \
      CFG_SITE_NAME, \
      CFG_SITE_URL, \
      CFG_PYLIBDIR, \
      CFG_WEBSUBMIT_STORAGEDIR, \
      CFG_SITE_SUPPORT_EMAIL, \
      CFG_SITE_SECURE_URL, \
      CFG_VERSION
 from invenio.dbquery import run_sql, Error, OperationalError
 from invenio.access_control_engine import acc_authorize_action
 from invenio.access_control_admin import *
 from invenio.webpage import page, create_error_box
 from invenio.webuser import getUid, get_email, list_registered_users, page_not_authorized
 from invenio.messages import gettext_set_language, wash_language
 from invenio.websubmit_config import *
 from invenio.search_engine import search_pattern, get_fieldvalues
 from invenio.websubmit_functions.Retrieve_Data import Get_Field
 from invenio.mailutils import send_email
 from invenio.urlutils import wash_url_argument
 from invenio.webgroup_dblayer import get_group_infos, insert_new_group, insert_new_member, delete_member
 from invenio.webaccessadmin_lib import cleanstring_email
 from invenio.access_control_config import MAXSELECTUSERS
 from invenio.access_control_admin import acc_get_user_email
 from invenio.webmessage import perform_request_send, perform_request_write_with_search
 import invenio.webbasket_dblayer as basketdb
 from invenio.webbasket_config import CFG_WEBBASKET_SHARE_LEVELS, CFG_WEBBASKET_CATEGORIES, CFG_WEBBASKET_SHARE_LEVELS_ORDERED
 from invenio.webbasket import perform_request_display_item, perform_request_save_comment
 from invenio.websubmit_functions.Retrieve_Data import Get_Field
 from invenio.errorlib import register_exception
 from invenio.bibrecord import create_records, record_get_field_value, record_get_field_values
 
 execfile("%s/invenio/websubmit_functions/Retrieve_Data.py" % CFG_PYLIBDIR)
 
 import invenio.template
 websubmit_templates = invenio.template.load('websubmit')
 
 CFG_WEBSUBMIT_PENDING_DIR = "%s/pending" % CFG_WEBSUBMIT_STORAGEDIR
 CFG_WEBSUBMIT_DUMMY_MARC_XML_REC = "dummy_marcxml_rec"
 CFG_WEBSUBMIT_MARC_XML_REC = "recmysql"
 
 
 def index(req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG,doctype="",categ="",RN="",send="",flow="",apptype="", action="", email_user_pattern="", id_user="", id_user_remove="", validate="", id_user_val="", msg_subject="", msg_body="", reply="", commentId=""):
     global uid
 
     ln = wash_language(ln)
     categ = wash_url_argument(categ, 'str')
     RN = wash_url_argument(RN, 'str')
     send = wash_url_argument(send, 'str')
     flow = wash_url_argument(flow, 'str')
     apptype = wash_url_argument(apptype, 'str')
     action = wash_url_argument(action, 'str')
     email_user_pattern = wash_url_argument(email_user_pattern, 'str')
     id_user = wash_url_argument(id_user, 'int')
     id_user_remove = wash_url_argument(id_user_remove, 'int')
     validate = wash_url_argument(validate, 'str')
     id_user_val = wash_url_argument(id_user_val, 'int')
     msg_subject = wash_url_argument(msg_subject, 'str')
     msg_body = wash_url_argument(msg_body, 'str')
     reply = wash_url_argument(reply, 'str')
     commentId = wash_url_argument(commentId, 'str')
 
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     t=""
     # get user ID:
     try:
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../publiline.py/index",
                                        navmenuid='yourapprovals')
         uid_email = get_email(uid)
     except Error, e:
         return errorMsg(str(e),req, ln = ln)
 
     if flow == "cplx":
         if doctype == "":
             t = selectCplxDoctype(ln)
         elif (categ == "") or (apptype == ""):
             t = selectCplxCateg(doctype, ln)
         elif RN == "":
             t = selectCplxDocument(doctype, categ, apptype, ln)
         elif action == "":
             t = displayCplxDocument(req, doctype, categ, RN, apptype, reply, commentId, ln)
         else:
             t = doCplxAction(req, doctype, categ, RN, apptype, action, email_user_pattern, id_user, id_user_remove, validate, id_user_val, msg_subject, msg_body, reply, commentId, ln)
         return page(title=_("Document Approval Workflow"),
                     navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display">%(account)s</a>""" % {
                                  'sitesecureurl' : CFG_SITE_SECURE_URL,
                                  'account' : _("Your Account"),
                               },
                     body=t,
                     description="",
                     keywords="",
                     uid=uid,
                     language=ln,
                     req=req,
                     navmenuid='yourapprovals')
     else:
         if doctype == "":
             t = selectDoctype(ln)
         elif categ == "":
             t = selectCateg(doctype, ln)
         elif RN == "":
             t = selectDocument(doctype, categ, ln)
         else:
             t = displayDocument(req, doctype, categ, RN, send, ln)
         return page(title=_("Approval and Refereeing Workflow"),
                     navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display">%(account)s</a>""" % {
                                  'sitesecureurl' : CFG_SITE_SECURE_URL,
                                  'account' : _("Your Account"),
                               },
                     body=t,
                     description="",
                     keywords="",
                     uid=uid,
                     language=ln,
                     req=req,
                     navmenuid='yourapprovals')
 
 def selectDoctype(ln = CFG_SITE_LANG):
     res = run_sql("select DISTINCT doctype from sbmAPPROVAL")
     docs = []
     for row in res:
         res2 = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (row[0],))
         docs.append({
                      'doctype' : row[0],
                      'docname' : res2[0][0],
                     })
     t = websubmit_templates.tmpl_publiline_selectdoctype(
           ln = ln,
           docs = docs,
         )
     return t
 
 def selectCplxDoctype(ln = CFG_SITE_LANG):
     res = run_sql("select DISTINCT doctype from sbmCPLXAPPROVAL")
     docs = []
     for row in res:
         res2 = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (row[0],))
         docs.append({
                      'doctype' : row[0],
                      'docname' : res2[0][0],
                     })
     t = websubmit_templates.tmpl_publiline_selectcplxdoctype(
           ln = ln,
           docs = docs,
         )
     return t
 
 def selectCateg(doctype, ln = CFG_SITE_LANG):
     t=""
     res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s",(doctype,))
     title = res[0][0]
     sth = run_sql("select * from sbmCATEGORIES where doctype=%s order by lname",(doctype,))
     if len(sth) == 0:
         categ = "unknown"
         return selectDocument(doctype,categ, ln = ln)
 
     categories = []
     for arr in sth:
         waiting = 0
         rejected = 0
         approved = 0
         sth2 = run_sql("select COUNT(*) from sbmAPPROVAL where doctype=%s and categ=%s and status='waiting'", (doctype,arr[1],))
         waiting = sth2[0][0]
         sth2 = run_sql("select COUNT(*) from sbmAPPROVAL where doctype=%s and categ=%s and status='approved'",(doctype,arr[1],))
         approved = sth2[0][0]
         sth2 = run_sql("select COUNT(*) from sbmAPPROVAL where doctype=%s and categ=%s and status='rejected'",(doctype,arr[1],))
         rejected = sth2[0][0]
         categories.append({
                             'waiting' : waiting,
                             'approved' : approved,
                             'rejected' : rejected,
                             'id' : arr[1],
                           })
 
     t = websubmit_templates.tmpl_publiline_selectcateg(
           ln = ln,
           categories = categories,
           doctype = doctype,
           title = title,
         )
     return t
 
 def selectCplxCateg(doctype, ln = CFG_SITE_LANG):
     t=""
     res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s",(doctype,))
     title = res[0][0]
     sth = run_sql("SELECT * FROM sbmCATEGORIES WHERE doctype=%s ORDER BY lname",(doctype,))
     if len(sth) == 0:
         categ = "unknown"
         return selectCplxDocument(doctype,categ, "", ln = ln)
 
     types = {}
     for apptype in ('RRP', 'RPB', 'RDA'):
         for arr in sth:
             info = {'id' : arr[1],
                     'desc' : arr[2],}
             for status in ('waiting', 'rejected', 'approved', 'cancelled'):
                 info[status] = __db_count_doc (doctype, arr[1], status, apptype)
             types.setdefault (apptype, []).append(info)
 
     t = websubmit_templates.tmpl_publiline_selectcplxcateg(
           ln = ln,
           types = types,
           doctype = doctype,
           title = title,
         )
     return t
 
 def selectDocument(doctype,categ, ln = CFG_SITE_LANG):
     t=""
     res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (doctype,))
     title = res[0][0]
     if categ == "":
         categ == "unknown"
 
     docs = []
     sth = run_sql("select rn,status from sbmAPPROVAL where doctype=%s and categ=%s order by status DESC,rn DESC",(doctype,categ))
     for arr in sth:
         docs.append({
                      'RN' : arr[0],
                      'status' : arr[1],
                     })
 
     t = websubmit_templates.tmpl_publiline_selectdocument(
           ln = ln,
           doctype = doctype,
           title = title,
           categ = categ,
           docs = docs,
         )
     return t
 
 def selectCplxDocument(doctype,categ,apptype, ln = CFG_SITE_LANG):
     t=""
     res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (doctype,))
     title = res[0][0]
 
     sth = run_sql("select lname from sbmCATEGORIES where doctype=%s and sname=%s order by lname",(doctype,categ,))
     if len(sth) != 0:
         categname = sth[0][0]
     else:
         categname = "Unknown"
 
     docs = []
     sth = run_sql("select rn,status from sbmCPLXAPPROVAL where doctype=%s and categ=%s and type=%s order by status DESC,rn DESC",(doctype,categ,apptype))
     for arr in sth:
         docs.append({
                      'RN' : arr[0],
                      'status' : arr[1],
                     })
 
     t = websubmit_templates.tmpl_publiline_selectcplxdocument(
           ln = ln,
           doctype = doctype,
           title = title,
           categ = categ,
           categname = categname,
           docs = docs,
           apptype = apptype,
         )
     return t
 
 def displayDocument(req, doctype,categ,RN,send, ln = CFG_SITE_LANG):
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     t=""
     res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (doctype,))
     docname = res[0][0]
     if categ == "":
         categ = "unknown"
     sth = run_sql("select rn,status,dFirstReq,dLastReq,dAction,access from sbmAPPROVAL where rn=%s",(RN,))
     if len(sth) > 0:
         arr = sth[0]
         rn = arr[0]
         status = arr[1]
         dFirstReq = arr[2]
         dLastReq = arr[3]
         dAction = arr[4]
         access = arr[5]
     else:
         return _("Approval has never been requested for this document.") + "<br />&nbsp;"
 
     ## Get the details of the pending item:
     item_details = get_pending_item_details(doctype, RN)
     ## get_pending_item_details has returned either None or a dictionary
     ## with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
     if item_details is not None:
         authors = ", ".join(item_details['authors'])
         newrn = item_details['report-number']
         title = item_details['title']
         sysno = item_details['recid']
     else:
         ## FIXME!
         ## For backward compatibility reasons, it we failed to find the item's
         ## details, we will try the old way, which includes searching for files
         ## like TI, TIF in the submission's working directory.
         ## This is not nice and should be removed.
         try:
             (authors,title,sysno,newrn) = getInfo(doctype,categ,RN)
         except TypeError:
             return _("Unable to display document.")
 
     confirm_send = 0
     if send == _("Send Again"):
         if authors == "unknown" or title == "unknown":
             SendWarning(doctype,categ,RN,title,authors,access, ln = ln)
         else:
             # @todo - send in different languages
             SendEnglish(doctype,categ,RN,title,authors,access,sysno)
             run_sql("update sbmAPPROVAL set dLastReq=NOW() where rn=%s",(RN,))
             confirm_send = 1
 
     if status == "waiting":
         if categ == "unknown":
             ## FIXME: This was necessary for document types without categories,
             ## such as DEMOBOO:
             categ = "*"
         (auth_code, auth_message) = acc_authorize_action(req, "referee",verbose=0,doctype=doctype, categ=categ)
     else:
         (auth_code, auth_message) = (None, None)
 
     t = websubmit_templates.tmpl_publiline_displaydoc(
           ln = ln,
           docname = docname,
           doctype = doctype,
           categ = categ,
           rn = rn,
           status = status,
           dFirstReq = dFirstReq,
           dLastReq = dLastReq,
           dAction = dAction,
           access = access,
           confirm_send = confirm_send,
           auth_code = auth_code,
           auth_message = auth_message,
           authors = authors,
           title = title,
           sysno = sysno,
           newrn = newrn,
         )
     return t
 
 def displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln = CFG_SITE_LANG):
     # load the right message language
     _ = gettext_set_language(ln)
 
     t=""
     uid = getUid(req)
     res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (doctype,))
     docname = res[0][0]
     if categ == "":
         categ = "unknown"
 
     key = (RN, apptype)
     infos = __db_get_infos (key)
     if len(infos) > 0:
         (status, id_group, id_bskBASKET, id_EdBoardGroup,
          dFirstReq,dLastReq,dEdBoardSel, dRefereeSel, dRefereeRecom, dEdBoardRecom, dPubComRecom, dProjectLeaderAction) = infos[0]
 
         dates = {'dFirstReq' : dFirstReq,
                  'dLastReq' : dLastReq,
                  'dEdBoardSel' : dEdBoardSel,
                  'dRefereeSel' : dRefereeSel,
                  'dRefereeRecom' : dRefereeRecom,
                  'dEdBoardRecom' : dEdBoardRecom,
                  'dPubComRecom' : dPubComRecom,
                  'dProjectLeaderAction' : dProjectLeaderAction,
                 }
     else:
         return _("Approval has never been requested for this document.") + "<br />&nbsp;"
 
 ## Removing call to deprecated "getInAlice" function and replacing it with
 ## a call to the newer "get_brief_doc_details_from_repository" function:
 ##     try:
 ##         (authors,title,sysno,newrn) = getInAlice(doctype,categ,RN)
 ##     except TypeError:
 ##         return _("Unable to display document.")
 
     item_details = get_brief_doc_details_from_repository(RN)
 
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
     if item_details is not None:
         ## Details of the item were found in the CDS Invenio repository
         authors = ", ".join(item_details['authors'])
         newrn = item_details['report-number']
         title = item_details['title']
         sysno = item_details['recid']
     else:
         ## Can't find any document details.
         return _("Unable to display document.")
 
     if status == "waiting":
         isPubCom = __is_PubCom (req, doctype)
         isEdBoard = __is_EdBoard (uid, id_EdBoardGroup)
         isReferee = __is_Referee (uid, id_bskBASKET)
         isProjectLeader = __is_ProjectLeader (req, doctype, categ)
         isAuthor = __is_Author (uid, sysno)
     else:
         isPubCom = None
         isEdBoard = None
         isReferee = None
         isProjectLeader = None
         isAuthor = None
 
     t += websubmit_templates.tmpl_publiline_displaycplxdoc(
           ln = ln,
           docname = docname,
           doctype = doctype,
           categ = categ,
           rn = RN,
           apptype = apptype,
           status = status,
           dates = dates,
           isPubCom = isPubCom,
           isEdBoard = isEdBoard,
           isReferee = isReferee,
           isProjectLeader = isProjectLeader,
           isAuthor = isAuthor,
           authors = authors,
           title = title,
           sysno = sysno,
           newrn = newrn,
         )
 
     if id_bskBASKET > 0:
         rights = basketdb.get_max_user_rights_on_basket(uid, id_bskBASKET)
         if not(__check_basket_sufficient_rights(rights, CFG_WEBBASKET_SHARE_LEVELS['READITM'])):
             return t
 
         comments = basketdb.get_comments(id_bskBASKET, sysno)
 
         if dProjectLeaderAction != None:
             user_can_add_comment = 0
         else:
             user_can_add_comment = __check_basket_sufficient_rights(rights, CFG_WEBBASKET_SHARE_LEVELS['ADDCMT'])
 
             comment_subject = ""
             comment_body = ""
             if reply == "true":
                 #Get the message subject and body from the comment
                 for comment in comments:
                     if str(commentId) == str(comment[0]):
                         comment_subject = comment[2]
                         comment_body = comment[3]
                 comment_subject = comment_subject.lstrip("Re: ")
                 comment_subject = "Re: " + comment_subject
                 comment_body = "> " + comment_body.replace("\n", "\n> ")
 
 
             t += websubmit_templates.tmpl_publiline_displaycplxdocitem(
                                                   doctype, categ, RN, apptype, "AddComment",
                                                   comments,
                                                   (__check_basket_sufficient_rights(rights, CFG_WEBBASKET_SHARE_LEVELS['READCMT']),
                                                    user_can_add_comment,
                                                    __check_basket_sufficient_rights(rights, CFG_WEBBASKET_SHARE_LEVELS['DELCMT'])),
                                                   selected_category=CFG_WEBBASKET_CATEGORIES['GROUP'], selected_topic=0, selected_group_id=id_group,
                                                   comment_subject=comment_subject, comment_body=comment_body, ln=ln)
 
     return t
 
 def __check_basket_sufficient_rights(rights_user_has, rights_needed):
     """Private function, check if the rights are sufficient."""
     try:
         out = CFG_WEBBASKET_SHARE_LEVELS_ORDERED.index(rights_user_has) >= \
               CFG_WEBBASKET_SHARE_LEVELS_ORDERED.index(rights_needed)
     except ValueError:
         out = 0
     return out
 
 def __is_PubCom (req,doctype):
     (isPubCom, auth_message) = acc_authorize_action(req, "pubcomchair",verbose=0,doctype=doctype)
     return isPubCom
 
 def __is_EdBoard (uid, id_EdBoardGroup):
     isEdBoard = None
     if id_EdBoardGroup > 0:
         edBoard = run_sql("""SELECT u.id
                              FROM user u LEFT JOIN user_usergroup ug ON u.id = ug.id_user
                              WHERE ug.id_usergroup = '%s' and user_status != 'A' AND user_status != 'P'""" % (id_EdBoardGroup, ))
         for uid_scan in edBoard:
             if uid == uid_scan[0]:
                 isEdBoard = 0
                 break
     return isEdBoard
 
 def __is_Referee (uid, id_bskBASKET):
     isReferee = None
     if id_bskBASKET > 0:
         if basketdb.check_user_owns_baskets (uid, id_bskBASKET) == 1:
             isReferee = 0
     return isReferee
 
 def __is_ProjectLeader (req, doctype, categ):
     (isProjectLeader, auth_message) = acc_authorize_action(req, "projectleader",verbose=0,doctype=doctype,categ=categ)
     return isProjectLeader
 
 def __is_Author (uid, sysno):
     email = Get_Field("8560_f",sysno)
     email = re.sub("[\n\r ]+","",email)
     uid_email = re.sub("[\n\r ]+","", acc_get_user_email(uid))
     isAuthor = None
     if (re.search(uid_email,email,re.IGNORECASE) != None) and (uid_email != ""):
         isAuthor = 0
     return isAuthor
 
 def __db_count_doc (doctype, categ, status, apptype):
     return run_sql("SELECT COUNT(*) FROM sbmCPLXAPPROVAL WHERE doctype=%s AND categ=%s AND status=%s AND type=%s",(doctype,categ,status,apptype,))[0][0]
 
 def __db_get_infos (key):
     return run_sql("SELECT status,id_group,id_bskBASKET,id_EdBoardGroup,dFirstReq,dLastReq,dEdBoardSel,dRefereeSel,dRefereeRecom,dEdBoardRecom,dPubComRecom,dProjectLeaderAction FROM sbmCPLXAPPROVAL WHERE rn=%s and type=%s", key)
 
 def __db_set_EdBoardSel_time (key):
     run_sql("UPDATE sbmCPLXAPPROVAL SET dEdBoardSel=NOW() WHERE  rn=%s and type=%s", key)
 
 def __db_check_EdBoardGroup ((RN,apptype), id_EdBoardGroup, uid, group_descr):
     res = get_group_infos (id_EdBoardGroup)
     if len(res) == 0:
         id_EdBoardGroup = insert_new_group (uid, RN, group_descr % RN, "VM")
         run_sql("UPDATE sbmCPLXAPPROVAL SET id_EdBoardGroup=%s WHERE  rn=%s and type=%s", (id_EdBoardGroup,RN,apptype,))
 
     return id_EdBoardGroup
 
 def __db_set_basket ((RN,apptype), id_bsk):
     run_sql("UPDATE sbmCPLXAPPROVAL SET id_bskBASKET=%s, dRefereeSel=NOW() WHERE  rn=%s and type=%s", (id_bsk,RN,apptype,))
 
 def __db_set_RefereeRecom_time (key):
     run_sql("UPDATE sbmCPLXAPPROVAL SET dRefereeRecom=NOW() WHERE  rn=%s and type=%s", key)
 
 def __db_set_EdBoardRecom_time (key):
     run_sql("UPDATE sbmCPLXAPPROVAL SET dEdBoardRecom=NOW() WHERE  rn=%s and type=%s", key)
 
 def __db_set_PubComRecom_time (key):
     run_sql("UPDATE sbmCPLXAPPROVAL SET dPubComRecom=NOW() WHERE  rn=%s and type=%s", key)
 
 def __db_set_status ((RN,apptype), status):
     run_sql("UPDATE sbmCPLXAPPROVAL SET status=%s, dProjectLeaderAction=NOW() WHERE  rn=%s and type=%s", (status,RN,apptype,))
 
 def doCplxAction(req, doctype, categ, RN, apptype, action, email_user_pattern, id_user, id_user_remove, validate, id_user_val, msg_subject, msg_body, reply, commentId, ln=CFG_SITE_LANG):
     """
     Perform complex action. Note: all argume,ts are supposed to be washed already.
     Return HTML body for the paget.
     In case of errors, deletes hard drive. ;-)
     """
     # load the right message language
     _ = gettext_set_language(ln)
 
     TEXT_RSN_RefereeSel_BASKET_DESCR = "Requests for refereeing process"
     TEXT_RSN_RefereeSel_MSG_REFEREE_SUBJECT = "Referee selection"
     TEXT_RSN_RefereeSel_MSG_REFEREE_BODY = "You have been named as a referee for this document :"
     TEXT_RSN_RefereeSel_MSG_GROUP_SUBJECT = "Please, review this publication"
     TEXT_RSN_RefereeSel_MSG_GROUP_BODY = "Please, review the following publication"
     TEXT_RSN_RefereeRecom_MSG_PUBCOM_SUBJECT = "Final recommendation from the referee"
-    TEXT_RSN_PubComRecom_MSG_PRJLEADER_SUBJECT = "Final recommendation from the publication board"
+    TEXT_RSN_PubComRecom_MSG_PRJLEADER_SUBJECT = "Final recommendation from the publication board : "
     TEXT_RSN_ProjectLeaderDecision_MSG_SUBJECT = "Final decision from the project leader"
 
     TEXT_RPB_EdBoardSel_MSG_EDBOARD_SUBJECT = "You have been selected in a editorial board"
     TEXT_RPB_EdBoardSel_MSG_EDBOARD_BODY = "You have been selected as a member of the editorial board of this document :"
     TEXT_RPB_EdBoardSel_EDBOARD_GROUP_DESCR = "Editorial board for %s"
     TEXT_RPB_RefereeSel_BASKET_DESCR = "Requests for publication"
     TEXT_RPB_RefereeSel_MSG_REFEREE_SUBJECT = "Referee selection"
     TEXT_RPB_RefereeSel_MSG_REFEREE_BODY = "You have been named as a referee for this document :"
     TEXT_RPB_RefereeSel_MSG_GROUP_SUBJECT = "Please, review this publication"
     TEXT_RPB_RefereeSel_MSG_GROUP_BODY = "Please, review the following publication"
     TEXT_RPB_RefereeRecom_MSG_EDBOARD_SUBJECT = "Final recommendation from the referee"
     TEXT_RPB_EdBoardRecom_MSG_PUBCOM_SUBJECT = "Final recommendation from the editorial board"
     TEXT_RPB_PubComRecom_MSG_PRJLEADER_SUBJECT = "Final recommendation from the publication board"
     TEXT_RPB_ProjectLeaderDecision_MSG_SUBJECT = "Final decision from the project leader"
 
     t=""
     uid = getUid(req)
 
     if categ == "":
         categ = "unknown"
 
     key = (RN, apptype)
 
     infos = __db_get_infos (key)
     if len(infos) > 0:
         (status, id_group, id_bskBASKET, id_EdBoardGroup, dummy, dummy,
          dEdBoardSel, dRefereeSel, dRefereeRecom, dEdBoardRecom, dPubComRecom, dProjectLeaderAction) = infos[0]
     else:
         return _("Approval has never been requested for this document.") + "<br />&nbsp;"
 
 
 ## Removing call to deprecated "getInAlice" function and replacing it with
 ## a call to the newer "get_brief_doc_details_from_repository" function:
 ##     try:
 ##         (authors,title,sysno,newrn) = getInAlice(doctype,categ,RN)
 ##     except TypeError:
 ##         return _("Unable to display document.")
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
     if item_details is not None:
         ## Details of the item were found in the CDS Invenio repository
         authors = ", ".join(item_details['authors'])
         newrn = item_details['report-number']
         title = item_details['title']
         sysno = item_details['recid']
     else:
         ## Can't find any document details.
         return _("Unable to display document.")
 
     if (action == "EdBoardSel") and (apptype == "RPB"):
         if __is_PubCom (req, doctype) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         if validate == "go":
             if dEdBoardSel == None:
                 __db_set_EdBoardSel_time (key)
                 perform_request_send (uid, "", RN, TEXT_RPB_EdBoardSel_MSG_EDBOARD_SUBJECT, TEXT_RPB_EdBoardSel_MSG_EDBOARD_BODY)
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         id_EdBoardGroup = __db_check_EdBoardGroup (key, id_EdBoardGroup, uid, TEXT_RPB_EdBoardSel_EDBOARD_GROUP_DESCR)
 
         subtitle1 = _('Adding users to the editorial board')
 
         # remove letters not allowed in an email
         email_user_pattern = cleanstring_email(email_user_pattern)
 
         stopon1 = ""
         stopon2 = ""
         stopon3 = ""
         users = []
         extrausers = []
         # pattern is entered
         if email_user_pattern:
             # users with matching email-address
             try:
-                users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE %s ORDER BY email """, (email_user_pattern, ))
+                users1 = run_sql("""SELECT id, email FROM user WHERE email<>'' AND email RLIKE %s ORDER BY email """, (email_user_pattern, ))
             except OperationalError:
                 users1 = ()
             # users that are connected
             try:
                 users2 = run_sql("""SELECT DISTINCT u.id, u.email
                 FROM user u LEFT JOIN user_usergroup ug ON u.id = ug.id_user
-                WHERE ug.id_usergroup = %s AND u.email RLIKE %s
+                WHERE u.email<>'' AND ug.id_usergroup = %s AND u.email RLIKE %s
                 ORDER BY u.email """, (id_EdBoardGroup, email_user_pattern))
             except OperationalError:
                 users2 = ()
 
             # no users that match the pattern
             if not (users1 or users2):
                 stopon1 = '<p>%s</p>' % _("no qualified users, try new search.")
             elif len(users1) > MAXSELECTUSERS:
                 stopon1 = '<p><strong>%s %s</strong>, %s (%s %s)</p>' % (len(users1), _("hits"), _("too many qualified users, specify more narrow search."), _("limit"), MAXSELECTUSERS)
 
             # show matching users
             else:
                 users = []
                 extrausers = []
                 for (user_id, email) in users1:
                     if (user_id, email) not in users2: users.append([user_id,email,''])
                 for (user_id, email) in users2:
                     extrausers.append([-user_id, email,''])
 
                 try: id_user = int(id_user)
                 except ValueError: pass
                 # user selected already connected to role
                 email_out = acc_get_user_email(id_user)
                 if id_user < 0:
                     stopon2 = '<p>%s</p>' % _("users in brackets are already attached to the role, try another one...")
                 # a user is selected
                 elif email_out:
                     result = insert_new_member(id_user, id_EdBoardGroup, "M")
                     stopon2  = '<p>confirm: user <strong>%s</strong> added to the editorial board.</p>' % (email_out, )
 
         subtitle2 = _('Removing users from the editorial board')
 
         usersremove = run_sql("""SELECT DISTINCT u.id, u.email
                             FROM user u LEFT JOIN user_usergroup ug ON u.id = ug.id_user
-                            WHERE ug.id_usergroup = %s and user_status != 'A' AND user_status != 'P'
+                            WHERE u.email <> "" AND ug.id_usergroup = %s and user_status != 'A' AND user_status != 'P'
                             ORDER BY u.email """, (id_EdBoardGroup, ))
 
         try: id_user_remove = int(id_user_remove)
         except ValueError: pass
         # user selected already connected to role
         email_out = acc_get_user_email(id_user_remove)
         # a user is selected
         if email_out:
             result = delete_member(id_EdBoardGroup, id_user_remove)
             stopon3  = '<p>confirm: user <strong>%s</strong> removed from the editorial board.</p>' % (email_out, )
 
         t = websubmit_templates.tmpl_publiline_displaydocplxaction (
               ln = ln,
               doctype = doctype,
               categ = categ,
               rn = RN,
               apptype = apptype,
               action = action,
               status = status,
               authors = authors,
               title = title,
               sysno = sysno,
               subtitle1 = subtitle1,
               email_user_pattern = email_user_pattern,
               stopon1 = stopon1,
               users = users,
               extrausers = extrausers,
               stopon2 = stopon2,
               subtitle2 = subtitle2,
               usersremove = usersremove,
               stopon3 = stopon3,
               validate_btn = _("Validate the editorial board selection"),
             )
         return t
 
     elif (action == "RefereeSel") and ((apptype == "RRP") or (apptype == "RPB")):
         if apptype == "RRP":
             to_check = __is_PubCom (req, doctype)
             TEXT_RefereeSel_BASKET_DESCR = TEXT_RSN_RefereeSel_BASKET_DESCR
             TEXT_RefereeSel_MSG_REFEREE_SUBJECT = TEXT_RSN_RefereeSel_MSG_REFEREE_SUBJECT
             TEXT_RefereeSel_MSG_REFEREE_BODY = TEXT_RSN_RefereeSel_MSG_REFEREE_BODY + " " + "\"" + item_details['title'] + "\""
             TEXT_RefereeSel_MSG_GROUP_SUBJECT = TEXT_RSN_RefereeSel_MSG_GROUP_SUBJECT
-            TEXT_RefereeSel_MSG_GROUP_BODY = TEXT_RSN_RefereeSel_MSG_GROUP_BODY
+            TEXT_RefereeSel_MSG_GROUP_BODY = TEXT_RSN_RefereeSel_MSG_GROUP_BODY + " " + "\"" + item_details['title'] + "\""
         elif apptype == "RPB":
             to_check = __is_EdBoard (uid, id_EdBoardGroup)
             TEXT_RefereeSel_BASKET_DESCR = TEXT_RSN_RefereeSel_BASKET_DESCR
             TEXT_RefereeSel_MSG_REFEREE_SUBJECT = TEXT_RSN_RefereeSel_MSG_REFEREE_SUBJECT
-            TEXT_RefereeSel_MSG_REFEREE_BODY = TEXT_RSN_RefereeSel_MSG_REFEREE_BODY
+            TEXT_RefereeSel_MSG_REFEREE_BODY = TEXT_RSN_RefereeSel_MSG_REFEREE_BODY + " " + "\"" + item_details['title'] + "\""
             TEXT_RefereeSel_MSG_GROUP_SUBJECT = TEXT_RSN_RefereeSel_MSG_GROUP_SUBJECT
-            TEXT_RefereeSel_MSG_GROUP_BODY = TEXT_RSN_RefereeSel_MSG_GROUP_BODY
+            TEXT_RefereeSel_MSG_GROUP_BODY = TEXT_RSN_RefereeSel_MSG_GROUP_BODY + " " + "\"" + item_details['title'] + "\""
         else:
             to_check = None
 
         if to_check != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         if validate == "go":
             if dRefereeSel == None:
                 id_bsk = basketdb.create_basket (int(id_user_val), RN, TEXT_RefereeSel_BASKET_DESCR)
                 basketdb.share_basket_with_group (id_bsk, id_group, CFG_WEBBASKET_SHARE_LEVELS['ADDCMT'])
                 basketdb.add_to_basket (int(id_user_val), (sysno, ), (id_bsk, ))
 
                 __db_set_basket (key, id_bsk)
 
                 email_address = run_sql("""SELECT email FROM user WHERE id = %s """, (id_user_val, ))[0][0]
                 perform_request_send (uid, email_address, "", TEXT_RefereeSel_MSG_REFEREE_SUBJECT, TEXT_RefereeSel_MSG_REFEREE_BODY, 0, 0, 0, ln, 1)
+		sendMailToReferee(doctype,categ,RN,email_address,authors)
 
                 group_name = run_sql("""SELECT name FROM usergroup WHERE id = %s""", (id_group, ))[0][0]
                 perform_request_send (int(id_user_val), "", group_name, TEXT_RefereeSel_MSG_GROUP_SUBJECT, TEXT_RefereeSel_MSG_GROUP_BODY)
                 sendMailToGroup(doctype,categ,RN,id_group,authors)
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         subtitle1 = _('Referee selection')
 
         # remove letters not allowed in an email
         email_user_pattern = cleanstring_email(email_user_pattern)
 
         stopon1 = ""
         stopon2 = ""
         users = []
         extrausers = []
         # pattern is entered
         if email_user_pattern:
             # users with matching email-address
             try:
-                users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE %s ORDER BY email """, (email_user_pattern, ))
+                users1 = run_sql("""SELECT id, email FROM user WHERE email <> "" AND email RLIKE %s ORDER BY email """, (email_user_pattern, ))
             except OperationalError:
                 users1 = ()
             # no users that match the pattern
             if not users1:
                 stopon1 = '<p>%s</p>' % _("no qualified users, try new search.")
             elif len(users1) > MAXSELECTUSERS:
                 stopon1 = '<p><strong>%s %s</strong>, %s (%s %s)</p>' % (len(users1), _("hits"), _("too many qualified users, specify more narrow search."), _("limit"), MAXSELECTUSERS)
 
             # show matching users
             else:
                 users = []
                 for (user_id, email) in users1:
                     users.append([user_id,email,''])
 
                 try: id_user = int(id_user)
                 except ValueError: pass
                 # user selected already connected to role
                 email_out = acc_get_user_email(id_user)
                 # a user is selected
                 if email_out:
                     stopon2  = """<p>user <strong>%s</strong> will be the referee ?
                                     <input type="hidden" name="id_user_val" value="%s" />
                                     <input type="hidden" name="validate" value="go" />
                                     <input class="adminbutton" type="submit" value="Validate the referee selection" />
                                   </p>""" % (email_out, id_user)
 
         t = websubmit_templates.tmpl_publiline_displaydocplxaction (
               ln = ln,
               doctype = doctype,
               categ = categ,
               rn = RN,
               apptype = apptype,
               action = action,
               status = status,
               authors = authors,
               title = title,
               sysno = sysno,
               subtitle1 = subtitle1,
               email_user_pattern = email_user_pattern,
               stopon1 = stopon1,
               users = users,
               extrausers = [],
               stopon2 = stopon2,
               subtitle2 = "",
               usersremove = [],
               stopon3 = "",
               validate_btn = "",
             )
         return t
 
     elif (action == "AddAuthorList") and (apptype == "RPB"):
         return ""
 
     elif (action == "AddComment") and ((apptype == "RRP") or (apptype == "RPB")):
         t = ""
 
         if validate == "go":
             (errors, infos) = perform_request_save_comment (uid, id_bskBASKET, sysno, msg_subject, msg_body, ln)
             t += "%(infos)s<br /><br />" % {'infos' : infos[0]}
 
         t += """
   <form action="publiline.py">
     <input type="hidden" name="flow" value="cplx" />
     <input type="hidden" name="doctype" value="%(doctype)s" />
     <input type="hidden" name="categ" value="%(categ)s" />
     <input type="hidden" name="RN" value="%(rn)s" />
     <input type="hidden" name="apptype" value="%(apptype)s" />
     <input type="submit" class="formbutton" value="%(button_label)s" />
   </form>""" % {'doctype' : doctype,
                 'categ' : categ,
                 'rn' : RN,
                 'apptype' : apptype,
                 'button_label' : _("Come back to the document"),
                }
 
         return t
 
     elif (action == "RefereeRecom") and ((apptype == "RRP") or (apptype == "RPB")):
         if __is_Referee (uid, id_bskBASKET) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         if apptype == "RRP":
             # Build publication committee chair's email address
             user_addr = ""
             # Try to retrieve the publication committee chair's email from the role database
             for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_%s" % (doctype,categ))):
                 user_addr += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
             # And if there are general publication committee chair's
             for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_*" % doctype)):
                 user_addr += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
             user_addr = re.sub(",$","",user_addr)
             group_addr = ""
             TEXT_RefereeRecom_MSG_SUBJECT = TEXT_RSN_RefereeRecom_MSG_PUBCOM_SUBJECT
         elif apptype == "RPB":
             user_addr = ""
             group_addr = RN
             TEXT_RefereeRecom_MSG_SUBJECT = TEXT_RPB_RefereeRecom_MSG_EDBOARD_SUBJECT
         else:
             user_addr = ""
             group_addr = ""
             TEXT_RefereeRecom_MSG_SUBJECT = ""
 
         if validate == "approve" or validate == "reject":
             if dRefereeRecom == None:
                 perform_request_send (uid, user_addr, group_addr, msg_subject, msg_body, 0, 0, 0, ln, 1)
 
                 if validate == "approve":
                     msg_body = "Approved : " + msg_body
                 else:
                     msg_body = "Rejected : " + msg_body
 
                 #Get the Project Leader's email address
-                email = ""
-                for user in acc_get_role_users(acc_get_role_id("projectleader_%s_%s" % (doctype,categ))):
-                    email += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
-                sendMailToProjectLeader(doctype, categ, RN, email, authors, "referee", msg_body)
+#                email = ""
+#                for user in acc_get_role_users(acc_get_role_id("projectleader_%s_%s" % (doctype,categ))):
+#                    email += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
+#                sendMailToProjectLeader(doctype, categ, RN, email, authors, "referee", msg_body)
                 sendMailtoCommitteeChair(doctype, categ, RN, user_addr, authors)
                 __db_set_RefereeRecom_time (key)
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         t = websubmit_templates.tmpl_publiline_displaycplxrecom (
               ln = ln,
               doctype = doctype,
               categ = categ,
               rn = RN,
               apptype = apptype,
               action = action,
               status = status,
               authors = authors,
               title = title,
               sysno = sysno,
               msg_to = user_addr,
               msg_to_group = group_addr,
               msg_subject = TEXT_RefereeRecom_MSG_SUBJECT,
             )
 
         return t
 
     elif (action == "EdBoardRecom") and (apptype == "RPB"):
         if __is_EdBoard (uid, id_EdBoardGroup) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         # Build publication committee chair's email address
         user_addr = ""
         # Try to retrieve the publication committee chair's email from the role database
         for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_%s" % (doctype,categ))):
             user_addr += run_sql("""SELECT nickname FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
         # And if there are general publication committee chair's
         for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_*" % doctype)):
             user_addr += run_sql("""SELECT nickname FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
         user_addr = re.sub(",$","",user_addr)
 
         if validate == "go":
             if dEdBoardRecom == None:
                 perform_request_send (uid, user_addr, "", msg_subject, msg_body)
                 __db_set_EdBoardRecom_time (key)
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         t = websubmit_templates.tmpl_publiline_displaycplxrecom (
               ln = ln,
               doctype = doctype,
               categ = categ,
               rn = RN,
               apptype = apptype,
               action = action,
               status = status,
               authors = authors,
               title = title,
               sysno = sysno,
               msg_to = user_addr,
               msg_to_group = "",
               msg_subject = TEXT_RPB_EdBoardRecom_MSG_PUBCOM_SUBJECT,
             )
 
         return t
 
     elif (action == "PubComRecom") and ((apptype == "RRP") or (apptype == "RPB")):
         if __is_PubCom (req, doctype) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         # Build project leader's email address
         user_addr = ""
         # Try to retrieve the project leader's email from the role database
         for user in acc_get_role_users(acc_get_role_id("projectleader_%s_%s" % (doctype,categ))):
             user_addr += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
         # And if there are general project leader's
         for user in acc_get_role_users(acc_get_role_id("projectleader_%s_*" % doctype)):
             user_addr += run_sql("""SELECT email FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
         user_addr = re.sub(",$","",user_addr)
 
         if apptype == "RRP":
             TEXT_PubComRecom_MSG_SUBJECT = TEXT_RSN_PubComRecom_MSG_PRJLEADER_SUBJECT
         elif apptype == "RPB":
             group_addr = RN
             TEXT_PubComRecom_MSG_SUBJECT = TEXT_RPB_PubComRecom_MSG_PRJLEADER_SUBJECT
         else:
             TEXT_PubComRecom_MSG_SUBJECT = ""
 
         if validate == "approve" or validate == "reject":
 
             if validate == "approve":
                 msg_body = "Approved : " + msg_body
             else:
                 msg_body = "Rejected : " + msg_body
 
             if dPubComRecom == None:
                 perform_request_send (uid, user_addr, "", msg_subject, msg_body, 0, 0, 0, ln, 1)
                 sendMailToProjectLeader(doctype, categ, RN, user_addr, authors, "publication committee chair", msg_body)
                 __db_set_PubComRecom_time (key)
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         t = websubmit_templates.tmpl_publiline_displaycplxrecom (
               ln = ln,
               doctype = doctype,
               categ = categ,
               rn = RN,
               apptype = apptype,
               action = action,
               status = status,
               authors = authors,
               title = title,
               sysno = sysno,
               msg_to = user_addr,
               msg_to_group = "",
               msg_subject = TEXT_PubComRecom_MSG_SUBJECT + " " + "\"" + item_details['title'] + "\"",
             )
 
         return t
 
     elif (action == "ProjectLeaderDecision") and ((apptype == "RRP") or (apptype == "RPB")):
         if __is_ProjectLeader (req, doctype, categ) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         t += """
   <form action="publiline.py">
     <input type="hidden" name="flow" value="cplx" />
     <input type="hidden" name="doctype" value="%(doctype)s" />
     <input type="hidden" name="categ" value="%(categ)s" />
     <input type="hidden" name="RN" value="%(rn)s" />
     <input type="hidden" name="apptype" value="%(apptype)s" />
     <input type="submit" class="formbutton" value="%(button_label)s" />
   </form>""" % {'doctype' : doctype,
                 'categ' : categ,
                 'rn' : RN,
                 'apptype' : apptype,
-                'button_label' : _("Come back to the document"),
+                'button_label' : _("Back to the document"),
                }
 
         if validate == "approve":
             if dProjectLeaderAction == None:
                 (errors, infos) = perform_request_save_comment (uid, id_bskBASKET, sysno, msg_subject, msg_body, ln)
                 out = "%(infos)s<br /><br />" % {'infos' : infos[0]}
 
                 sendMailToSubmitter(doctype, categ, RN, "approved")
                 __db_set_status (key, 'approved')
             return out + t
 
         elif validate == "reject":
             if dProjectLeaderAction == None:
                 (errors, infos) = perform_request_save_comment (uid, id_bskBASKET, sysno, msg_subject, msg_body, ln)
                 out = "%(infos)s<br /><br />" % {'infos' : infos[0]}
 
                 sendMailToSubmitter(doctype, categ, RN, "rejected")
                 __db_set_status (key, 'rejected')
             return out + t
 
         validation = """
     <select name="validate">
       <option> %(select)s</option>
       <option value="approve">%(approve)s</option>
       <option value="reject">%(reject)s</option>
     </select>
     <input type="submit" class="formbutton" value="%(button_label)s" />""" % {'select' : _('Select:'),
                                                                               'approve' : _('Approve'),
                                                                               'reject' : _('Reject'),
                                                                               'button_label' : _('Take a decision'),
                                                                              }
 
         if apptype == "RRP":
             TEXT_ProjectLeaderDecision_MSG_SUBJECT = TEXT_RSN_ProjectLeaderDecision_MSG_SUBJECT
         elif apptype == "RPB":
             TEXT_ProjectLeaderDecision_MSG_SUBJECT = TEXT_RPB_ProjectLeaderDecision_MSG_SUBJECT
         else:
             TEXT_ProjectLeaderDecision_MSG_SUBJECT = ""
 
         t = websubmit_templates.tmpl_publiline_displaywritecomment(doctype, categ, RN, apptype, action, _("Take a decision"), TEXT_ProjectLeaderDecision_MSG_SUBJECT, validation, "", ln)
 
         return t
 
     elif (action == "ProjectLeaderDecision") and (apptype == "RDA"):
         if __is_ProjectLeader (req, doctype, categ) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if status == "cancelled":
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         if validate == "approve":
             if dProjectLeaderAction == None:
                 __db_set_status (key, 'approved')
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         elif validate == "reject":
             if dProjectLeaderAction == None:
                 __db_set_status (key, 'rejected')
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         t = """<p>
                  <form action="publiline.py">
                     <input type="hidden" name="flow" value="cplx" />
                     <input type="hidden" name="doctype" value="%(doctype)s" />
                     <input type="hidden" name="categ" value="%(categ)s" />
                     <input type="hidden" name="RN" value="%(rn)s" />
                     <input type="hidden" name="apptype" value="%(apptype)s" />
                     <input type="hidden" name="action" value="%(action)s" />
                     <input type="hidden" name="validate" value="approve" />
                     <input class="adminbutton" type="submit" value="%(approve)s" />
                   </form>
                   <form action="publiline.py">
                     <input type="hidden" name="flow" value="cplx" />
                     <input type="hidden" name="doctype" value="%(doctype)s" />
                     <input type="hidden" name="categ" value="%(categ)s" />
                     <input type="hidden" name="RN" value="%(rn)s" />
                     <input type="hidden" name="apptype" value="%(apptype)s" />
                     <input type="hidden" name="action" value="%(action)s" />
                     <input type="hidden" name="validate" value="reject" />
                     <input class="adminbutton" type="submit" value="%(reject)s" />
                   </form>
                 </p>""" % {
                  'rn' : RN,
                  'categ' : categ,
                  'doctype' : doctype,
                  'apptype' : apptype,
                  'action' : action,
                  'approve' : _('Approve'),
                  'reject' : _('Reject'),
                }
 
         return t
 
     elif (action == "AuthorCancel") and ((apptype == "RRP") or (apptype == "RPB") or (apptype == "RDA")):
         if __is_Author (uid, sysno) != 0:
             return _("Action unauthorized for this document.") + "<br />&nbsp;"
 
         if (status == "cancelled") or (dProjectLeaderAction != None):
             return _("Action unavailable for this document.") + "<br />&nbsp;"
 
         if validate == "go":
             __db_set_status (key, 'cancelled')
             return displayCplxDocument(req, doctype,categ,RN,apptype, reply, commentId, ln)
 
         t = """<p>
                  <form action="publiline.py">
                     <input type="hidden" name="flow" value="cplx" />
                     <input type="hidden" name="doctype" value="%(doctype)s" />
                     <input type="hidden" name="categ" value="%(categ)s" />
                     <input type="hidden" name="RN" value="%(rn)s" />
                     <input type="hidden" name="apptype" value="%(apptype)s" />
                     <input type="hidden" name="action" value="%(action)s" />
                     <input type="hidden" name="validate" value="go" />
                     <input class="adminbutton" type="submit" value="%(cancel)s" />
                   </form>
                 </p>""" % {
                  'rn' : RN,
                  'categ' : categ,
                  'doctype' : doctype,
                  'apptype' : apptype,
                  'action' : action,
                  'cancel' : _('Cancel'),
                }
         return t
 
     else:
         return _("Wrong action for this document.") + "<br />&nbsp;"
 
     return t
 
 def get_pending_item_details(doctype, reportnumber):
     """Given a doctype and reference number, try to retrieve an item's details.
        The first place to search for them should be the WebSubmit pending
        directory. If nothing is retrieved from there, and attempt is made
        to retrieve them from the CDS Invenio repository itself.
        @param doctype: (string) - the doctype of the item for which brief
         details are to be retrieved.
        @param reportnumber: (string) - the report number of the item
         for which details are to be retrieved.
        @return: (dictionary or None) - If details are found for the item,
         they will be returned in a dictionary structured as follows:
             { 'title'         : '-', ## String - the item's title
               'recid'         : '',  ## String - recid taken from the SN file
               'report-number' : '',  ## String - the item's report number
               'authors'       : [],  ## List   - the item's authors
             }
         If no details were found a NoneType is returned.
     """
     ## First try to get the details of a document from the pending dir:
     item_details = get_brief_doc_details_from_pending(doctype, \
                                                       reportnumber)
     if item_details is None:
         item_details = get_brief_doc_details_from_repository(reportnumber)
     ## Return the item details:
     return item_details
 
 def get_brief_doc_details_from_pending(doctype, reportnumber):
     """Try to get some brief details about the submission that is awaiting
        the referee's decision.
        Details sought are:
         + title
         + Authors
         + recid (why?)
         + report-number (why?)
        This function searches for a MARC XML record in the pending submission's
        working directory. It prefers the so-called 'dummy' record, but will
        search for the final MARC XML record that would usually be passed to
        bibupload (i.e. recmysql) if that is not present. If neither of these
        records are present, no details will be found.
        @param doctype: (string) - the WebSubmit document type of the item
         to be refereed. It is used in order to locate the submission's
         working directory in the WebSubmit pending directory.
        @param reportnumber: (string) - the report number of the item for
         which details are to be recovered. It is used in order to locate the
         submission's working directory in the WebSubmit pending directory.
        @return: (dictionary or None) - If details are found for the item,
         they will be returned in a dictionary structured as follows:
             { 'title'            : '-', ## String - the item's title
               'recid'            : '',  ## String - recid taken from the SN file
               'report-number'    : '',  ## String - the item's report number
               'authors'          : [],  ## List   - the item's authors
             }
         If no details were found (i.e. no MARC XML files in the submission's
         working directory), a NoneType is returned.
     """
     pending_doc_details = None
     marcxml_rec_name = None
     ## Check for a MARC XML record in the pending dir.
     ## If it's there, we will use it to obtain certain bibliographic
     ## information such as title, author(s), etc, which we will then
     ## display to the referee.
     ## We favour the "dummy" record (created with the WebSubmit function
     ## "Make_Dummy_MARC_XML_Record"), because it was made for this
     ## purpose. If it's not there though, we'll take the normal
     ## (final) recmysql record that would generally be passed to bibupload.
     if os.access("%s/%s/%s/%s" % (CFG_WEBSUBMIT_PENDING_DIR, \
                                   doctype, \
                                   reportnumber, \
                                   CFG_WEBSUBMIT_DUMMY_MARC_XML_REC), \
                  os.F_OK|os.R_OK):
         ## Found the "dummy" marc xml record in the submission dir.
         ## Use it:
         marcxml_rec_name = CFG_WEBSUBMIT_DUMMY_MARC_XML_REC
     elif os.access("%s/%s/%s/%s" % (CFG_WEBSUBMIT_PENDING_DIR, \
                                     doctype, \
                                     reportnumber, \
                                     CFG_WEBSUBMIT_MARC_XML_REC), \
                    os.F_OK|os.R_OK):
         ## Although we didn't find the "dummy" marc xml record in the
         ## submission dir, we did find the "real" one (that which would
         ## normally be passed to bibupload). Use it:
         marcxml_rec_name = CFG_WEBSUBMIT_MARC_XML_REC
 
     ## If we have a MARC XML record in the pending submission's
     ## working directory, go ahead and use it:
     if marcxml_rec_name is not None:
         try:
             fh_marcxml_record = open("%s/%s/%s/%s" \
                                      % (CFG_WEBSUBMIT_PENDING_DIR, \
                                         doctype, \
                                         reportnumber, \
                                         marcxml_rec_name), "r")
             xmltext = fh_marcxml_record.read()
             fh_marcxml_record.close()
         except IOError:
             ## Unfortunately, it wasn't possible to read the details of the
             ## MARC XML record. Register the exception.
             exception_prefix = "Error: Publiline was unable to read the " \
                                "MARC XML record [%s/%s/%s/%s] when trying to " \
                                "use it to recover details about a pending " \
                                "submission." % (CFG_WEBSUBMIT_PENDING_DIR, \
                                                 doctype, \
                                                 reportnumber, \
                                                 marcxml_rec_name)
             register_exception(prefix=exception_prefix)
         else:
             ## Attempt to use bibrecord to create an internal representation
             ## of the record, from which we can extract certain bibliographic
             ## information:
             records = create_records(xmltext, 1, 1)
             try:
                 record = records[0][0]
             except IndexError:
                 ## Bibrecord couldn't successfully represent the record
                 ## contained in the xmltext string. The record must have
                 ## been empty or badly formed (or something).
                 pass
             else:
                 ## Dictionary to hold the interesting details of the
                 ## pending item:
                 pending_doc_details = { 'title'         : '-',
                                         'recid'         : '',
                                         'report-number' : '',
                                         'authors'       : [],
                                       }
                 ## Get the recid:
                 ## Note - the old "getInPending" function reads the "SN"
                 ## file from the submission's working directory and since
                 ## the "SN" file is currently "magic" and hardcoded
                 ## throughout WebSubmit, I'm going to stick to this model.
                 ## I could, however, have tried to get it from the MARC XML
                 ## record as so:
                 ## recid = record_get_field_value(rec=record, tag="001")
                 try:
                     fh_recid = open("%s/%s/%s/SN" \
                                     % (CFG_WEBSUBMIT_PENDING_DIR, \
                                        doctype, \
                                        reportnumber), "r")
                     recid = fh_recid.read()
                     fh_recid.close()
                 except IOError:
                     ## Probably, there was no "SN" file in the submission's
                     ## working directory.
                     pending_doc_details['recid'] = ""
                 else:
                     pending_doc_details['recid'] = recid.strip()
 
                 ## Item report number (from record):
                 ## Note: I don't know what purpose this serves. It appears
                 ## to be used in the email that is sent to the author, but
                 ## it seems funny to me, since we already have the report
                 ## number (which is indeed used to find the submission's
                 ## working directory in pending). Perhaps it's used for
                 ## cases when the reportnumber is changed after approval?
                 ## To investigate when time allows:
                 finalrn = record_get_field_value(rec=record, \
                                                  tag="037", \
                                                  code="a")
                 if finalrn != "":
                     pending_doc_details['report-number'] = finalrn
 
                 ## Item title:
                 title = record_get_field_value(rec=record, \
                                                tag="245", \
                                                code="a")
                 if title != "":
                     pending_doc_details['title'] = title
                 else:
                     ## Alternative title:
                     alt_title = record_get_field_value(rec=record, \
                                                        tag="246", \
                                                        ind1="1", \
                                                        code="a")
                     if alt_title != "":
                         pending_doc_details['title'] = alt_title
 
                 ## Item first author:
                 first_author = record_get_field_value(rec=record, \
                                                       tag="100", \
                                                       code="a")
                 if first_author != "":
                     pending_doc_details['authors'].append(first_author)
 
                 ## Other Authors:
                 other_authors = record_get_field_values(rec=record, \
                                                         tag="700", \
                                                         code="a")
                 for author in other_authors:
                     pending_doc_details['authors'].append(author)
 
     ## Return the details discovered about the pending document:
     return pending_doc_details
 
 
 def get_brief_doc_details_from_repository(reportnumber):
     """Try to get some brief details about the submission that is awaiting
        the referee's decision.
        Details sought are:
         + title
         + Authors
         + recid (why?)
         + report-number (why?)
         + email
        This function searches in the CDS Invenio repository, based on
        "reportnumber" for a record and then pulls the interesting fields
        from it.
        @param reportnumber: (string) - the report number of the item for
         which details are to be recovered. It is used in the search.
        @return: (dictionary or None) - If details are found for the item,
         they will be returned in a dictionary structured as follows:
             { 'title'            : '-', ## String - the item's title
               'recid'            : '',  ## String - recid taken from the SN file
               'report-number'    : '',  ## String - the item's report number
               'authors'          : [],  ## List   - the item's authors
             }
         If no details were found a NoneType is returned.
     """
     ## Details of the pending document, as found in the repository:
     pending_doc_details = None
     ## Search for records matching this "report number"
     found_record_ids = list(search_pattern(req=None, \
                                            p=reportnumber, \
                                            f="reportnumber", \
                                            m="e"))
     ## How many records were found?
     if len(found_record_ids) == 1:
         ## Found only 1 record. Get the fields of interest:
         pending_doc_details = { 'title'         : '-',
                                 'recid'         : '',
                                 'report-number' : '',
                                 'authors'       : [],
                                 'email'         : '',
                               }
         recid = found_record_ids[0]
         ## Authors:
         first_author  = get_fieldvalues(recid, "100__a")
         for author in first_author:
             pending_doc_details['authors'].append(author)
         other_authors = get_fieldvalues(recid, "700__a")
         for author in other_authors:
             pending_doc_details['authors'].append(author)
         ## Title:
         title = get_fieldvalues(recid, "245__a")
         if len(title) > 0:
             pending_doc_details['title'] = title[0]
         else:
             ## There was no value for title - check for an alternative title:
             alt_title = get_fieldvalues(recid, "2641_a")
             if len(alt_title) > 0:
                 pending_doc_details['title'] = alt_title[0]
         ## Record ID:
         pending_doc_details['recid'] = recid
         ## Report Number:
         reptnum = get_fieldvalues(recid, "037__a")
         if len(reptnum) > 0:
             pending_doc_details['report-number'] = reptnum[0]
         ## Email:
         email = get_fieldvalues(recid, "859__f")
         if len(email) > 0:
             pending_doc_details['email'] = email[0]
     elif len(found_record_ids) > 1:
         ## Oops. This is unexpected - there shouldn't be me multiple matches
         ## for this item. The old "getInAlice" function would have simply
         ## taken the first record in the list. That's not very nice though.
         ## Some kind of warning or error should be raised here. FIXME.
         pass
     return pending_doc_details
 
 
 # Retrieve info about document
 def getInfo(doctype,categ,RN):
     """FIXME: DEPRECATED!"""
     result = getInPending(doctype,categ,RN)
     if not result:
         result = getInAlice(doctype,categ,RN)
     return result
 
 #seek info in pending directory
 def getInPending(doctype,categ,RN):
     """FIXME: DEPRECATED!"""
     PENDIR="%s/pending" % CFG_WEBSUBMIT_STORAGEDIR
     if os.path.exists("%s/%s/%s/AU" % (PENDIR,doctype,RN)):
         fp = open("%s/%s/%s/AU" % (PENDIR,doctype,RN),"r")
         authors=fp.read()
         fp.close()
     else:
         authors = ""
     if os.path.exists("%s/%s/%s/TI" % (PENDIR,doctype,RN)):
         fp = open("%s/%s/%s/TI" % (PENDIR,doctype,RN),"r")
         title=fp.read()
         fp.close()
     else:
         title = ""
     if os.path.exists("%s/%s/%s/SN" % (PENDIR,doctype,RN)):
         fp = open("%s/%s/%s/SN" % (PENDIR,doctype,RN),"r")
         sysno=fp.read()
         fp.close()
     else:
         sysno = ""
     if title == "" and os.path.exists("%s/%s/%s/TIF" % (PENDIR,doctype,RN)):
         fp = open("%s/%s/%s/TIF" % (PENDIR,doctype,RN),"r")
         title=fp.read()
         fp.close()
     if title == "":
         return 0
     else:
         return (authors,title,sysno,"")
 
 #seek info in Alice database
 def getInAlice(doctype,categ,RN):
     """FIXME: DEPRECATED!"""
     # initialize sysno variable
     sysno = ""
     searchresults = list(search_pattern(req=None, p=RN, f="reportnumber"))
     if len(searchresults) == 0:
         return 0
     sysno = searchresults[0]
     if sysno != "":
         title = Get_Field('245__a',sysno)
         emailvalue = Get_Field('8560_f',sysno)
         authors = Get_Field('100__a',sysno)
         authors += "\n%s" % Get_Field('700__a',sysno)
         newrn = Get_Field('037__a',sysno)
         return (authors,title,sysno,newrn)
     else:
         return 0
 
 def SendEnglish(doctype,categ,RN,title,authors,access,sysno):
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
     # retrieve useful information from webSubmit configuration
     res = run_sql("select value from sbmPARAMETERS where name='categformatDAM' and doctype=%s", (doctype,))
     categformat = res[0][0]
     categformat = re.sub("<CATEG>","([^-]*)",categformat)
     categs = re.match(categformat,RN)
     if categs is not None:
         categ = categs.group(1)
     else:
         categ = "unknown"
     res = run_sql("select value from sbmPARAMETERS where name='addressesDAM' and doctype=%s",(doctype,))
     if len(res) > 0:
         otheraddresses = res[0][0]
         otheraddresses = otheraddresses.replace("<CATEG>",categ)
     else:
         otheraddresses = ""
     # Build referee's email address
     refereeaddress = ""
     # Try to retrieve the referee's email from the referee's database
     for user in acc_get_role_users(acc_get_role_id("referee_%s_%s" % (doctype,categ))):
         refereeaddress += user[1] + ","
     # And if there are general referees
     for user in acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
         refereeaddress += user[1] + ","
     refereeaddress = re.sub(",$","",refereeaddress)
     # Creation of the mail for the referee
     addresses = ""
     if refereeaddress != "":
         addresses = refereeaddress + ","
     if otheraddresses != "":
         addresses += otheraddresses
     else:
         addresses = re.sub(",$","",addresses)
     if addresses=="":
         SendWarning(doctype,categ,RN,title,authors,access)
         return 0
     if authors == "":
         authors = "-"
     res = run_sql("select value from sbmPARAMETERS where name='directory' and doctype=%s", (doctype,))
     directory = res[0][0]
     message = """
     The document %s has been published as a Communication.
     Your approval is requested for it to become an official Note.
 
     Title: %s
 
     Author(s): %s
 
     To access the document(s), select the file(s) from the location:
     <%s/record/%s/files/>
 
     To approve/reject the document, you should go to this URL:
     <%s/approve.py?%s>
 
     ---------------------------------------------
     Best regards.
     The submission team.""" % (RN,title,authors,CFG_SITE_URL,sysno,CFG_SITE_URL,access)
     # send the mail
     send_email(FROMADDR,addresses,"Request for Approval of %s" % RN, message,footer="")
     return ""
 
 def SendWarning(doctype,categ,RN,title,authors,access):
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
     message = "Failed sending approval email request for %s" % RN
     # send the mail
     send_email(FROMADDR,CFG_SITE_ADMIN_EMAIL,"Failed sending approval email request",message)
     return ""
 
 def errorMsg(title,req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG):
     return page(title="error",
                 body = create_error_box(req, title=title,verbose=0, ln=ln),
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='yourapprovals')
 
 def warningMsg(title,req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG):
     return page(title="warning",
                 body = title,
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 uid = getUid(req),
                 language=ln,
                 req=req,
                 navmenuid='yourapprovals')
 
 def sendMailToReferee(doctype,categ,RN,email,authors):
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
 
 
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
 
     message = """
     Scientific Note approval for document %s has been submitted to the CERN Document Server.
-    Your reccommendation is requested on it.
+    Your recommendation is requested on it.
 
     Requested subcategory: %s
 
     Title: %s
 
     Author(s): %s
 
     To access the document(s), select the file(s) from the location:
     <%s/record/%s>
 
     To make a reccommendation, you should go to this URL:
     <%s>
 
     You can also check the status of the document:
     <%s>
 
     ---------------------------------------------
     Best regards.
     The submission team.""" % (str(RN),
                                str(categ),
                                str(item_details['title']),
                                authors,
                                CFG_SITE_URL,
                                str(item_details['recid']),
                                str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN+"&action=RefereeRecom"),
                                str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN))
 
     # send the mail
     send_email(FROMADDR, email,"Request for document %s recommendation" % (RN),message)
     return ""
 
 def sendMailToGroup(doctype,categ,RN,group_id,authors):
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
 
 
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
 
     message = """
     Scientific Note approval for document %s has been submitted to the CERN Document Server.
     Your comments are requested on this document.
 
     Requested subcategory: %s
 
     Title: %s
 
     Author(s): %s
 
     To access the document(s), select the file(s) from the location:
     <%s/record/%s>
 
     To leave a comment or check the status of the approval process, you should go to this URL:
     <%s>
 
     """ % (str(RN),
            str(categ),
            str(item_details['title']),
            authors,
            CFG_SITE_URL,
            str(item_details['recid']),
            str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN))
 
     # send mails to all members of the ATLAS group
     group_member_ids = run_sql("SELECT id_user FROM user_usergroup WHERE id_usergroup = '%s'" % (group_id))
     for member_id in group_member_ids:
         member_email = run_sql("SELECT email FROM user WHERE id = '%s'" % (member_id))
         if not member_email[0][0] == "cds.support@cern.ch":
             send_email(FROMADDR, member_email[0][0],"Request for comment on document %s" % (RN),message)
     return ""
 
 def sendMailToProjectLeader(doctype, categ, RN, email, authors, actor, recommendation):
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
 
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
 
     message = """
     Scientific Note approval for document %s has been submitted to the CERN Document Server.
     Your approval is requested for this document. Once you have received recommendations from both the referee and the publication committee chair, you will be able to make your decision.
 
     Requested subcategory: %s
 
     Title: %s
 
     Author(s): %s
 
     To access the document(s), select the file(s) from the location:
     <%s/record/%s>
 
     The %s has made a recommendation for the document. He/she said the following:
 
     %s
 
     You can approve this document by visiting this page:
     <%s>
+
+    You can also check the status of the document from:
+    <%s>
+
     """ % (str(RN),
            str(categ),
            str(item_details['title']),
            authors,
            CFG_SITE_URL,
            str(item_details['recid']),
            actor,
            recommendation,
-           str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN+"&action=ProjectLeaderDecision"))
+           str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN+"&action=ProjectLeaderDecision"),
+           str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN))
 
     # send mails to all members of the ATLAS group
     send_email(FROMADDR, email,"Request for approval/rejection of document %s" % (RN),message)
     return ""
 
 def sendMailToSubmitter(doctype, categ, RN, outcome):
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
 
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
 
     message = """
     The approval process for your document : %s, has been completed. The details of this document are as follows:
 
     Requested subcategory: %s
     Title: %s
 
     The project leader has made the following recommendation for the document:
 
     %s
     """ % (RN, categ, item_details['title'], outcome)
 
     # send mails to all members of the ATLAS group
     send_email(FROMADDR, item_details['email'],"Final outcome for approval of document : %s" % (RN),message)
     return ""
 
 def sendMailtoCommitteeChair(doctype, categ, RN, email, authors):
     item_details = get_brief_doc_details_from_repository(RN)
     ## get_brief_doc_details_from_repository has returned either None
     ## or a dictionary with the following structure:
     ##   { 'title'            : '-', ## String - the item's title
     ##     'recid'            : '',  ## String - recid
     ##     'report-number'    : '',  ## String - the item's report number
     ##     'authors'          : [],  ## List   - the item's authors
     ##   }
 
     FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
 
     message = """
     The referree assigned to the document detailed below has made a reccommendation. You are now requested to make a reccommendation of your own.
 
     Requested subcategory: %s
 
     Title: %s
 
     Author(s): %s
 
     To access the document(s), select the file(s) from the location:
     <%s/record/%s>
 
     You can make a reccommendation by visiting this page:
     <%s>
     """ % (str(categ),
            str(item_details['title']),
            authors,
            CFG_SITE_URL,
            str(item_details['recid']),
            str(CFG_SITE_URL + "/publiline.py?flow=cplx&doctype="+doctype+"&ln=en&apptype=RRP&categ="+categ+"&RN="+RN))
 
     # send mails to all members of the ATLAS group
     send_email(FROMADDR, email,"Request for reccommendation of document %s" % (RN),message)
 
 
diff --git a/modules/websubmit/web/test_submit_article.html b/modules/websubmit/web/test_submit_article.html
index 3922a4c2c..cebb3c7b3 100644
--- a/modules/websubmit/web/test_submit_article.html
+++ b/modules/websubmit/web/test_submit_article.html
@@ -1,132 +1,132 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head profile="http://selenium-ide.openqa.org/profiles/test-case">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <link rel="selenium.base" href="http://localhost" />
 <title>test_submit_article</title>
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
 <thead>
 <tr><td rowspan="1" colspan="3">test_submit_article</td></tr>
 </thead><tbody>
 <tr>
-        <td>open</td>
-        <td>http://localhost</td>
-        <td></td>
+	<td>open</td>
+	<td>http://localhost</td>
+	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>jekyll</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>j123ekyll</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Submit</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Demo Article Submission</td>
 	<td></td>
 </tr>
 <tr>
 	<td>click</td>
 	<td>comboARTICLE</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>//input[@value='Submit New Record']</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_REP</td>
 	<td>Test-Ref-001<br />Test-Ref-002</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_TITLE</td>
 	<td>Test article document title</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_AU</td>
 	<td>Author1, Firstname1<br />Author2, Firstname2</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_ABS</td>
 	<td>This is a test abstract.<br />It has some more lines.<br /><br />...and some empty lines.<br /><br />And it finishes here.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_NUMP</td>
 	<td>1234</td>
 </tr>
 <tr>
 	<td>select</td>
 	<td>DEMOART_LANG</td>
 	<td>label=French</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_DATE</td>
 	<td>11/01/2001</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_KW</td>
 	<td>test keyword1<br />test keyword2<br />test keyword3</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_NOTE</td>
 	<td>I don't think I have any additional comments.<br />But maybe I'll input some quotes here: &quot; ' ` and the rest.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_FILE</td>
 	<td>/opt/cds-invenio/lib/webtest/invenio/test.pdf</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>endS</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Submission Complete!<br /></td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>our document has the following reference(s): DEMO-ARTICLE</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 
 </tbody></table>
 </body>
 </html>
diff --git a/modules/websubmit/web/test_submit_book_approval.html b/modules/websubmit/web/test_submit_book_approval.html
index d67692da5..182121932 100644
--- a/modules/websubmit/web/test_submit_book_approval.html
+++ b/modules/websubmit/web/test_submit_book_approval.html
@@ -1,127 +1,127 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head profile="http://selenium-ide.openqa.org/profiles/test-case">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<link rel="selenium.base" href="http://localhost" />
+<link rel="selenium.base" href="http://localhost/" />
 <title>test_submit_book_approval</title>
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
 <thead>
 <tr><td rowspan="1" colspan="3">test_submit_book_approval</td></tr>
 </thead><tbody>
 <tr>
 	<td>open</td>
 	<td>http://localhost</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>hyde</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>h123yde</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=approvals</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextNotPresent</td>
 	<td>You are a general referee</td>
 	<td></td>
 </tr>
 <tr>
 	<td>open</td>
 	<td>http://localhost/publiline.py?doctype=DEMOBOO</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=DEMO-BOOK-2008-001</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextNotPresent</td>
 	<td>As a referee for this document, you may click this button to approve or reject it</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login here</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>dorian</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>d123orian</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=approvals</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>You are a general referee</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=You are a general referee</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>DEMO-BOOK-</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=DEMO-BOOK-2008-001</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>As a referee for this document, you may click this button to approve or reject it</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 
 </tbody></table>
 </body>
 </html>
diff --git a/modules/websubmit/web/test_submit_picture.html b/modules/websubmit/web/test_submit_picture.html
index 849a2becc..55549d8f7 100644
--- a/modules/websubmit/web/test_submit_picture.html
+++ b/modules/websubmit/web/test_submit_picture.html
@@ -1,122 +1,122 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head profile="http://selenium-ide.openqa.org/profiles/test-case">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<link rel="selenium.base" href="http://localhost" />
+<link rel="selenium.base" href="http://localhost/" />
 <title>test_submit_picture</title>
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
 <thead>
 <tr><td rowspan="1" colspan="3">test_submit_picture</td></tr>
 </thead><tbody>
 <tr>
 	<td>open</td>
 	<td>http://localhost</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>jekyll</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>j123ekyll</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Submit</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Demo Picture Submission</td>
 	<td></td>
 </tr>
 <tr>
 	<td>click</td>
 	<td>comboLIFE</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>//input[@value='Submit New Record']</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_TITLE</td>
 	<td>Test picture title</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_PHOTOG</td>
 	<td>AuthorA, FirstnameA<br />AuthorB, FirstnameB<br />AuthorC, FirstnameC</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_DATE</td>
 	<td>11/01/2001</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_KW</td>
 	<td>test keyword 1<br />test keyword 2</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_DESCR</td>
 	<td>This is some test description of the test picture.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_ADD_RN</td>
 	<td>test-ref-a<br />test-ref-b</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_NOTE</td>
 	<td>This is a test comment.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPIC_FILE</td>
 	<td>/opt/cds-invenio/lib/webtest/invenio/test.jpg</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>endS</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Submission Complete!<br /></td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Your document has the following reference(s): DEMO-PICTURE-LIFE-</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 
 </tbody></table>
 </body>
 </html>
diff --git a/modules/websubmit/web/test_submit_poetry.html b/modules/websubmit/web/test_submit_poetry.html
index 0214a949e..909e1b9bb 100644
--- a/modules/websubmit/web/test_submit_poetry.html
+++ b/modules/websubmit/web/test_submit_poetry.html
@@ -1,107 +1,107 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head profile="http://selenium-ide.openqa.org/profiles/test-case">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<link rel="selenium.base" href="http://localhost" />
+<link rel="selenium.base" href="http://localhost/" />
 <title>test_submit_poetry</title>
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
 <thead>
 <tr><td rowspan="1" colspan="3">test_submit_poetry</td></tr>
 </thead><tbody>
 <tr>
 	<td>open</td>
 	<td>http://localhost</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>jekyll</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>j123ekyll</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Submit</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Demo Poetry Submission</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>//input[@value='Submit New Record']</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPOE_TITLE</td>
 	<td>A test poem</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPOE_AU</td>
 	<td>Doe, John</td>
 </tr>
 <tr>
 	<td>select</td>
 	<td>DEMOPOE_LANG</td>
 	<td>label=Slovak</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPOE_YEAR</td>
 	<td>1234</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>//strong/font</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOPOE_ABS</td>
 	<td>This is a test poem&lt;br&gt;<br />a test poem indeed&lt;br&gt;<br />with some accented characters&lt;br&gt;<br />&lt;br&gt;<br />Ελληνικά&lt;br&gt; <br />日本語&lt;br&gt;<br />Español </td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>endS</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Submission Complete!<br /></td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Your document has the following reference(s): DEMO-POETRY-</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 
 </tbody></table>
 </body>
 </html>
diff --git a/modules/websubmit/web/test_submit_tar_gz.html b/modules/websubmit/web/test_submit_tar_gz.html
index 77b021de0..7c748fb02 100644
--- a/modules/websubmit/web/test_submit_tar_gz.html
+++ b/modules/websubmit/web/test_submit_tar_gz.html
@@ -1,132 +1,132 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head profile="http://selenium-ide.openqa.org/profiles/test-case">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<link rel="selenium.base" href="http://localhost" />
+<link rel="selenium.base" href="http://localhost/" />
 <title>test_submit_tar_gz</title>
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
 <thead>
 <tr><td rowspan="1" colspan="3">test_submit_tar_gz</td></tr>
 </thead><tbody>
 <tr>
-        <td>open</td>
-        <td>http://localhost</td>
-        <td></td>
+	<td>open</td>
+	<td>http://localhost</td>
+	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=login</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_un</td>
 	<td>jekyll</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>p_pw</td>
 	<td>j123ekyll</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>action</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Submit</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=Demo Article Submission</td>
 	<td></td>
 </tr>
 <tr>
 	<td>click</td>
 	<td>comboARTICLE</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>//input[@value='Submit New Record']</td>
 	<td></td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_REP</td>
 	<td>Test-Ref-001<br />Test-Ref-002</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_TITLE</td>
 	<td>Test article tar gz document title</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_AU</td>
 	<td>Author1, Firstname1<br />Author2, Firstname2</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_ABS</td>
 	<td>This is a test abstract.<br />It has some more lines.<br /><br />...and some empty lines.<br /><br />And it finishes here.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_NUMP</td>
 	<td>1234</td>
 </tr>
 <tr>
 	<td>select</td>
 	<td>DEMOART_LANG</td>
 	<td>label=French</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_DATE</td>
 	<td>11/01/2001</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_KW</td>
 	<td>test keyword1<br />test keyword2<br />test keyword3</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_NOTE</td>
 	<td>I don't think I have any additional comments.<br />But maybe I'll input some quotes here: &quot; ' ` and the rest.</td>
 </tr>
 <tr>
 	<td>type</td>
 	<td>DEMOART_FILE</td>
 	<td>/opt/cds-invenio/lib/webtest/invenio/test.tar.gz</td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>endS</td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>Submission Complete!<br /></td>
 	<td></td>
 </tr>
 <tr>
 	<td>verifyTextPresent</td>
 	<td>our document has the following reference(s): DEMO-ARTICLE</td>
 	<td></td>
 </tr>
 <tr>
 	<td>clickAndWait</td>
 	<td>link=logout</td>
 	<td></td>
 </tr>
 
 </tbody></table>
 </body>
 </html>
diff --git a/modules/websubmit/web/yourapprovals.py b/modules/websubmit/web/yourapprovals.py
index 979b560fc..5cd39531a 100644
--- a/modules/websubmit/web/yourapprovals.py
+++ b/modules/websubmit/web/yourapprovals.py
@@ -1,122 +1,119 @@
 ## $Id$
 
 ## This file is part of CDS Invenio.
 ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
 ##
 ## CDS Invenio 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.
 ##
 ## CDS Invenio 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 CDS Invenio; if not, write to the Free Software Foundation, Inc.,
 ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
 __revision__ = "$Id$"
 
 ## import interesting modules:
 import os
 import sys
 
 from invenio.config import \
      CFG_ACCESS_CONTROL_LEVEL_SITE, \
      CFG_SITE_LANG, \
      CFG_SITE_NAME, \
      CFG_SITE_SECURE_URL, \
      CFG_VERSION
 from invenio.dbquery import run_sql, Error
 from invenio.access_control_engine import acc_authorize_action
 from invenio.access_control_admin import *
 from invenio.webpage import page, create_error_box
 from invenio.webuser import getUid, get_email, list_registered_users, page_not_authorized
 from invenio.messages import gettext_set_language, wash_language
 from invenio.websubmit_config import *
 from invenio.search_engine import search_pattern
 
 import invenio.template
 websubmit_templates = invenio.template.load('websubmit')
 
 def index(req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG,order="",doctype="",deletedId="",deletedAction="",deletedDoctype=""):
     global uid
     ln = wash_language(ln)
 
     # load the right message language
     _ = gettext_set_language(ln)
 
     t=""
     # get user ID:
     try:
         uid = getUid(req)
         if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
             return page_not_authorized(req, "../yourapprovals.py/index",
                                        navmenuid='yourapprovals')
         u_email = get_email(uid)
     except Error, e:
         return errorMsg(str(e), req, ln = ln)
 
-    res = run_sql("select sdocname,ldocname from sbmDOCTYPE")
+    res = run_sql("SELECT sdocname,ldocname FROM sbmDOCTYPE ORDER BY ldocname")
     referees = []
     for row in res:
         doctype = row[0]
         docname = row[1]
         reftext = ""
-        if isReferee(req,doctype,"*"):
+        if isReferee(req, doctype, "*"):
             referees.append ({'doctype': doctype,
                               'docname': docname,
                               'categories': None})
         else:
-            res2 = run_sql("select sname,lname from sbmCATEGORIES where doctype=%s",(doctype,))
+            res2 = run_sql("select sname,lname from sbmCATEGORIES where doctype=%s", (doctype,))
             categories = []
             for row2 in res2:
                 category = row2[0]
                 categname = row2[1]
-                if isReferee(req,doctype,category):
+                if isReferee(req, doctype, category):
                     categories.append({
                                         'id' : category,
                                         'name' : categname,
                                       })
-            referees.append({
+            if categories:
+                referees.append({
                             'doctype' : doctype,
                             'docname' : docname,
                             'categories' : categories
                            })
 
-
-    t = websubmit_templates.tmpl_yourapprovals(
-          ln = ln,
-          referees = referees
-        )
+    t = websubmit_templates.tmpl_yourapprovals(ln=ln, referees=referees)
     return page(title=_("Your Approvals"),
                 navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display">%(account)s</a>""" % {
                              'sitesecureurl' : CFG_SITE_SECURE_URL,
                              'account' : _("Your Account"),
                           },
                 body=t,
                 description="",
                 keywords="",
                 uid=uid,
                 language=ln,
                 req=req,
                 navmenuid='yourapprovals')
 
-def isReferee(req,doctype="",categ=""):
-    (auth_code, auth_message) = acc_authorize_action(req, "referee",verbose=0,doctype=doctype, categ=categ)
+def isReferee(req, doctype="", categ=""):
+    (auth_code, auth_message) = acc_authorize_action(req, "referee", verbose=0, doctype=doctype, categ=categ)
     if auth_code == 0:
         return 1
     else:
         return 0
 
 def errorMsg(title,req,c=CFG_SITE_NAME,ln=CFG_SITE_LANG):
     return page(title="error",
                 body = create_error_box(req, title=title,verbose=0, ln=ln),
                 description="%s - Internal Error" % c,
                 keywords="%s, Internal Error" % c,
                 language=ln,
                 req=req,
                 navmenuid='yourapprovals')