diff --git a/modules/bibindex/lib/bibindex_engine.py b/modules/bibindex/lib/bibindex_engine.py
index 95229aacf..8e61c2bce 100644
--- a/modules/bibindex/lib/bibindex_engine.py
+++ b/modules/bibindex/lib/bibindex_engine.py
@@ -1,1584 +1,1585 @@
# -*- coding: utf-8 -*-
##
## $Id$
## BibIndxes bibliographic data, reference and fulltext indexing utility.
##
## 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.
"""
BibIndex indexing engine implementation. See bibindex executable for entry point.
"""
__revision__ = "$Id$"
import os
import re
import sys
import time
import urllib2
import tempfile
import traceback
from invenio.config import \
CFG_BIBINDEX_CHARS_ALPHANUMERIC_SEPARATORS, \
CFG_BIBINDEX_CHARS_PUNCTUATION, \
CFG_BIBINDEX_FULLTEXT_INDEX_LOCAL_FILES_ONLY, \
CFG_BIBINDEX_MIN_WORD_LENGTH, \
CFG_BIBINDEX_REMOVE_HTML_MARKUP, \
CFG_BIBINDEX_REMOVE_LATEX_MARKUP, \
weburl, CFG_TMPDIR
from invenio.bibindex_engine_config import *
from invenio.bibdocfile import bibdocfile_url_to_fullpath, bibdocfile_url_p, decompose_bibdocfile_url
from invenio.search_engine import perform_request_search, strip_accents, wash_index_term, get_index_stemming_language
from invenio.dbquery import run_sql, DatabaseError, serialize_via_marshal, deserialize_via_marshal
from invenio.bibindex_engine_stopwords import is_stopword
from invenio.bibindex_engine_stemmer import stem
from invenio.bibtask import task_init, write_message, get_datetime, \
task_set_option, task_get_option, task_get_task_param, task_update_status, \
task_update_progress
from invenio.intbitset import intbitset
from invenio.errorlib import register_exception
## import optional modules:
try:
import psyco
psyco.bind(get_words_from_phrase)
psyco.bind(WordTable.merge_with_old_recIDs)
except:
pass
## precompile some often-used regexp for speed reasons:
re_subfields = re.compile('\$\$\w')
re_html = re.compile("(?s)<[^>]*>|?\w+;")
re_block_punctuation_begin = re.compile(r"^"+CFG_BIBINDEX_CHARS_PUNCTUATION+"+")
re_block_punctuation_end = re.compile(CFG_BIBINDEX_CHARS_PUNCTUATION+"+$")
re_punctuation = re.compile(CFG_BIBINDEX_CHARS_PUNCTUATION)
re_separators = re.compile(CFG_BIBINDEX_CHARS_ALPHANUMERIC_SEPARATORS)
re_datetime_shift = re.compile("([-\+]{0,1})([\d]+)([dhms])")
nb_char_in_line = 50 # for verbose pretty printing
chunksize = 1000 # default size of chunks that the records will be treated by
base_process_size = 4500 # process base size
_last_word_table = None
## Dictionary merging functions
def intersection(dict1, dict2):
"Returns intersection of the two dictionaries."
int_dict = {}
if len(dict1) > len(dict2):
for e in dict2:
if dict1.has_key(e):
int_dict[e] = 1
else:
for e in dict1:
if dict2.has_key(e):
int_dict[e] = 1
return int_dict
def union(dict1, dict2):
"Returns union of the two dictionaries."
union_dict = {}
for e in dict1.keys():
union_dict[e] = 1
for e in dict2.keys():
union_dict[e] = 1
return union_dict
def diff(dict1, dict2):
"Returns dict1 - dict2."
diff_dict = {}
for e in dict1.keys():
if not dict2.has_key(e):
diff_dict[e] = 1
return diff_dict
def list_union(list1, list2):
"Returns union of the two lists."
union_dict = {}
for e in list1:
union_dict[e] = 1
for e in list2:
union_dict[e] = 1
return union_dict.keys()
## safety function for killing slow DB threads:
def kill_sleepy_mysql_threads(max_threads=CFG_MAX_MYSQL_THREADS, thread_timeout=CFG_MYSQL_THREAD_TIMEOUT):
"""Check the number of DB threads and if there are more than
MAX_THREADS of them, lill all threads that are in a sleeping
state for more than THREAD_TIMEOUT seconds. (This is useful
for working around the the max_connection problem that appears
during indexation in some not-yet-understood cases.) If some
threads are to be killed, write info into the log file.
"""
res = run_sql("SHOW FULL PROCESSLIST")
if len(res) > max_threads:
for row in res:
r_id, dummy, dummy, dummy, r_command, r_time, dummy, dummy = row
if r_command == "Sleep" and int(r_time) > thread_timeout:
run_sql("KILL %s", (r_id,))
write_message("WARNING: too many DB threads, killing thread %s" % r_id, verbose=1)
return
## MARC-21 tag/field access functions
def get_fieldvalues(recID, tag):
"""Returns list of values of the MARC-21 'tag' fields for the record
'recID'."""
out = []
bibXXx = "bib" + tag[0] + tag[1] + "x"
bibrec_bibXXx = "bibrec_" + bibXXx
query = "SELECT value FROM %s AS b, %s AS bb WHERE bb.id_bibrec=%s AND bb.id_bibxxx=b.id AND tag LIKE '%s'" \
% (bibXXx, bibrec_bibXXx, recID, tag)
res = run_sql(query)
for row in res:
out.append(row[0])
return out
def get_associated_subfield_value(recID, tag, value, associated_subfield_code):
"""Return list of ASSOCIATED_SUBFIELD_CODE, if exists, for record
RECID and TAG of value VALUE. Used by fulltext indexer only.
Note: TAG must be 6 characters long (tag+ind1+ind2+sfcode),
otherwise en empty string is returned.
FIXME: what if many tag values have the same value but different
associated_subfield_code? Better use bibrecord library for this.
"""
out = ""
if len(tag) != 6:
return out
bibXXx = "bib" + tag[0] + tag[1] + "x"
bibrec_bibXXx = "bibrec_" + bibXXx
query = """SELECT bb.field_number, b.tag, b.value FROM %s AS b, %s AS bb
WHERE bb.id_bibrec=%s AND bb.id_bibxxx=b.id AND tag LIKE '%s%%'""" % \
(bibXXx, bibrec_bibXXx, recID, tag[:-1])
res = run_sql(query)
field_number = -1
for row in res:
if row[1] == tag and row[2] == value:
field_number = row[0]
if field_number > 0:
for row in res:
if row[0] == field_number and row[1] == tag[:-1] + associated_subfield_code:
out = row[2]
break
return out
def get_field_tags(field):
"""Returns a list of MARC tags for the field code 'field'.
Returns empty list in case of error.
Example: field='author', output=['100__%','700__%']."""
out = []
query = """SELECT t.value FROM tag AS t, field_tag AS ft, field AS f
WHERE f.code='%s' AND ft.id_field=f.id AND t.id=ft.id_tag
ORDER BY ft.score DESC""" % field
res = run_sql(query)
for row in res:
out.append(row[0])
return out
## Fulltext word extraction functions
def get_fulltext_urls_from_html_page(htmlpagebody):
"""Parses htmlpagebody data (the splash page content) looking for
url_directs referring to probable fulltexts.
Returns an array of (ext,url_direct) to fulltexts.
Note: it looks for file format extensions as defined by global
'CONV_PROGRAMS' structure, minus the HTML ones, because we don't
want to index HTML pages that the splash page might point to.
"""
out = []
for ext in CONV_PROGRAMS.keys():
expr = re.compile( r"\"(http://[\w]+\.+[\w]+[^\"'><]*\." + \
ext + r")\"")
match = expr.search(htmlpagebody)
if match and ext not in ['htm', 'html']:
out.append([ext, match.group(1)])
#else: # FIXME: workaround for getfile, should use bibdoc tables
#expr_getfile = re.compile(r"\"(http://.*getfile\.py\?.*format=" + ext + r"&version=.*)\"")
#match = expr_getfile.search(htmlpagebody)
#if match and ext not in ['htm', 'html']:
#out.append([ext, match.group(1)])
return out
-def get_words_from_local_fulltext(path, ext=''):
- # FIXME
+def get_words_from_local_fulltext(path, ext='', stemming_language=None):
+ # FIXME to be continued
+ raise NotImplemented
if not ext:
ext = path[len(file_strip_ext(path))+1:].lower()
tmp_name = path.replace(';', '\\;')
tmp_dst_name = tempfile.mkstemp('invenio.tmp.txt', dir=CFG_TMPDIR)[1]
# try all available conversion programs according to their order:
bingo = 0
for conv_program in CONV_PROGRAMS.get(ext, []):
if os.path.exists(conv_program):
# intelligence on how to run various conversion programs:
cmd = "" # wil keep command to run
bingo = 0 # had we success?
if os.path.basename(conv_program) == "pdftotext":
cmd = "%s -enc UTF-8 %s %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "pstotext":
if ext == "ps.gz":
# is there gzip available?
if os.path.exists(CONV_PROGRAMS_HELPERS["gz"]):
cmd = "%s -cd %s | %s > %s" \
% (CONV_PROGRAMS_HELPERS["gz"], tmp_name, conv_program, tmp_dst_name)
else:
cmd = "%s %s > %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "ps2ascii":
if ext == "ps.gz":
# is there gzip available?
if os.path.exists(CONV_PROGRAMS_HELPERS["gz"]):
cmd = "%s -cd %s | %s > %s"\
% (CONV_PROGRAMS_HELPERS["gz"], tmp_name,
conv_program, tmp_dst_name)
else:
cmd = "%s %s %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "antiword":
cmd = "%s %s > %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "catdoc":
cmd = "%s %s > %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "wvText":
cmd = "%s %s %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "ppthtml":
# is there html2text available?
if os.path.exists(CONV_PROGRAMS_HELPERS["html"]):
cmd = "%s %s | %s > %s"\
% (conv_program, tmp_name,
CONV_PROGRAMS_HELPERS["html"], tmp_dst_name)
else:
cmd = "%s %s > %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "xlhtml":
# is there html2text available?
if os.path.exists(CONV_PROGRAMS_HELPERS["html"]):
cmd = "%s %s | %s > %s" % \
(conv_program, tmp_name,
CONV_PROGRAMS_HELPERS["html"], tmp_dst_name)
else:
cmd = "%s %s > %s" % \
(conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "html2text":
cmd = "%s %s > %s" % \
(conv_program, tmp_name, tmp_dst_name)
else:
sys.stderr.write("Error: Do not know how to handle %s conversion program.\n" % conv_program)
# try to run it:
try:
write_message("..... launching %s" % cmd, verbose=9)
# Note we replace ; in order to make happy internal file names
errcode = os.system(cmd)
if errcode == 0 and os.path.exists(tmp_dst_name):
bingo = 1
break # bingo!
else:
write_message("Error while running %s for %s.\n" % (cmd, path), sys.stderr)
except:
write_message("Error running %s for %s.\n" % (cmd, path), sys.stderr)
# were we successful?
if bingo:
tmp_name_txt_file = open(tmp_dst_name)
for phrase in tmp_name_txt_file.xreadlines():
for word in get_words_from_phrase(phrase, stemming_language):
if not words.has_key(word):
words[word] = 1
tmp_name_txt_file.close()
else:
write_message("No conversion success for %s.\n" % (path), sys.stderr)
# delete temp files (they might not exist):
try:
os.unlink(tmp_dst_name)
except StandardError:
write_message("Error: Could not delete file. It didn't exist", sys.stderr)
write_message("... reading fulltext files from %s ended" % path, verbose=2)
return words.keys()
def get_words_from_fulltext(url_direct_or_indirect, stemming_language=None):
"""Returns all the words contained in the document specified by
URL_DIRECT_OR_INDIRECT with the words being split by various
SRE_SEPARATORS regexp set earlier. If FORCE_FILE_EXTENSION is
set (e.g. to "pdf", then treat URL_DIRECT_OR_INDIRECT as a PDF
file. (This is interesting to index Indico for example.) Note
also that URL_DIRECT_OR_INDIRECT may be either a direct URL to
the fulltext file or an URL to a setlink-like page body that
presents the links to be indexed. In the latter case the
URL_DIRECT_OR_INDIRECT is parsed to extract actual direct URLs
to fulltext documents, for all knows file extensions as
specified by global CONV_PROGRAMS config variable.
"""
if CFG_BIBINDEX_FULLTEXT_INDEX_LOCAL_FILES_ONLY and \
url_direct_or_indirect.find(weburl) < 0:
return []
write_message("... reading fulltext files from %s started" % url_direct_or_indirect, verbose=2)
fulltext_urls = []
if bibdocfile_url_p(url_direct_or_indirect):
write_message("... url %s is an internal url" % url_direct_or_indirect, verbose=9)
ext = decompose_bibdocfile_url(url_direct_or_indirect)[2]
if ext[0] == '.':
ext = ext[1:].lower()
fulltext_urls = [(ext, url_direct_or_indirect)]
else:
# check for direct link in url
url_direct_or_indirect_ext = url_direct_or_indirect.split(".")[-1].lower()
if url_direct_or_indirect_ext in CONV_PROGRAMS.keys():
fulltext_urls = [(url_direct_or_indirect_ext, url_direct_or_indirect)]
# Indirect URL. Try to discover the real fulltext(s) from this splash page URL.
if not fulltext_urls:
# read "setlink" data
try:
htmlpagebody = urllib2.urlopen(url_direct_or_indirect).read()
except Exception, e:
register_exception()
sys.stderr.write("Error: Cannot read %s: %s" % (url_direct_or_indirect, e))
return []
fulltext_urls = get_fulltext_urls_from_html_page(htmlpagebody)
write_message("... fulltext_urls = %s" % fulltext_urls, verbose=9)
write_message('... data to elaborate: %s' % fulltext_urls, verbose=9)
words = {}
# process as many urls as they were found:
for (ext, url_direct) in fulltext_urls:
write_message(".... processing %s from %s started" % (ext, url_direct), verbose=2)
# sanity check:
if not url_direct:
break
if bibdocfile_url_p(url_direct):
# Let's manage this with BibRecDocs...
# We got something like http://$(weburl)/record/xxx/yyy.ext
try:
tmp_name = bibdocfile_url_to_fullpath(url_direct)
write_message("Found internal path %s for url %s" % (tmp_name, url_direct), verbose=2)
no_src_delete = True
except Exception, e:
register_exception()
sys.stderr.write("Error in retrieving fulltext from internal url %s: %s\n" % (url_direct, e))
break # try other fulltext files...
else:
# read fulltext file:
try:
url = urllib2.urlopen(url_direct)
no_src_delete = False
except Exception, e:
register_exception()
sys.stderr.write("Error: Cannot read %s: %s\n" % (url_direct, e))
break # try other fulltext files...
tmp_fd, tmp_name = tempfile.mkstemp('invenio.tmp')
data_chunk = url.read(8*1024)
while data_chunk:
os.write(tmp_fd, data_chunk)
data_chunk = url.read(8*1024)
os.close(tmp_fd)
tmp_dst_name = tempfile.mkstemp('invenio.tmp.txt', dir=CFG_TMPDIR)[1]
bingo = 0
# try all available conversion programs according to their order:
for conv_program in CONV_PROGRAMS.get(ext, []):
if os.path.exists(conv_program):
# intelligence on how to run various conversion programs:
cmd = "" # will keep command to run
bingo = 0 # had we success?
if os.path.basename(conv_program) == "pdftotext":
cmd = "%s -enc UTF-8 %s %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "pstotext":
if ext == "ps.gz":
# is there gzip available?
if os.path.exists(CONV_PROGRAMS_HELPERS["gz"]):
cmd = "%s -cd %s | %s > %s" \
% (CONV_PROGRAMS_HELPERS["gz"], tmp_name, conv_program, tmp_dst_name)
else:
cmd = "%s %s > %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "ps2ascii":
if ext == "ps.gz":
# is there gzip available?
if os.path.exists(CONV_PROGRAMS_HELPERS["gz"]):
cmd = "%s -cd %s | %s > %s"\
% (CONV_PROGRAMS_HELPERS["gz"], tmp_name,
conv_program, tmp_dst_name)
else:
cmd = "%s %s %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "antiword":
cmd = "%s %s > %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "catdoc":
cmd = "%s %s > %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "wvText":
cmd = "%s %s %s" % (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "ppthtml":
# is there html2text available?
if os.path.exists(CONV_PROGRAMS_HELPERS["html"]):
cmd = "%s %s | %s > %s"\
% (conv_program, tmp_name,
CONV_PROGRAMS_HELPERS["html"], tmp_dst_name)
else:
cmd = "%s %s > %s" \
% (conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "xlhtml":
# is there html2text available?
if os.path.exists(CONV_PROGRAMS_HELPERS["html"]):
cmd = "%s %s | %s > %s" % \
(conv_program, tmp_name,
CONV_PROGRAMS_HELPERS["html"], tmp_dst_name)
else:
cmd = "%s %s > %s" % \
(conv_program, tmp_name, tmp_dst_name)
elif os.path.basename(conv_program) == "html2text":
cmd = "%s %s > %s" % \
(conv_program, tmp_name, tmp_dst_name)
else:
sys.stderr.write("Error: Do not know how to handle %s conversion program.\n" % conv_program)
# try to run it:
try:
write_message("..... launching %s" % cmd, verbose=9)
# Note we replace ; in order to make happy internal file names
errcode = os.system(cmd.replace(';', '\\;'))
if errcode == 0 and os.path.exists(tmp_dst_name):
bingo = 1
break # bingo!
else:
write_message("Error while running %s for %s.\n" % (cmd, url_direct), sys.stderr)
except:
write_message("Error running %s for %s.\n" % (cmd, url_direct), sys.stderr)
# were we successful?
if bingo:
tmp_name_txt_file = open(tmp_dst_name)
for phrase in tmp_name_txt_file.xreadlines():
for word in get_words_from_phrase(phrase, stemming_language):
if not words.has_key(word):
words[word] = 1
tmp_name_txt_file.close()
else:
write_message("No conversion success for %s.\n" % (url_direct), sys.stderr)
# delete temp files (they might not exist):
try:
if not no_src_delete:
os.unlink(tmp_name)
os.unlink(tmp_dst_name)
except StandardError:
write_message("Error: Could not delete file. It didn't exist", sys.stderr)
write_message(".... processing %s from %s ended" % (ext, url_direct), verbose=2)
write_message("... reading fulltext files from %s ended" % url_direct_or_indirect, verbose=2)
return words.keys()
latex_markup_re = re.compile(r"\\begin(\[.+?\])?\{.+?\}|\\end\{.+?}|\\\w+(\[.+?\])?\{(?P %s %s %s, %s (%s %s) %s confirm: user %s added to the editorial board. confirm: user %s removed from the editorial board. %s %s %s, %s (%s %s) user %s will be the referee ?
"
return t
def displayAddUser(doctype):
"""Display controls for adding users"""
t = ""
# start displaying the table which will contain the add form
t += """
"""
roles = acc_get_all_roles()
referees = {}
for role in roles:
role_name = role[1]
role_id = role[0]
if re.match("^referee_%s_" % doctype, role_name):
# Try to retrieve the referee's email from the referee's database
if acc_get_role_users(role_id) is not None:
referees[role_name] = acc_get_role_users(role_id)
if len(referees) == 0:
t += 'Referees
' % images
i = 0
for role in referees.keys():
categ = re.match("referee_%s_(.*)" % doctype, role).group(1)
res = run_sql("SELECT lname FROM sbmCATEGORIES WHERE sname=%s and doctype=%s", (categ, doctype,))
if len(res) > 0:
categname = "Referee(s) for category: %s" % res[0][0]
else:
categname = "General Referee(s)"
t += ' ' % categname
for referee in referees[role]:
if int(i/2) == i/2:
bgcolor = "#eeeeee"
else:
bgcolor = "#dddddd"
t += '%s ' % bgcolor
t += ' '
i += 1
# close table
t += "'
t += referee[1]
t += ' '
t += '''''' % (referee[0], role)
t += '' % images
t += ' '
t += '
'
return t
def errorMsg(title, req, uid, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
"""Prints the error page."""
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,
uid=uid,
req=req)
diff --git a/modules/websubmit/web/publiline.py b/modules/websubmit/web/publiline.py
index 8520a85b5..766297969 100644
--- a/modules/websubmit/web/publiline.py
+++ b/modules/websubmit/web/publiline.py
@@ -1,1592 +1,1592 @@
## $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, \
accessurl, \
CFG_SITE_ADMIN_EMAIL, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
images, \
CFG_PYLIBDIR, \
CFG_WEBSUBMIT_STORAGEDIR, \
supportemail, \
sweburl, \
urlpath, \
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, 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=""):
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')
# 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(e.value,req, ln = ln)
+ 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, 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, ln)
return page(title="specific publication line",
navtrail= """%(account)s""" % {
'sweburl' : sweburl,
'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="publication line",
navtrail= """%(account)s""" % {
'sweburl' : sweburl,
'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,
images = images,
)
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,
images = images,
)
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,
images = images,
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,
images = images,
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.") + "
Add
User:
"""
users = list_registered_users()
if len(users) < 20:
numrows = len(users)
else:
numrows = 20
t += '
'
t += '
'
t += ''''''
t += '
"
## 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":
(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,
images = images,
accessurl = accessurl,
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, 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.") + "
"
## 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,
images = images,
accessurl = accessurl,
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'])
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,
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, 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_RRP_RefereeSel_BASKET_DESCR = "Requests for refereeing process"
TEXT_RRP_RefereeSel_MSG_REFEREE_SUBJECT = "Referee selection"
TEXT_RRP_RefereeSel_MSG_REFEREE_BODY = "You have been named as a referee for this document :"
TEXT_RRP_RefereeSel_MSG_GROUP_SUBJECT = "Please, review this publication"
TEXT_RRP_RefereeSel_MSG_GROUP_BODY = "Please, review the following publication"
TEXT_RRP_RefereeRecom_MSG_PUBCOM_SUBJECT = "Final recommendation from the referee"
TEXT_RRP_PubComRecom_MSG_PRJLEADER_SUBJECT = "Final recommendation from the publication board"
TEXT_RRP_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.") + "
"
## 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.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
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, 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
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE %s ORDER BY email """, (email_user_pattern, ))
# users that are connected
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
ORDER BY u.email """, (id_EdBoardGroup, email_user_pattern))
# no users that match the pattern
if not (users1 or users2):
stopon1 = '
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
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)
referee_name = run_sql("""SELECT nickname FROM user WHERE id = %s """, (id_user_val, ))[0][0]
perform_request_send (uid, referee_name, "", TEXT_RefereeSel_MSG_REFEREE_SUBJECT, TEXT_RefereeSel_MSG_REFEREE_BODY)
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)
return displayCplxDocument(req, doctype,categ,RN,apptype, 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
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE %s ORDER BY email """, (email_user_pattern, ))
# no users that match the pattern
if not users1:
stopon1 = '
" % {'infos' : infos[0]}
t += """
""" % {'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.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
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 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)
group_addr = ""
TEXT_RefereeRecom_MSG_SUBJECT = TEXT_RRP_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 == "go":
if dRefereeRecom == None:
perform_request_send (uid, user_addr, group_addr, msg_subject, msg_body)
__db_set_RefereeRecom_time (key)
return displayCplxDocument(req, doctype,categ,RN,apptype, ln)
t = websubmit_templates.tmpl_publiline_displaycplxrecom (
ln = ln,
doctype = doctype,
categ = categ,
rn = RN,
apptype = apptype,
action = action,
status = status,
images = images,
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.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
# 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, ln)
t = websubmit_templates.tmpl_publiline_displaycplxrecom (
ln = ln,
doctype = doctype,
categ = categ,
rn = RN,
apptype = apptype,
action = action,
status = status,
images = images,
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.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
# 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 nickname 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 nickname FROM user WHERE id = %s """, (user[0], ))[0][0] + ","
user_addr = re.sub(",$","",user_addr)
if apptype == "RRP":
TEXT_PubComRecom_MSG_SUBJECT = TEXT_RRP_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 == "go":
if dPubComRecom == None:
perform_request_send (uid, user_addr, "", msg_subject, msg_body)
__db_set_PubComRecom_time (key)
return displayCplxDocument(req, doctype,categ,RN,apptype, ln)
t = websubmit_templates.tmpl_publiline_displaycplxrecom (
ln = ln,
doctype = doctype,
categ = categ,
rn = RN,
apptype = apptype,
action = action,
status = status,
images = images,
authors = authors,
title = title,
sysno = sysno,
msg_to = user_addr,
msg_to_group = "",
msg_subject = TEXT_PubComRecom_MSG_SUBJECT,
)
return t
elif (action == "ProjectLeaderDecision") and ((apptype == "RRP") or (apptype == "RPB")):
if __is_ProjectLeader (req, doctype, categ) != 0:
return _("Action unauthorized for this document.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
t += """
""" % {'doctype' : doctype,
'categ' : categ,
'rn' : RN,
'apptype' : apptype,
'button_label' : _("Come 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
" % {'infos' : infos[0]}
__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
" % {'infos' : infos[0]}
__db_set_status (key, 'rejected')
return out + t
validation = """
""" % {'select' : _('Select:'),
'approve' : _('Approve'),
'reject' : _('Reject'),
'button_label' : _('Take a decision'),
}
if apptype == "RRP":
TEXT_ProjectLeaderDecision_MSG_SUBJECT = TEXT_RRP_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.") + "
"
if status == "cancelled":
return _("Action unavailable for this document.") + "
"
if validate == "approve":
if dProjectLeaderAction == None:
__db_set_status (key, 'approved')
return displayCplxDocument(req, doctype,categ,RN,apptype, ln)
elif validate == "reject":
if dProjectLeaderAction == None:
__db_set_status (key, 'rejected')
return displayCplxDocument(req, doctype,categ,RN,apptype, ln)
t = """
""" % { 'rn' : RN, 'categ' : categ, 'doctype' : doctype, 'apptype' : apptype, 'action' : action, 'cancel' : _('Cancel'), } return t else: return _("Wrong action for this document.") + "