diff --git a/modules/websubmit/lib/Makefile.am b/modules/websubmit/lib/Makefile.am index 51585510b..b42d1ecef 100644 --- a/modules/websubmit/lib/Makefile.am +++ b/modules/websubmit/lib/Makefile.am @@ -1,28 +1,29 @@ ## $Id$ ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. SUBDIRS = functions pylibdir = $(libdir)/python/cdsware -pylib_DATA = websubmit_config.py websubmit_engine.py file.py +pylib_DATA = websubmit_config.py websubmit_engine.py file.py \ + websubmit_templates.py EXTRA_DIST = $(pylib_DATA) CLEANFILES = *~ *.tmp diff --git a/modules/websubmit/lib/file.py b/modules/websubmit/lib/file.py index 1d8242724..cd9ca15ed 100644 --- a/modules/websubmit/lib/file.py +++ b/modules/websubmit/lib/file.py @@ -1,519 +1,552 @@ ## $Id$ ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## import interesting modules: import string import os import sys import time import types import re import mimetypes import shutil import md5 import urllib from config import * from access_control_engine import acc_authorize_action from access_control_admin import acc_isRole from webpage import page, create_error_box from webuser import getUid, get_email from dbquery import run_sql from messages import * from mod_python import apache from websubmit_config import * +from messages import gettext_set_language + +import template +websubmit_templates = template.load('websubmit') + archivepath = filedir archivesize = filedirsize # sort compressed file extensions list to get lengthy ones first: cfg_compressed_file_extensions_sorted = cfg_compressed_file_extensions cfg_compressed_file_extensions_sorted.sort() class BibRecDocs: """this class represents all the files attached to one record""" def __init__(self,recid): self.id = recid self.bibdocs = [] self.buildBibDocList() - + def buildBibDocList(self): self.bibdocs = [] res = run_sql("select id_bibdoc,type from bibrec_bibdoc,bibdoc where id=id_bibdoc and id_bibrec=%s and status!='deleted'", (self.id,)) for row in res: self.bibdocs.append(BibDoc(bibdocid=row[0],recid=self.id)) - + def listBibDocs(self,type=""): tmp=[] for bibdoc in self.bibdocs: if type=="" or type == bibdoc.getType(): tmp.append(bibdoc) return tmp - + def getBibDocNames(self,type="Main"): names = [] for bibdoc in self.listBibDocs(type): names.append(bibdoc.getDocName()) return names - + def getBibDoc(self,bibdocid): for bibdoc in self.bibdocs: if bibdoc.getId() == bibdocid: return bibdoc return None - + def deleteBibDoc(self,bibdocid): for bibdoc in self.bibdocs: if bibdoc.getId() == bibdocid: bibdoc.delete() self.buildBibDocList() - + def addBibDoc(self,type="Main",docname="file"): while docname in self.getBibDocNames(type): match = re.match("(.*_)([^_]*)",docname) if match: try: docname = match.group(1)+str(int(match.group(2)) + 1) except: docname = docname + "_2" else: docname = docname + "_2" bibdoc = BibDoc(recid=self.id,type=type,docname=docname) if bibdoc != None: self.bibdocs.append(bibdoc) return bibdoc - + def addNewFile(self,fullpath,type="Main"): filename = re.sub("\..*","",re.sub(r".*[\\/:]", "", fullpath)) bibdoc = self.addBibDoc(type,filename) if bibdoc != None: bibdoc.addFilesNewVersion(files=[fullpath]) return bibdoc return None - + def addNewVersion(self,fullpath,bibdocid): bibdoc = self.getBibDoc(bibdocid) if bibdoc != None: bibdoc.addFilesNewVersion(files=[fullpath]) docname = re.sub("\..*","",re.sub(r".*[\\/:]", "", fullpath)) if docname != bibdoc.getDocName(): while docname in self.getBibDocNames(bibdoc.getType()): match = re.match("(.*_)([^_]*)",docname) if match: try: docname = match.group(1)+str(int(match.group(2)) + 1) except: docname = docname + "_2" else: docname = docname + "_2" bibdoc.changeName(docname) return bibdoc return None - + def addNewFormat(self,fullpath,bibdocid): bibdoc = self.getBibDoc(bibdocid) if bibdoc != None: bibdoc.addFilesNewFormat(files=[fullpath]) return bibdoc return None - + def listLatestFiles(self,type=""): docfiles = [] for bibdoc in self.listBibDocs(type): for docfile in bibdoc.listLatestFiles(): docfiles.append(docfile) return docfiles - + def checkFileExists(self,fullpath,type=""): if os.path.exists(fullpath): docfiles = self.listLatestFiles(type) for docfile in docfiles: if md5.new(readfile(fullpath)).digest() == md5.new(readfile(docfile.getPath())).digest(): return docfile.getBibDocId() else: return 0 - - def display(self,bibdocid="",version="",type=""): + + def display(self,bibdocid="",version="",type="", ln = cdslang): t="" bibdocs = [] if bibdocid!="": for bibdoc in self.bibdocs: if bibdoc.getId() == bibdocid: bibdocs.append(bibdoc) else: bibdocs = self.listBibDocs(type) if len(bibdocs) > 0: types = listTypesFromArray(bibdocs) + fulltypes = [] for mytype in types: - t+="%s file(s):" % mytype - t+="" + fulltype['content'].append(bibdoc.display(version, ln = ln)) + fulltypes.append(fulltype) + + t = websubmit_templates.tmpl_bibrecdoc_filelist( + ln = ln, + types = fulltypes, + ) return t class BibDoc: """this class represents one file attached to a record - there is a one to one mapping between an instance of this class and + there is a one to one mapping between an instance of this class and an entry in the bibdoc db table""" - + def __init__ (self,bibdocid="",recid="",docname="file",type="Main"): # bibdocid is known, the document already exists if bibdocid != "": if recid == "": res = run_sql("select id_bibrec,type from bibrec_bibdoc where id_bibdoc=%s",(bibdocid,)) if len(res) > 0: recid = res[0][0] self.type = res[0][1] else: recid = None self.type = "" else: res = run_sql("select type from bibrec_bibdoc where id_bibrec=%s and id_bibdoc=%s",(recid,bibdocid,)) self.type = res[0][0] # gather the other information res = run_sql("select * from bibdoc where id=%s", (bibdocid,)) self.cd = res[0][3] self.md = res[0][4] self.recid = recid self.docname = res[0][2] self.id = bibdocid group = "g"+str(int(int(self.id)/archivesize)) self.basedir = "%s/%s/%s" % (archivepath,group,self.id) # else it is a new document else: if docname == "" or type == "": return None else: self.recid = recid self.type = type self.docname = docname self.id = run_sql("insert into bibdoc (docname,creation_date,modification_date) values(%s,NOW(),NOW())", (docname,)) if self.id != None: #we link the document to the record if a recid was specified if self.recid != "": run_sql("insert into bibrec_bibdoc values(%s,%s,%s)", (recid,self.id,self.type,)) else: return None group = "g"+str(int(int(self.id)/archivesize)) self.basedir = "%s/%s/%s" % (archivepath,group,self.id) # we create the corresponding storage directory if not os.path.exists(self.basedir): os.makedirs(self.basedir) # and save the father record id if it exists if self.recid!="": fp = open("%s/.recid" % self.basedir,"w") fp.write(str(self.recid)) fp.close() # build list of attached files self.docfiles = {} self.BuildFileList() # link with relatedFiles self.relatedFiles = {} self.BuildRelatedFileList() - + def addFilesNewVersion(self,files=[]): """add a new version of a file to an archive""" latestVersion = self.getLatestVersion() if latestVersion == "0": myversion = "1" else: myversion = str(int(latestVersion)+1) for file in files: if os.path.exists(file): filename = re.sub(r".*[\\/:]", "", file) shutil.copy(file,"%s/%s;%s" % (self.basedir,filename,myversion)) self.BuildFileList() - + def addFilesNewFormat(self,files=[],version=""): """add a new format of a file to an archive""" if version == "": version = self.getLatestVersion() for file in files: if os.path.exists(file): filename = re.sub(r".*[\\/:]", "", file) shutil.copy(file,"%s/%s;%s" % (self.basedir,filename,version)) self.BuildFileList() - + def getIcon(self): if self.relatedFiles.has_key('Icon'): return self.relatedFiles['Icon'][0] else: return None - + def addIcon(self,file): """link an icon with the bibdoc object""" #first check if an icon already exists existingIcon = self.getIcon() if existingIcon != None: existingIcon.delete() #then add the new one filename = re.sub("\..*","",re.sub(r".*[\\/:]", "", file)) newicon = BibDoc(type='Icon',docname=filename) if newicon != None: newicon.addFilesNewVersion(files=[file]) run_sql("insert into bibdoc_bibdoc values(%s,%s,'Icon')", (self.id,newicon.getId(),)) if os.path.exists(newicon.getBaseDir()): fp = open("%s/.docid" % newicon.getBaseDir(),"w") fp.write(str(self.id)) fp.close() self.BuildRelatedFileList() - + def deleteIcon(self): existingIcon = self.getIcon() if existingIcon != None: existingIcon.delete() self.BuildRelatedFileList() - def display(self,version=""): + def display(self,version="", ln = cdslang): t="" if version == "all": docfiles = self.listAllFiles() elif version != "": docfiles = self.listVersionFiles(version) else: docfiles = self.listLatestFiles() existingIcon = self.getIcon() if existingIcon != None: imagepath = "%s/getfile.py?docid=%s&name=%s&format=gif" % (weburl,existingIcon.getId(),urllib.quote(existingIcon.getDocName())) else: imagepath = "%s/smallfiles.gif" % images - t+="" % (imagepath,self.docname) + + versions = [] for version in listVersionsFromArray(docfiles): + currversion = { + 'version' : version, + 'previous' : 0, + 'content' : [] + } if version == self.getLatestVersion() and version != "1": - versiontext = "
(see previous)" % (weburl,self.id) - else: - versiontext = "" - t+="" - t+="
  %s
version %s%s" % (version,versiontext) - t+="" + currversion['previous'] = 1 for docfile in docfiles: if docfile.getVersion() == version: - t +=docfile.display() - t+="
" + currversion['content'].append(docfile.display(ln = ln)) + versions.append(currversion) + + t = websubmit_templates.tmpl_bibdoc_filelist( + ln = ln, + weburl = weburl, + versions = versions, + imagepath = imagepath, + docname = self.docname, + id = self.id, + ) return t - + def changeName(self,newname): run_sql("update bibdoc set docname=%s where id=%s",(newname,self.id,)) self.docname = newname - + def getDocName(self): """retrieve bibdoc name""" return self.docname - + def getBaseDir(self): """retrieve bibdoc base directory""" return self.basedir - + def getType(self): """retrieve bibdoc type""" return self.type - + def getRecid(self): """retrieve bibdoc recid""" return self.recid - + def getId(self): """retrieve bibdoc id""" return self.id - + def getFile(self,name,format,version): if version == "": docfiles = self.listLatestFiles() else: docfiles = self.listVersionFiles(version) for docfile in docfiles: if docfile.getName()==name and docfile.getFormat()==format: return docfile return None def listVersions(self): versions = [] for docfile in self.docfiles: if not docfile.getVersion() in versions: versions.append(docfile.getVersion()) return versions - + def delete(self): """delete the current bibdoc instance""" run_sql("update bibdoc set status='deleted' where id=%s",(self.id,)) - + def BuildFileList(self): """lists all files attached to the bibdoc""" self.docfiles = [] if os.path.exists(self.basedir): for fil in os.listdir(self.basedir): if fil != ".recid" and fil != ".docid" and fil != "." and fil != "..": filepath = "%s/%s" % (self.basedir,fil) fileversion = re.sub(".*;","",fil) fullname = fil.replace(";%s" % fileversion,"") # detect fullname's basename and extension: fullname_lowercase = fullname.lower() fullname_extension_postition = -1 # first try to detect compressed file extensions: for compressed_file_extension in cfg_compressed_file_extensions_sorted: if fullname_lowercase.endswith("." + compressed_file_extension): fullname_extension_postition = fullname[:-len(compressed_file_extension)-1].rfind(".") break if fullname_extension_postition == -1: # okay, no compressed extension found, so try to find last dot: fullname_extension_postition = fullname.rfind(".") # okay, fullname_extension_postition should now indicate where extension starts (incl. compressed ones) if fullname_extension_postition == -1: fullname_basename = fullname fullname_extension = "" else: fullname_basename = fullname[:fullname_extension_postition] fullname_extension = fullname[fullname_extension_postition+1:] # we can append file: self.docfiles.append(BibDocFile(filepath,self.type,fileversion,fullname_basename,fullname_extension,self.id)) - + def BuildRelatedFileList(self): res = run_sql("select ln.id_bibdoc2,ln.type from bibdoc_bibdoc as ln,bibdoc where id=ln.id_bibdoc2 and ln.id_bibdoc1=%s and status!='deleted'",(self.id,)) for row in res: bibdocid = row[0] type = row[1] if not self.relatedFiles.has_key(type): self.relatedFiles[type] = [] self.relatedFiles[type].append(BibDoc(bibdocid=bibdocid)) - + def listAllFiles(self): return self.docfiles - + def listLatestFiles(self): return self.listVersionFiles(self.getLatestVersion()) def listVersionFiles(self,version): tmp = [] for docfile in self.docfiles: if docfile.getVersion() == version: tmp.append(docfile) return tmp - + def getLatestVersion(self): if len(self.docfiles) > 0: self.docfiles.sort(orderFilesWithVersion) return self.docfiles[0].getVersion() else: return 0 def getFileNumber(self): return len(self.files) def registerDownload(self,addressIp,version,format,userid=0): return run_sql("INSERT INTO rnkDOWNLOADS (id_bibrec,id_bibdoc,file_version,file_format,id_user,client_host,download_time) VALUES (%s,%s,%s,%s,%s,INET_ATON(%s),NOW())", (self.recid,self.id,version,string.upper(format),userid,addressIp,)) + class BibDocFile: """this class represents a physical file in the CDSware filesystem""" - + def __init__(self,fullpath,type,version,name,format,bibdocid): self.fullpath = fullpath self.type = type self.bibdocid = bibdocid self.version = version self.size = os.path.getsize(fullpath) self.md = os.path.getmtime(fullpath) - try: + try: self.cd = os.path.getctime(fullpath) - except: - self.cd = self.md + except: + self.cd = self.md self.name = name self.format = format self.dir = os.path.dirname(fullpath) if format == "": self.mime = "text/plain" self.encoding = "" self.fullname = name else: self.fullname = "%s.%s" % (name,format) (self.mime,self.encoding) = mimetypes.guess_type(self.fullname) if self.mime == None: - self.mime = "text/plain" - - def display(self): + self.mime = "text/plain" + + def display(self, ln = cdslang): if self.format != "": format = ".%s" % self.format else: format = "" - return "%s%s[%s B]\n""" % (weburl,self.bibdocid,urllib.quote(self.name),urllib.quote(self.format),self.version,self.name,format,self.size) - + return websubmit_templates.tmpl_bibdocfile_filelist( + ln = ln, + weburl = weburl, + id = self.bibdocid, + selfformat = self.format, + version = self.version, + name = self.name, + format = format, + size = self.size, + ) + def getType(self): return self.type - + def getPath(self): return self.fullpath - + def getBibDocId(self): return self.bibdocid - + def getName(self): return self.name - + def getFormat(self): return self.format - + def getSize(self): return self.size - + def getVersion(self): return self.version - + def getRecid(self): return run_sql("select id_bibrec from bibrec_bibdoc where id_bibdoc=%s",(self.bibdocid,))[0][0] - + def stream(self,req): if os.path.exists(self.fullpath): req.content_type = self.mime req.encoding = self.encoding req.filename = self.fullname req.headers_out["Content-Disposition"] = "file; filename=%s" % self.fullname req.send_http_header() fp = file(self.fullpath,"r") content = fp.read() fp.close() return content - + def readfile(path): if os.path.exists(path): fp = open(path,"r") content = fp.read() fp.close() return content def listTypesFromArray(bibdocs): types = [] for bibdoc in bibdocs: if not bibdoc.getType() in types: types.append(bibdoc.getType()) return types - + def listVersionsFromArray(docfiles): versions = [] for docfile in docfiles: if not docfile.getVersion() in versions: versions.append(docfile.getVersion()) return versions - + def orderFilesWithVersion(docfile1,docfile2): """order docfile objects according to their version""" version1 = int(docfile1.getVersion()) version2 = int(docfile2.getVersion()) return cmp(version2,version1) diff --git a/modules/websubmit/lib/websubmit_engine.py b/modules/websubmit/lib/websubmit_engine.py index 57b1bc2ce..ea5de19c9 100644 --- a/modules/websubmit/lib/websubmit_engine.py +++ b/modules/websubmit/lib/websubmit_engine.py @@ -1,1338 +1,1157 @@ ## $Id$ -## CDSware WebSubmit in mod_python. ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. -"""CDSware Submission Web Interface.""" - ## import interesting modules: import string import os import sys import time import types import re import MySQLdb import shutil from config import * from dbquery import run_sql from access_control_engine import acc_authorize_action from access_control_admin import acc_isRole from webpage import page, create_error_box from webuser import getUid, get_email from messages import * from mod_python import apache from websubmit_config import * from file import * +from messages import gettext_set_language + +import template +websubmit_templates = template.load('websubmit') + def interface(req,c=cdsname,ln=cdslang, doctype="", act="", startPg=1, indir="", access="",mainmenu="",fromdir="",file="",nextPg="",nbPg="",curpage=1): ln = wash_language(ln) + + # load the right message language + _ = gettext_set_language(ln) + sys.stdout = req # get user ID: try: uid = getUid(req) uid_email = get_email(uid) except MySQLdb.Error, e: - return errorMsg(e.value,req) + return errorMsg(e.value,req, c, ln) # 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": - warningMsg("
Sorry, you must log in to perform this action. Please use the top right menu to do so.
",req) + return warningMsg(websubmit_templates.tmpl_warning_message( + ln = ln, + msg = _("Sorry, you must log in to perform this action. Please use the top right menu to do so.") + ), req, ln) + # warningMsg("""
""",req, ln) # check we have minimum fields if doctype=="" or act=="" or access=="": - return errorMsg("invalid parameter",req) + return errorMsg(_("invalid parameter"),req, c, ln) # retrieve the action and doctype data if indir == "": res = run_sql("select dir from sbmACTION where sactname=%s",(act,)) if len(res) == 0: - return errorMsg("cannot find submission directory",req) + return errorMsg(_("cannot find submission directory"),req, c, ln) else: row = res[0] indir = row[0] res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s",(doctype,)) if len(res) == 0: - return errorMsg("unknown document type",req) + return errorMsg(_("unknown document type"),req, c, ln) else: docname = res[0][0] docname = string.replace(docname," "," ") res = run_sql("SELECT lactname FROM sbmACTION WHERE sactname=%s",(act,)) if len(res) == 0: - return errorMsg("unknown action",req) + return errorMsg(_("unknown action"),req, c, ln) else: actname = res[0][0] actname = string.replace(actname," "," ") subname = "%s%s" % (act,doctype) res = run_sql("SELECT nbpg FROM sbmIMPLEMENT WHERE subname=%s", (subname,)) if len(res) == 0: - return errorMsg("can't figure number of pages",req) + return errorMsg(_("can't figure number of pages"),req, c, ln) else: nbpages = res[0][0] #Get current page if startPg != "" and (curpage=="" or curpage==0): curpage = startPg # retrieve the name of the file in which the reference of # the submitted document will be stored res = run_sql("SELECT value FROM sbmPARAMETERS WHERE doctype=%s and name='edsrn'", (doctype,)) if len(res) == 0: edsrn = "" else: edsrn = res[0][0] # This defines the path to the directory containing the action data curdir = "%s/%s/%s/%s" % (storage,indir,doctype,access) # 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 = "%s/%s/%s/%s" % (storage,fromdir,doctype,access) 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: - return errorMsg("can't create submission directory",req) + return errorMsg(_("can't create submission directory"),req, c, ln) # retrieve the original main menu url ans save it in the "mainmenu" file if mainmenu != "": fp = open("%s/mainmenu" % curdir,"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("%s/mainmenu" % curdir): fp = open("%s/mainmenu" % curdir,"r"); mainmenu = fp.read() fp.close() else: mainmenu = "%s/submit.py" %urlpath # 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("%s/SuE" % curdir,"w") fp.write(uid_email) fp.close() # is user authorized to perform this action? (auth_code, auth_message) = acc_authorize_action(uid, "submit",verbose=0,doctype=doctype, act=act) if acc_isRole("submit",doctype=doctype,act=act) and auth_code != 0: return warningMsg("
%s
" % auth_message, req) - # then we update the "journal of submission" + # then we update the "journal of submission" res = run_sql("SELECT * FROM sbmSUBMISSIONS WHERE doctype=%s and action=%s and id=%s and email=%s", (doctype,act,access,uid_email,)) if len(res) == 0: run_sql("INSERT INTO sbmSUBMISSIONS values (%s,%s,%s,'pending',%s,'',NOW(),NOW())", (uid_email,doctype,act,access,)) else: run_sql("UPDATE sbmSUBMISSIONS SET md=NOW() WHERE doctype=%s and action=%s and id=%s and email=%s", (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 in form.keys(): formfields = form[key] if re.search("\[\]",key): filename = key.replace("[]","") else: filename = key # the field is an array if isinstance(formfields,types.ListType): fp = open("%s/%s" % (curdir,filename),"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("%s/%s" % (curdir,filename),"w") fp.write(specialchars(value)) fp.close() # the field is a file elif hasattr(formfields,"filename"): if not os.path.exists("%s/files/%s" % (curdir,key)): try: os.makedirs("%s/files/%s" % (curdir,key)) except: - return errorMsg("can't create submission directory",req) + return errorMsg(_("can't create submission directory"),req, c, ln) filename = formfields.filename if filename != "": # This may be dangerous if the file size is bigger than the available memory data = formfields.file.read() fp = open("%s/files/%s/%s" % (curdir,key,filename),"w") fp.write(data) fp.close() fp = open("%s/lastuploadedfile" % curdir,"w") fp.write(filename) fp.close() fp = open("%s/%s" % (curdir,key),"w") fp.write(filename) fp.close() # 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: run_sql("UPDATE sbmSUBMISSIONS SET reference=%s WHERE doctype=%s and id=%s and email=%s", (value,doctype,access,uid_email,)) # Now deal with the cookies # If the fields must be saved as a cookie, we do so # In this case, the value of the field will be retrieved and # displayed as the default value of the field next time the user # does a submission if value!="": res = run_sql("SELECT cookie FROM sbmFIELDDESC WHERE name=%s", (key,)) if len(res) > 0: if res[0][0] == 1: setCookie(key,value,uid) + # create interface - # top menu - t=t+"
" - t=t+"
" - t=t+" " % docname - t=t+" " % actname - t=t+""" - \n" - t=t+"\n" % (doctype,act,access,indir) - t=t+"" - # main cell - t=t+"\n" - # Display the navigation cell - # Display "previous page" navigation arrows - t=t+"
%s  %s  - - """ - for i in range(1,nbpages+1): - if i == int(curpage): - t=t+"" % curpage - else: - t=t+"" % (i,i) - t=t+"
   page:%s  %s   
 SUMMARY(2) 

" - # display the static form fields - t=t+"\n" % file - t=t+"\n" % nextPg - t=t+"\n" % access - t=t+"\n" % curpage - t=t+"\n" % nbPg - t = t +"\n" % doctype - t=t+"\n" % act - t=t+"\n" % indir - t=t+"\n" - t=t+"\n" # For each field to be displayed on the page subname = "%s%s" % (act,doctype) res = run_sql("SELECT * FROM sbmFIELD WHERE subname=%s and pagenb=%s ORDER BY fieldnb,fieldnb", (subname,curpage,)) - nbFields = 0 + + full_fields = [] + values = [] for arr in res: + full_field = {} # We retrieve its HTML description res3 = run_sql("SELECT * FROM sbmFIELDDESC WHERE name=%s", (arr[3],)) arr3 = res3[0] if arr3[8]==None: val="" else: val=arr3[8] # we also retrieve and add the javascript code of the checking function, if needed + full_field['javascript'] = '' if arr[7] != '': res2 = run_sql("SELECT chdesc FROM sbmCHECKS WHERE chname=%s", (arr[7],)) - t=t+"\n" - # If the field is a textarea - if arr3[3] == 'T': - text="" % (arr[3],arr3[5],arr3[6],val) - # If the field is a file upload - elif arr3[3] == 'F': - text="" % (arr[3],arr3[4],arr3[7]); - # If the field is a text input - elif arr3[3] == 'I': - text="" % (arr[3],arr3[4],val) - # If the field is a hidden input - elif arr3[3] == 'H': - text="" % (arr[3],val) - # If the field is user-defined - elif arr3[3] == 'D': - text=arr3[9] - # If the field is a select box - elif arr3[3] == 'S': - text=arr3[9] - # If the field is an evaluated script - # the execed code should set variable text - elif arr3[3] == 'R': - co = compile(arr3[9].replace("\r\n","\n"),"","exec") + full_field['javascript'] = res2[0][0] + full_field['type'] = arr3[3] + full_field['name'] = arr[3] + full_field['rows'] = arr3[5] + full_field['cols'] = arr3[6] + full_field['val'] = val + full_field['size'] = arr3[4] + full_field['maxlength'] = arr3[7] + full_field['htmlcode'] = arr3[9] + full_field['typename'] = arr[1] + + # 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"),"","exec") exec(co) - # If the field type is not recognized else: - text="%s: unknown field type" % arr[1] + text = websubmit_templates.tmpl_submit_field (ln = ln, field = full_field) + # we now determine the exact type of the created field - if arr3[3] not in [ 'D','R']: - field.append(arr[3]) + if full_field['type'] not in [ 'D','R']: + field.append(full_field['name']) level.append(arr[5]) fullDesc.append(arr[4]) txt.append(arr[6]) check.append(arr[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) != None: select.append(1) else: select.append(0) # checks whether it is a radio field or not - if re.search("TYPE=radio",text,re.IGNORECASE) != None: + if re.search(r"TYPE=[\"']?radio",text,re.IGNORECASE) != None: radio.append(1) else: radio.append(0) # checks whether it is a file upload or not - if re.search("TYPE=file",text,re.IGNORECASE) != None: + if re.search(r"TYPE=[\"']?file",text,re.IGNORECASE) != None: upload.append(1) else: upload.append(0) # if the field description contains the "" 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) # if there is a tag in it, replace it by the current year year = time.strftime("%Y"); text = text.replace("",year) fieldhtml.append(text) - # increment the fields counter - nbFields = nbFields + 1 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(arr[3]) level.append(arr[5]) txt.append(arr[6]) fullDesc.append(arr[4]) check.append(arr[7]) fieldhtml.append(text) - nbFields = nbFields+1 - # now displays the html form field(s) - t+="%s\n" % fullDesc[nbFields-1] - t+=text+"\n" - # if there is a file upload field, we change the encoding type - t=t+"
 
 
\n" - if int(curpage) != 1: - t=t+" \n" - else: - t=t+" \n" - # Display the submission number - t=t+" \n" % access - # Display the "next page" navigation arrow - if int(curpage) != int(nbpages): - t=t+" \n" - t=t+"
 \n" - t=t+" " % (int(curpage)-1) - t=t+" \"previous\n" % images - t=t+" previous page Submission no(1): %s\n" - t=t+" \n" % (int(curpage)+1) - t=t+" next page\n" - t=t+" \"next " % images - else: - t=t+"  
" - - # # # # # # # # # # # # # # # # # # # # # # # # # - # Fill the fields with the previously saved values - # # # # # # # # # # # # # # # # # # # # # # # # # - t=t+" -
-
""" - # Display the "back to main menu" button - t=t+"\n" % mainmenu - t=t+"\"back

\n" % images - t=t+""" -
- (1) you should take note of this number at the beginning of the submission, it will allow you to get your information back in case your browser crashes before the end of the submission.
""" - # Add the summary window definition if needed - t=t+" (2) mandatory fields appear in red in the 'Summary' window.
\n" + 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, + images = images, + returnto = returnto, + ), + images = images, + mainmenu = mainmenu, + ) + # start display: req.content_type = "text/html" req.send_http_header() - p_navtrail = "Submit > %s > %s" % (doctype,docname,actname) - return page(title="" , - body=t, - navtrail = p_navtrail, - description="", - keywords="", - uid=uid, - language=ln, - urlargs=req.args) + p_navtrail = """%(submit)s > %(docname)s """ % { + 'submit' : _("Submit"), + 'doctype' : doctype, + 'docname' : docname, + } + return page(title= actname, + body = t, + navtrail = p_navtrail, + description = "submit documents in CDSWare", + keywords = "submit, CDSWare", + uid = uid, + language = ln, + urlargs = req.args) def endaction(req,c=cdsname,ln=cdslang, doctype="", act="", startPg=1, indir="", access="",mainmenu="",fromdir="",file="",nextPg="",nbPg="",curpage=1,step=1,mode="U"): - global rn,sysno,dismode,curdir,uid,uid_email,lats_step,action_score + 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: try: uid = getUid(req) uid_email = get_email(uid) except MySQLdb.Error, e: - return errorMsg(e.value) + return errorMsg(e.value, req, c, ln) # Preliminary tasks # check that the user is logged in if uid_email == "" or uid_email == "guest": - return warningMsg("
Sorry, you must log in to perform this action. Please use the top right menu to do so.
",req,cdsname,ln) + return warningMsg(websubmit_templates.tmpl_warning_message( + ln = ln, + msg = _("Sorry, you must log in to perform this action. Please use the top right menu to do so.") + ), req, ln) # check we have minimum fields if doctype=="" or act=="" or access=="": - return errorMsg("invalid parameter",req,cdsname,ln) + return errorMsg(_("invalid parameter"),req, c, ln) # retrieve the action and doctype data if indir == "": res = run_sql("select dir from sbmACTION where sactname=%s", (act,)) if len(res) == 0: - return errorMsg("cannot find submission directory",req,cdsname,ln) + return errorMsg(_("cannot find submission directory"),req, c, ln) else: row = res[0] indir = row[0] # 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 = "%s/%s/%s/%s" % (storage,indir,doctype,access) # If the submission directory still does not exist, we create it if not os.path.exists(curdir): try: os.makedirs(curdir) except: - return errorMsg("can't create submission directory",req,cdsname,ln) + return errorMsg(_("can't create submission directory"),req, c, ln) # retrieve the original main menu url ans save it in the "mainmenu" file if mainmenu != "": fp = open("%s/mainmenu" % curdir,"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("%s/mainmenu" % curdir): fp = open("%s/mainmenu" % curdir,"r"); mainmenu = fp.read() fp.close() else: mainmenu = "%s/submit.py" % urlpath # retrieve the name of the file in which the reference of # the submitted document will be stored res = run_sql("SELECT value FROM sbmPARAMETERS WHERE doctype=%s and name='edsrn'",(doctype,)) if len(res) == 0: edsrn = "" else: edsrn = res[0][0] # Now we test whether the user has already completed the action and # reloaded the page (in this case we don't want the functions to be called # once again - reloaded = Test_Reload(uid_email,doctype,act,access) + # reloaded = Test_Reload(uid_email,doctype,act,access) # if the action has been completed #if reloaded: # return warningMsg(" Sorry, this action has already been completed. Please go back to the main menu to start a new action.",req) # We must determine if the action is finished (ie there is no other steps after the current one res = run_sql("SELECT step FROM sbmFUNCTIONS WHERE action=%s and doctype=%s and step > %s", (act,doctype,step,)) if len(res) == 0: finished = 1 else: finished = 0 # 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] if re.search("\[\]",key): filename = key.replace("[]","") else: filename = key # the field is an array if isinstance(formfields,types.ListType): fp = open("%s/%s" % (curdir,filename),"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("%s/%s" % (curdir,filename),"w") fp.write(specialchars(value)) fp.close() # the field is a file elif hasattr(formfields,"filename"): if not os.path.exists("%s/files/%s" % (curdir,key)): try: os.makedirs("%s/files/%s" % (curdir,key)) except: return errorMsg("can't create submission directory",req,cdsname,ln) filename = formfields.filename if filename != "": # This may be dangerous if the file size is bigger than the available memory data = formfields.file.read() fp = open("%s/files/%s/%s" % (curdir,key,filename),"w") fp.write(data) fp.close() fp = open("%s/lastuploadedfile" % curdir,"w") fp.write(filename) fp.close() fp = open("%s/%s" % (curdir,key),"w") fp.write(filename) fp.close() # 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: run_sql("UPDATE sbmSUBMISSIONS SET reference=%s WHERE doctype=%s and id=%s and email=%s", (value,doctype,access,uid_email,)) # Now deal with the cookies # If the fields must be saved as a cookie, we do so # In this case, the value of the field will be retrieved and # displayed as the default value of the field next time the user # does a submission if value!="": res = run_sql("SELECT cookie FROM sbmFIELDDESC WHERE name=%s", (key,)) if len(res) > 0: if res[0][0] == 1: setCookie(key,value,uid) - # those fields are necessary for the navigation - t=t+"
\n" - t=t+"\n" % file - t=t+"\n" % nextPg - t=t+"\n" % startPg - t=t+"\n" % access - t=t+"\n" % curpage - t=t+"\n" % nbPg - t=t+"\n" % doctype - t=t+"\n" %act - t=t+"\n" % indir - t=t+"\n" - t=t+"\n" % mainmenu - # parameters for new MESS end scripts - t=t+"\n" - t=t+"\n" - t=t+"\n" - t=t+"\n" - t=t+"\n" + # Get document name res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,)) if len(res) > 0: docname = res[0][0] else: - return errorMsg("unknown type of document",req,cdsname,ln) + return errorMsg(_("unknown type of document"),req,cdsname,ln) # Get action name res = run_sql("SELECT lactname FROM sbmACTION WHERE sactname=%s", (act,)) if len(res) > 0: actname = res[0][0] else: - return errorMsg("unknown action",req,cdsname,ln) + return errorMsg(_("unknown action"),req,cdsname,ln) # Get number of pages subname = "%s%s" % (act,doctype) res = run_sql("SELECT nbpg FROM sbmIMPLEMENT WHERE subname=%s",(subname,)) if len(res) > 0: nbpages = res[0][0] else: - return errorMsg("this action does not apply on this type of document",req,cdsname,ln) - # Display table header - t=t+"
" - t=t+" " % docname - t=t+" " % actname - t=t+""" - \n" - t=t+"\n" - else: - for i in range(1,nbpages+1): - t=t+"" % (i,i) - t=t+"
%s  %s  - - """ - if finished == 1: - t=t+"
  finished!  
  %s end of action  
\n" - t=t+" SUMMARY(2) \n" % (doctype,act,access,indir) - t=t+"\n" - # Display main cell - t=t+"\n" - t=t+" \n" - t=t+"

\n" + return errorMsg(_("this action does not apply on this type of document"),req,cdsname,ln) + # we specify here whether we are in the last step of the action or not res = run_sql("SELECT step FROM sbmFUNCTIONS WHERE action=%s and doctype=%s and step>%s", (act,doctype,step,)) if len(res) == 0: last_step = 1 else: last_step = 0 + # 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: - t=t+print_function_calls(doctype, act, step, form) + function_content = print_function_calls(doctype, act, step, form) except functionError,e: - return errorMsg(e.value,req) + return errorMsg(e.value,req, c, ln) except functionStop,e: if e.value != None: - t=t+e.value + function_content = e.value else: - t=t+e + function_content = e + # If the action was mandatory we propose the next mandatory action (if any) + next_action = '' if action_score != -1 and last_step == 1: - t=t+Propose_Next_Action(doctype,action_score,access,current_level,indir) + 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 != "": res = run_sql("SELECT * FROM sbmSUBMISSIONS WHERE doctype=%s and action=%s and id=%s and email=%s", (doctype,act,access,uid_email,)) if len(res) == 0: run_sql("INSERT INTO sbmSUBMISSIONS values(%s,%s,%s,'finished',%s,%s,NOW(),NOW())", (uid_email,doctype,act,access,rn,)) else: run_sql("UPDATE sbmSUBMISSIONS SET md=NOW(),reference=%s,status='finished' WHERE doctype=%s and action=%s and id=%s and email=%s", (rn,doctype,act,access,uid_email,)) - t=t+"""

- - - - """ - if finished == 0: - t=t+"Submission no²:\n" - t=t+"%s\n" % access - else: - t=t+" \n" - t=t+""" - - - -
- -
-
""" - # Add the "back to main menu" button - if finished == 0: - t=t+ " \n" % mainmenu - else: - t=t+" \n" % mainmenu - t=t+"\"back

\n" % images + + t = websubmit_templates.tmpl_page_endaction( + ln = ln, + weburl = weburl, + # 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, + images = images, + function_content = function_content, + next_action = next_action, + ) # start display: req.content_type = "text/html" req.send_http_header() - p_navtrail = "Submit > %s > %s" % (doctype,docname,actname) - return page(title="", - body=t, - navtrail = p_navtrail, - description="", - keywords="", - uid=uid, - language=ln, - urlargs=req.args) + p_navtrail = """""" + _("Submit") +\ + """ > %(docname)s""" % { + 'doctype' : doctype, + 'docname' : docname, + } + return page(title= actname, + body = t, + navtrail = p_navtrail, + description="submit documents in CDSWare", + keywords="submit, CDSWare", + uid = uid, + language = ln, + urlargs = req.args) def simpleendaction(doctype="", act="", startPg=1, indir="", access="",step=1,mode="U"): global rn,sysno,dismode,curdir,uid,uid_email,lats_step,action_score dismode = mode # check we have minimum fields if doctype=="" or act=="" or access=="": return "invalid parameter" # retrieve the action and doctype data if indir == "": res = run_sql("select dir from sbmACTION where sactname=%s", (act,)) if len(res) == 0: return "cannot find submission directory" else: row = res[0] indir = row[0] # This defines the path to the directory containing the action data curdir = "%s/%s/%s/%s" % (storage,indir,doctype,access) # If the submission directory still does not exist, we create it if not os.path.exists(curdir): return "submission directory %s does not exist" % curdir # retrieve the name of the file in which the reference of # the submitted document will be stored res = run_sql("SELECT value FROM sbmPARAMETERS WHERE doctype=%s and name='edsrn'",(doctype,)) if len(res) == 0: edsrn = "" else: edsrn = res[0][0] # Get document name res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,)) if len(res) > 0: docname = res[0][0] else: return "unknown type of document %s" % doctype # Get action name res = run_sql("SELECT lactname FROM sbmACTION WHERE sactname=%s", (act,)) if len(res) > 0: actname = res[0][0] else: return "unknown action %s" % act # 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 print_function_calls(doctype, act, step, "") return "ok" def home(req,c=cdsname,ln=cdslang): ln = wash_language(ln) # get user ID: try: uid = getUid(req) except MySQLdb.Error, e: return errorMsg(e.value) # start display: req.content_type = "text/html" req.send_http_header() - finaltext = "" - finaltext = finaltext + """ - - - - - - - - -""" - p_navtrail = "Submit" - return page(title="", - body=finaltext, - navtrail=p_navtrail, - description="toto", - keywords="keywords", - uid=uid, - language=ln, - urlargs=req.args - ) - -def makeCataloguesTable(): + + # 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 in CDSWare", + keywords="submit, CDSWare", + uid=uid, + language=ln, + urlargs=req.args + ) + +def makeCataloguesTable(ln): text = "" catalogues = [] queryResult = run_sql("SELECT id_son FROM sbmCOLLECTION_sbmCOLLECTION WHERE id_father=0 ORDER BY catalogue_order"); if len(queryResult) != 0: # Query has executed successfully, so we can proceed to display all # catalogues in the EDS system... - text = "
    \n" for row in queryResult: - catalogues.append(row[0]) - text = text + displayCatalogueBranch(row[0],1,catalogues) - text = text + "
\n" + catalogues.append(getCatalogueBranch(row[0], 1)) + + text = websubmit_templates.tmpl_submit_home_catalogs( + ln = ln, + catalogs = catalogues + ) else: - text = "

No document types yet...

\n" + text = websubmit_templates.tmpl_submit_home_catalog_no_content(ln = ln) return text +def getCatalogueBranch(id_father,level): + elem = {} + queryResult = run_sql("SELECT name, id FROM sbmCOLLECTION WHERE id=%s", (id_father,)) + if len(queryResult) != 0: + row = queryResult[0] + elem['name'] = row[0] + elem['id'] = row[1] + elem['level'] = level + # display the son document types + elem['docs'] = [] + res1 = run_sql("SELECT id_son FROM sbmCOLLECTION_sbmDOCTYPE WHERE id_father=%s ORDER BY catalogue_order", (id_father,)) + if len(res1) != 0: + for row in res1: + elem['docs'].append(getDoctypeBranch(row[0])) + + elem['sons'] = [] + res2 = run_sql("SELECT id_son FROM sbmCOLLECTION_sbmCOLLECTION WHERE id_father=%s ORDER BY catalogue_order", (id_father,)) + if len(res2) != 0: + for row in res2: + elem['sons'].append(getCatalogueBranch(row[0], level + 1)) + + return elem + +def getDoctypeBranch(doctype): + res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,)) + return {'id' : doctype, + 'name' : res[0][0], + } + def displayCatalogueBranch(id_father,level,catalogues): text = "" queryResult = run_sql("SELECT name, id FROM sbmCOLLECTION WHERE id=%s", (id_father,)) if len(queryResult) != 0: row = queryResult[0] if level == 1: text = "
  • %s\n" % row[0] else: if level == 2: text = "
  • %s\n" % row[0] else: if level > 2: text = "
  • %s\n" % row[0] # display the son document types res1 = run_sql("SELECT id_son FROM sbmCOLLECTION_sbmDOCTYPE WHERE id_father=%s ORDER BY catalogue_order", (id_father,)) res2 = run_sql("SELECT id_son FROM sbmCOLLECTION_sbmCOLLECTION WHERE id_father=%s ORDER BY catalogue_order", (id_father,)) if len(res1) != 0 or len(res2) != 0: text = text + "
      \n" if len(res1) != 0: for row in res1: text = text + displayDoctypeBranch(row[0],catalogues) # display the son catalogues for row in res2: catalogues.append(row[0]) text = text + displayCatalogueBranch(row[0],level+1,catalogues) if len(res1) != 0 or len(res2) != 0: text = text + "
    \n" return text def displayDoctypeBranch(doctype,catalogues): text = "" res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,)) row = res[0] text = "
  • %s\n" % (doctype,doctype,doctype,row[0]) return text def action(req,c=cdsname,ln=cdslang,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 MySQLdb.Error, e: - return errorMsg(e.value, req) + return errorMsg(e.value, req, ln) #parses database to get all data #first the list of categories res = run_sql("SELECT * FROM sbmCATEGORIES WHERE doctype=%s ORDER BY lname", (doctype,)) if len(res) > 0: for arr in res: nbCateg = nbCateg+1 snameCateg.append(arr[1]) lnameCateg.append(arr[2]) #then data about the document type res = run_sql("SELECT * FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,)) if len(res) > 0: arr = res[0] docFullDesc = arr[0] docShortDesc = arr[1] description = arr[4] else: - return errorMsg ("Cannot find document %s" % doctype, req) + return errorMsg (_("Cannot find document %s") % doctype, req) #then data about associated actions res2 = run_sql("SELECT * FROM sbmIMPLEMENT LEFT JOIN sbmACTION on sbmACTION.sactname=sbmIMPLEMENT.actname WHERE docname=%s and displayed='Y' ORDER BY sbmIMPLEMENT.buttonorder", (docShortDesc,)) for arr2 in res2: res = run_sql("SELECT * FROM sbmACTION WHERE sactname=%s", (arr2[1],)) for arr in res: actionShortDesc.append(arr[1]) indir.append(arr[2]) actionbutton.append(arr[5]) statustext.append(arr[6]) - t = """ - -
    """ - t = t + "\n" % doctype - t = t + "" - - pid = os.getpid() - now = time.time() - t = t + "" % (now,pid) - t = t + """ - -""" - t = t + "\n" % doctype - t = t + """ - - """ - t+=" " % docFullDesc - t+=""" - - - - -""" - p_navtrail = "Submit > %s" % docFullDesc - return page(title="", - body=t, - navtrail=p_navtrail, - description="toto", - keywords="keywords", - uid=uid, - language=ln, - urlargs=req.args - ) + t = websubmit_templates.tmpl_action_page( + ln = ln, + 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 = """%(submit)s""" % {'submit' : _("Submit")} + + return page(title = docFullDesc, + body=t, + navtrail=p_navtrail, + description="submit documents in CDSWare", + keywords="submit, CDSWare", + uid=uid, + language=ln, + urlargs=req.args + ) def set_report_number (newrn): global uid_email,doctype,access,rn # First we save the value in the global object rn = newrn # then we save this value in the "journal of submissions" if uid_email != "" and uid_email != "guest": run_sql("UPDATE sbmSUBMISSIONS SET reference=%s WHERE doctype=%s and id=%s and email=%s", (newrn,doctype,access,uid_email,)) def get_report_number(): global rn return rn def set_sysno (newsn) : global sysno sysno = newsn def get_sysno() : global sysno return sysno 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 res = run_sql("SELECT value FROM sbmPARAMETERS WHERE doctype=%s and name=%s", (doctype,field,)) # If no data is found then the data concerning the DEF(ault) doctype is used if len(res) == 0: res = run_sql("SELECT value FROM sbmPARAMETERS WHERE doctype='DEF' and name=%s", (field,)) if len(res) == 0: return "" else: if res[0][0] != None: return res[0][0] else: return "" def Get_Parameters (function, doctype): # Returns the function parameters, in an array, for the function # Gets a description of the parameter parray = {} res = run_sql("SELECT * FROM sbmFUNDESC WHERE function=%s", (function,)) for i in range(0,len(res)): parameter = res[i][1] parray[parameter] = Evaluate_Parameter (parameter , doctype) return parray def get_level (doctype, action): res = run_sql("SELECT * FROM sbmIMPLEMENT WHERE docname=%s and actname=%s", (doctype,action,)) if len(res) > 0: return res[0][9] 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) res = run_sql("SELECT * FROM sbmIMPLEMENT WHERE docname=%s and actname=%s", (doctype,action,)) if len(res)>0: if res[0][9] != "0": return res[0][10] else: return -1 else: return -1 def print_function_calls (doctype, action, step, form): # 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,storage,access,pylibdir + global htdocsdir,storage,access,pylibdir,dismode t="" # Get the list of functions to be called res = run_sql("SELECT * FROM sbmFUNCTIONS WHERE action=%s and doctype=%s and step=%s ORDER BY score", (action,doctype,step,)) # If no data is found then the data concerning the DEF(ault) doctype is used if len(res) == 0: res = run_sql("SELECT * FROM sbmFUNCTIONS WHERE action=%s and doctype='DEF' and step=%s ORDER BY score", (action,step,)) if len(res) > 0: - t=t+Request_Print("S", "

    Here is the %s function list for %s documents at level %s

    " % (action,doctype,step)) - t=t+Request_Print("S", "") # while there are functions left... - for function in res: + functions = [] + for function in res: function_name = function[2] function_score = function[3] + currfunction = { + 'name' : function_name, + 'score' : function_score, + 'error' : 0, + 'text' : '', + } if os.path.exists("%s/cdsware/websubmit_functions/%s.py" % (pylibdir,function_name)): - t=t+Request_Print("S", "") + currfunction['text'] = function(parameters,curdir,form) else: - t=t+"function %s does not exist...
    " % function_name - t=t+Request_Print("S","
    FunctionScoreRunning Function
    %s%s" % (function_name,function_score)) # import the function itself #function = getattr(cdsware.websubmit_functions, function_name) execfile("%s/cdsware/websubmit_functions/%s.py" % (pylibdir,function_name),globals()) if not globals().has_key(function_name): - t=t+"function %s does not exist...
    " % 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 - t=t+function(parameters,curdir,form) - t=t+Request_Print("S","
    ") + 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 : - t=t+Request_Print("S","

    Your chosen action is not supported by the document") + if dismode == 'S': + t = "

    " + _("Your chosen action is not supported by the document") + "" return t def Propose_Next_Action (doctype,action_score,access,currentlevel,indir): global machine,storage,act,rn t="" res = run_sql("SELECT * FROM sbmIMPLEMENT WHERE docname=%s and level!='0' and level=%s and score>%s ORDER BY score", (doctype,currentlevel,action_score,)) if len(res) > 0: - t=t+Request_Print("A","

    You now have to

      ") + actions = [] first_score = res[0][10] for i in range(0,len(res)): action = res[i] if action[10] == first_score: - if i > 0: - t=t+Request_Print("A"," or"); res2 = run_sql("SELECT dir FROM sbmACTION WHERE sactname=%s", (action[1],)) nextdir = res2[0][0] - t=t+Request_Print("A","
    • %s " % (action[11],action[11],action[1],doctype,nextdir,access,indir,action[12])) - t=t+Request_Print("A","
    ") + 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 Test_Reload(uid_email,doctype,act,access): res = run_sql("SELECT * FROM sbmSUBMISSIONS WHERE doctype=%s and action=%s and id=%s and email=%s and status='finished'", (doctype,act,access,uid_email,)) if len(res) > 0: return 1 else: return 0 class functionError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class functionStop(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def errorMsg(title,req,c=cdsname,ln=cdslang): - return page(title="error", - body = create_error_box(req, title=title,verbose=0, ln=ln), - description="%s - Internal Error" % c, - keywords="%s, CDSware, Internal Error" % c, - language=ln, - urlargs=req.args) + # 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, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args) def warningMsg(title,req,c=cdsname,ln=cdslang): - return page(title="warning", - body = title, - description="%s - Internal Error" % c, - keywords="%s, CDSware, Internal Error" % c, - language=ln, - urlargs=req.args) + # load the right message language + _ = gettext_set_language(ln) + + return page(title = _("warning"), + body = title, + description="%s - Internal Error" % c, + keywords="%s, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args) def getCookie(name,uid): # these are not real http cookies but are stored in the DB res = run_sql("select value from sbmCOOKIES where uid=%s and name=%s", (uid,name,)) if len(res) > 0: return res[0][0] else: return None def setCookie(name,value,uid): # these are not real http cookies but are stored in the DB res = run_sql("select id from sbmCOOKIES where uid=%s and name=%s", (uid,name,)) if len(res) > 0: run_sql("update sbmCOOKIES set value=%s where uid=%s and name=%s", (value,uid,name,)) else: run_sql("insert into sbmCOOKIES(name,value,uid) values(%s,%s,%s)", (name,value,uid,)) return 1 def specialchars(text): text = string.replace(text,"“","\042"); text = string.replace(text,"”","\042"); text = string.replace(text,"’","\047"); text = string.replace(text,"—","\055"); text = string.replace(text,"…","\056\056\056"); return text - - diff --git a/modules/websubmit/lib/websubmit_templates.py b/modules/websubmit/lib/websubmit_templates.py new file mode 100644 index 000000000..287e510ba --- /dev/null +++ b/modules/websubmit/lib/websubmit_templates.py @@ -0,0 +1,1929 @@ +## $Id$ + +## This file is part of the CERN Document Server Software (CDSware). +## Copyright (C) 2002, 2003, 2004, 2005 CERN. +## +## The CDSware is free software; you can redistribute it and/or +## modify it under the terms of the GNU General Public License as +## published by the Free Software Foundation; either version 2 of the +## License, or (at your option) any later version. +## +## The CDSware is distributed in the hope that it will be useful, but +## WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +## General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with CDSware; if not, write to the Free Software Foundation, Inc., +## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +import urllib +import time +import cgi +import gettext +import string +import locale +import re +import operator +import os + +from config import * +from messages import gettext_set_language + +class Template: + 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 """ + + + + + + + + + """ % { + 'document_types' : _("Document types available for submission"), + 'please_select' : _("Please select the type of document you want to submit"), + 'catalogues' : catalogues, + } + + 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 = "

    " + _("No document types yet...") + "

    \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 = "
    " + pprint.pformat(catalogs)
    +        out = ""
    +        for catalog in catalogs:
    +            out += "
      " + out += self.tmpl_submit_home_catalogs_sub(ln, catalog) + + 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 = "
    • %s\n" % catalog['name'] + else: + if catalog['level'] == 2: + out = "
    • %s\n" % catalog['name'] + else: + if catalog['level'] > 2: + out = "
    • %s\n" % catalog['name'] + + if len(catalog['docs']) or len(catalog['sons']): + out += "
        " + + 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 += "
      " + + 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 """
    • %(name)s""" % doc + + def tmpl_action_page(self, ln, 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 += """ + +
      + + + + + + + + + + + + + + + + """ % { + 'continue_explain' : _("To continue an interrupted submission, enter your access number directly in the input box."), + 'doctype' : doctype, + 'go' : _("go"), + } + + 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 """
      %s
      """ % msg + + def tmpl_page_interface(self, ln, docname, actname, curpage, nbpages, file, nextPg, access, nbPg, doctype, act, indir, fields, javascript, images, 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 + + - 'images' *string* - the path to the images + + - 'mainmenu' *string* - the url of the main menu + + """ + + # load the right message language + _ = gettext_set_language(ln) + + # top menu + out = """ +
      +
      + + + + + + + \n" + + # Display the navigation cell + # Display "previous page" navigation arrows + out += """
      %(docname)s  %(actname)s  + + + """ % { + 'docname' : docname, + 'actname' : actname, + } + + for i in range(1, nbpages+1): + if i == int(curpage): + out += """""" % curpage + else: + out += """""" % (i,i) + out += """
         page: %s  %s    +
      +
       %(summary)s(2) 
      +
      +
      + + + + + + + + + + + """ % { + 'summary' : _("SUMMARY"), + 'doctype' : doctype, + 'act' : act, + 'access' : access, + 'indir' : indir, + 'file' : file, + 'nextPg' : nextPg, + 'curpage' : curpage, + 'nbPg' : nbPg, + } + + for field in fields: + if field['javascript']: + out += """ + """ % field['javascript']; + + # now displays the html form field(s) + out += "%s\n%s\n" % (field['fullDesc'], field['text']) + + out += javascript + out += "
       
       
      """ + if int(curpage) != 1: + out += """ + """ % { + 'prpage' : int(curpage) - 1, + 'images' : images, + 'prevpage' : _("previous page"), + } + else: + out += """ """ + # Display the submission number + out += """ \n""" % { + 'submission' : _("Submission no(1)"), + 'access' : access, + } + # Display the "next page" navigation arrow + if int(curpage) != int(nbpages): + out += """ + """ % { + 'nxpage' : int(curpage) + 1, + 'images' : images, + 'nextpage' : _("next page"), + } + else: + out += """ """ + out += """
        + + %(prevpage)s + %(prevpage)s + +  %(submission)s: %(access)s + + %(nextpage)s + %(nextpage)s + +  
      + +
      +
      + + %(back)s +

      +
      + %(take_note)s
      + %(explain_summary)s
      + """ % { + 'surequit' : _("Are you sure you want to quit this submission?"), + 'back' : _("back to main menu"), + 'mainmenu' : mainmenu, + 'images' : images, + 'take_note' : _("(1) you should take note of this number at the beginning of the submission, it will allow you to get your information back in case your browser crashes before the end of the submission."), + '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': + text="" % (field['name'],field['rows'],field['cols'],field['val']) + # If the field is a file upload + elif field['type'] == 'F': + text="" % (field['name'],field['size'], field['maxlength']); + # If the field is a text input + elif field['type'] == 'I': + text="" % (field['name'],field['size'],field['val']) + # If the field is a hidden input + elif field['type'] == 'H': + text="" % (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, images, 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 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 + + - 'images' *int* - the path to the images + + - '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 = """""" + return out + + def tmpl_page_endaction(self, ln, weburl, file, nextPg, startPg, access, curpage, nbPg, nbpages, doctype, act, docname, actname, indir, mainmenu, finished, function_content, next_action, images): + """ + Produces the pages after all the fields have been submitted. + + Parameters: + + - 'ln' *string* - The language to display the interface in + + - 'weburl' *string* - The url of cdsware + + - '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 + + - 'images' *string* - the path to the images + + - '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 = """ +
      + + + + + + + + + + + + + + + + + + +
      + + + + + """ % { + 'finished' : _("finished!"), + } + else: + for i in range(1, nbpages + 1): + out += """""" % (i,i) + out += """
      %(docname)s  %(actname)s  + + + """ % { + 'file' : file, + 'nextPg' : nextPg, + 'startPg' : startPg, + 'access' : access, + 'curpage' : curpage, + 'nbPg' : nbPg, + 'doctype' : doctype, + 'act' : act, + 'docname' : docname, + 'actname' : actname, + 'indir' : indir, + 'mainmenu' : mainmenu, + } + + if finished == 1: + out += """ + +
        %(finished)s  
      +
         + %s %(end_action)s  
      +  %(summary)s(2) """ % { + 'end_action' : _("end of action"), + 'summary' : _("SUMMARY"), + 'doctype' : doctype, + 'act' : act, + 'access' : access, + 'indir' : indir, + } + out += """ + + +

      + %(function_content)s + %(next_action)s +

      + + + + """ % { + 'function_content' : function_content, + 'next_action' : next_action, + } + if finished == 0: + out += """%(submission)s²: + %(access)s""" % { + 'submission' : _("Submission no"), + 'access' : access, + } + else: + out += " \n" + out += """ + + + +
      + +
      +
      """ + # Add the "back to main menu" button + if finished == 0: + out += """ """ % { + 'surequit' : _("Are you sure you want to quit this submission?"), + 'mainmenu' : mainmenu, + } + else: + out += """ + %(back)s +

      """ % { + 'back' : _("back to main menu"), + 'images' : images, + '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 += """

      %(function_list)s

      + + + """ % { + 'function_list' : _("Here is the %(action)s function list for %(doctype)s documents at level %(step)s") % { + 'action' : action, + 'doctype' : doctype, + 'step' : step, + }, + 'function' : _("Function"), + 'score' : _("Score"), + 'running' : _("Running Function"), + } + for function in functions: + out += """""" % { + 'name' : function['name'], + 'score' : function['score'], + 'result' : function['error'] and (_("function %s does not exist...") % function['name'] + "
      ") or function['text'] + } + out += "
      %(function)s%(score)s%(running)s
      %(name)s%(score)s%(result)s
      " + 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 = "

      %(haveto)s

        " % { + 'haveto' : _("You now have to"), + } + i = 0 + for action in actions: + if i > 0: + out += " " + _("or") + " " + i += 1 + out += """
      • %(name)s """ % action + + out += "
      " + return out + + def tmpl_filelist(self, ln, filelist, recid, docid, version): + """ + Displays the file list for a record. + + Parameters: + + - 'ln' *string* - The language to display the interface in + + - 'recid' *string* - The record id + + - 'docid' *string* - The document id + + - 'version' *string* - 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 #%s") % ("%s" % (recid,recid)) + if docid != "": + title += _(" document #%s") % docid + if version != "": + title += _(" version #%s") % version + + out = """
      + """ % (title, filelist) + + return out + + def tmpl_bibrecdoc_filelist(self, ln, types): + """ + 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 + """ + + # load the right message language + _ = gettext_set_language(ln) + + out = "" + for mytype in types: + out += "%s %s:" % (mytype['name'], _("file(s)")) + out += "
        " + for content in mytype['content']: + out += content + out += "
      " + return out + + def tmpl_bibdoc_filelist(self, ln, weburl, versions, imagepath, docname, id): + """ + Displays the file list for a record. + + Parameters: + + - 'ln' *string* - The language to display the interface in + + - 'weburl' *string* - The url of cdsware + + - '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 + + - 'imagepath' *string* - The path to the image of the file + + - 'docname' *string* - The name of the document + + - 'id' *int* - The id of the document + + """ + + # load the right message language + _ = gettext_set_language(ln) + + out = """ + + + """ % { + 'imagepath' : imagepath, + 'docname' : docname + } + for version in versions: + if version['previous']: + versiontext = """
      (%(see)s %(previous)s)""" % { + 'see' : _("see"), + 'weburl' : weburl, + 'id' : id, + 'previous': _("previous"), + } + else: + versiontext = "" + out += """ + + " + out += "" + return out + + def tmpl_bibdocfile_filelist(self, ln, weburl, id, name, selfformat, version, format, size): + """ + Displays a file in the file list. + + Parameters: + + - 'ln' *string* - The language to display the interface in + + - 'weburl' *string* - The url of cdsware + + - 'id' *int* - The id of the document + + - 'name' *string* - The name of the file + + - 'selfformat' *string* - The format to pass in parameter + + - '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 """ + + + %(name)s%(format)s + + + + [%(size)s B] + """ % { + 'weburl' : weburl, + 'docid' : id, + 'quotedname' : urllib.quote(name), + 'selfformat' : urllib.quote(selfformat), + 'version' : version, + 'name' : name, + 'format' : format, + 'size' : size + } + + def tmpl_submit_summary (self, ln, values, images): + """ + 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 + + - 'images' *string* - the path to the images + """ + + # load the right message language + _ = gettext_set_language(ln) + + out = """""" % \ + { 'images' : images } + + for value in values: + if value['mandatory']: + color = "red" + else: + color = "" + out += """ + + + """ % { + 'color' : color, + 'name' : value['name'], + 'value' : value['value'], + 'page' : value['page'] + } + out += "
      + + + %(name)s + + + + %(value)s +
      " + return out + + def tmpl_yoursubmissions(self, ln, images, weburl, order, doctypes, submissions): + """ + Displays the list of the user's submissions. + + Parameters: + + - 'ln' *string* - The language to display the interface in + + - 'images' *string* - the path to the images + + - 'weburl' *string* - The url of cdsware + + - '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 += """ +
      + +
      + + + + + + + + + +
      " + 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 = """ + + + + + " + 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 = """ + + + + + + + + """ + return out + + def tmpl_publiline_selectcateg(self, ln, doctype, title, categories, images): + """ + 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 + + - 'images' *string* - the path to the images + + - '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 = """ + + + + + + + + """ % { + 'key' : _("Key"), + 'pending' : _("pending"), + 'images' : images, + 'waiting' : _("waiting for approval"), + 'approved' : _("approved"), + 'already_approved' : _("already approved"), + 'rejected' : _("rejected"), + 'rejected_text' : _("rejected"), + 'already_approved' : _("already approved"), + 'somepending' : _("some documents are pending"), + } + return out + + def tmpl_publiline_selectdocument(self, ln, doctype, title, categ, images, 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 + + - 'images' *string* - the path to the images + + - '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 = """ + + + + + + + + """ + return out + + def tmpl_publiline_displaydoc(self, ln, doctype, docname, categ, rn, status, dFirstReq, dLastReq, dAction, access, images, accessurl, 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) + + - 'images' *string* - the path to the images + + - 'accessurl' *string* - the URL of the publications + + - '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 = """""" % images + elif status == "approved": + image = """""" % images + elif status == "rejected": + image = """""" % images + else: + image = "" + out = """ + + + + + + + + + + """ + return out diff --git a/modules/websubmit/web/getfile.py b/modules/websubmit/web/getfile.py index 2215085f3..31b68ca3e 100644 --- a/modules/websubmit/web/getfile.py +++ b/modules/websubmit/web/getfile.py @@ -1,108 +1,114 @@ ## $Id$ -## + ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## import interesting modules: import string import os import time import types import re from mod_python import apache import sys from cdsware.config import cdsname,cdslang from cdsware.access_control_engine import acc_authorize_action from cdsware.access_control_admin import acc_isRole from cdsware.webpage import page, create_error_box from cdsware.webuser import getUid, get_email, page_not_authorized from cdsware.messages import * from cdsware.websubmit_config import * from cdsware.file import * from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE +from cdsware.messages import gettext_set_language + +import cdsware.template +websubmit_templates = cdsware.template.load('websubmit') + def index(req,c=cdsname,ln=cdslang,recid="",docid="",version="",name="",format=""): + # load the right message language + _ = gettext_set_language(ln) + # get user ID: try: uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "../getfile.py/index") uid_email = get_email(uid) except MySQLdb.Error, e: return errorMsg(e.value,req) docfiles = [] t="" filelist="" ip=str(req.get_remote_host(apache.REMOTE_NOLOOKUP)) # if a precise file is requested, we stream it if name!="": if docid=="": - return errorMsg("Parameter docid missing",req) + return errorMsg(_("Parameter docid missing"), req, c, ln) else: doc = BibDoc(bibdocid=docid) docfile=doc.getFile(name,format,version) if docfile == None: - return warningMsg("can't find file...",req) + return warningMsg(_("can't find file..."),req, c, ln) else: res = doc.registerDownload(ip, version, format, uid) return docfile.stream(req) # all files attached to a record elif recid!="": bibarchive = BibRecDocs(recid) - filelist = bibarchive.display(docid,version) + filelist = bibarchive.display(docid, version, ln = ln) # a precise filename elif docid!="": bibdoc = BibDoc(bibdocid=docid) recid = bibdoc.getRecid() - filelist = bibdoc.display(version) - title = "record #%s" % (recid,recid) - if docid != "": - title += " document #%s" % docid - if version != "": - title += " version #%s" % version - t = """
      \n""" - p_navtrail = "Access to Fulltext" + filelist = bibdoc.display(version, ln = ln) + t = websubmit_templates.tmpl_filelist( + ln = ln, + recid = recid, + docid = docid, + version = version, + filelist = filelist, + ) + p_navtrail = _("Access to Fulltext") return page(title="", - body=t, - navtrail = p_navtrail, - description="", - keywords="keywords", - uid=uid, - language=ln, - urlargs=req.args - ) - + body=t, + navtrail = p_navtrail, + description="", + keywords="keywords", + uid=uid, + language=ln, + urlargs=req.args + ) + def errorMsg(title,req,c=cdsname,ln=cdslang): return page(title="error", body = create_error_box(req, title=title,verbose=0, ln=ln), - description="%s - Internal Error" % c, + description="%s - Internal Error" % c, keywords="%s, CDSware, Internal Error" % c, language=ln, urlargs=req.args) def warningMsg(title,req,c=cdsname,ln=cdslang): return page(title="warning", body = title, - description="%s - Internal Error" % c, + description="%s - Internal Error" % c, keywords="%s, CDSware, Internal Error" % c, language=ln, urlargs=req.args) - diff --git a/modules/websubmit/web/publiline.py b/modules/websubmit/web/publiline.py index 8f24081b4..898ea01ba 100644 --- a/modules/websubmit/web/publiline.py +++ b/modules/websubmit/web/publiline.py @@ -1,422 +1,361 @@ ## $Id$ -## + ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## import interesting modules: import string import os import sys import time import types import re import MySQLdb import shutil - from cdsware.config import cdsname,cdslang,supportemail,pylibdir from cdsware.dbquery import run_sql from cdsware.access_control_engine import acc_authorize_action from cdsware.access_control_admin import * from cdsware.webpage import page, create_error_box from cdsware.webuser import getUid, get_email, list_registered_users, page_not_authorized from cdsware.messages import * from cdsware.websubmit_config import * from cdsware.search_engine import search_pattern from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE execfile("%s/cdsware/websubmit_functions/Retrieve_Data.py" % pylibdir) execfile("%s/cdsware/websubmit_functions/mail.py" % pylibdir) +from cdsware.messages import gettext_set_language +import cdsware.template +websubmit_templates = cdsware.template.load('websubmit') + def index(req,c=cdsname,ln=cdslang,doctype="",categ="",RN="",send=""): 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, "../publiline.py/index") uid_email = get_email(uid) except MySQLdb.Error, e: - return errorMsg(e.value,req) + return errorMsg(e.value,req, ln = ln) if doctype == "": - t=selectDoctype() + t = selectDoctype(ln) elif categ == "": - t=selectCateg(doctype) + t = selectCateg(doctype, ln) elif RN == "": - t=selectDocument(doctype,categ) + t = selectDocument(doctype,categ, ln) else: - t=displayDocument(doctype,categ,RN,send) + t = displayDocument(doctype,categ,RN,send, ln) return page(title="publication line", - body=t, - description="", - keywords="", - uid=uid, - language=ln, - urlargs=req.args) - -def selectDoctype(): - t=""" - - - - - - - -""" + docs.append({ + 'doctype' : row[0], + 'docname' : res2[0][0], + }) + t = websubmit_templates.tmpl_publiline_selectdoctype( + ln = ln, + docs = docs, + ) return t -def selectCateg(doctype): +def selectCateg(doctype, ln = cdslang): 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) - t+=""" - - """ - t+= "" % title - t+=""" - - - - -""" + 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 selectDocument(doctype,categ): +def selectDocument(doctype,categ, ln = cdslang): t="" res = run_sql("select ldocname from sbmDOCTYPE where sdocname=%s", (doctype,)) title = res[0][0] if categ == "": categ == "unknown" - t+=""" - - """ - t+= "" % (title,categ) - t+=""" - - - - -""" + 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 displayDocument(doctype,categ,RN,send): +def displayDocument(doctype,categ,RN,send, ln = cdslang): + + # 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] - if status == "waiting": - image = "\"\"" % images - elif status == "approved": - image = "\"\"" % images - elif status == "rejected": - image = "\"\"" % images - else: - image = "" - t+=""" - - """ - t+= "" % (image,RN) - t+=""" - - - - - - -""" + 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 # Retrieve info about document def getInfo(doctype,categ,RN): 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): PENDIR="%s/pending" % storage 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): # initialize sysno variable sysno = "" searchresults = search_pattern(req=None, p=RN, f="reportnumber").items().tolist() 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>' % (cdsname,supportemail) # 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("","([^-]*)",categformat) categs = re.match(categformat,RN) if categs != 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) else: otheraddresses = "" # Build referee's email address refereeaddress = "" # Try to retrieve the referee's email from the referee's database for user in acc_getRoleUsers(acc_getRoleId("referee_%s_%s" % (doctype,categ))): refereeaddress += user[1] + "," # And if there are general referees for user in acc_getRoleUsers(acc_getRoleId("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/getfile.py?recid=%s> - + To approve/reject the document, you should go to this URL: <%s/approve.py?%s> - + --------------------------------------------- Best regards. The submission team.""" % (RN,title,authors,urlpath,sysno,urlpath,access) # send the mail body = forge_email(FROMADDR,addresses,adminemail,"Request for Approval of %s" % RN,message) send_email(FROMADDR,addresses,body,0) return "" def SendWarning(doctype,categ,RN,title,authors,access): FROMADDR = '%s Submission Engine <%s>' % (cdsname,supportemail) message = "Failed sending approval email request for %s" % RN # send the mail body = forge_email(FROMADDR,adminemail,"","Failed sending approval email request",message) send_email(FROMADDR,adminemail,body,0) return "" +def errorMsg(title,req,c=cdsname,ln=cdslang): + return page(title="error", + body = create_error_box(req, title=title,verbose=0, ln=ln), + description="%s - Internal Error" % c, + keywords="%s, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args) + +def warningMsg(title,req,c=cdsname,ln=cdslang): + return page(title="warning", + body = title, + description="%s - Internal Error" % c, + keywords="%s, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args) + diff --git a/modules/websubmit/web/summary.py b/modules/websubmit/web/summary.py index 543f8ea8d..771538934 100644 --- a/modules/websubmit/web/summary.py +++ b/modules/websubmit/web/summary.py @@ -1,66 +1,76 @@ ## $Id$ -## + ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. -"""CDSware Submission Web Interface.""" - ## import interesting modules: import string import os import sys import time from cdsware.config import cdsname,cdslang from cdsware.dbquery import run_sql from cdsware.access_control_engine import acc_authorize_action from cdsware.websubmit_config import * from cdsware.webpage import page, create_error_box from cdsware.webuser import getUid,get_email, page_not_authorized from cdsware.messages import * from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE -def index(req,doctype="",act="",access="",indir=""): +from cdsware.messages import gettext_set_language + +import cdsware.template +websubmit_templates = cdsware.template.load('websubmit') + +def index(req,doctype="",act="",access="",indir="", ln=cdslang): uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "../summary.py/index") - t="" + t="" curdir = "%s/%s/%s/%s" % (storage,indir,doctype,access) subname = "%s%s" % (act,doctype) res = run_sql("select sdesc,fidesc,pagenb,level from sbmFIELD where subname=%s order by pagenb,fieldnb", (subname,)) nbFields = 0 - t=t+"\n" % images + + values = [] for arr in res: if arr[0] != "": - if arr[3] == "M": - color = "red" - else: - color = "" + val = { + 'mandatory' : (arr[3] == 'M'), + 'value' : '', + 'page' : arr[2], + 'name' : arr[0], + } if os.path.exists("%s/%s" % (curdir,arr[1])): fd = open("%s/%s" % (curdir,arr[1]),"r") value = fd.read() fd.close() value = value.replace("\n"," ") value = value.replace("Select:","") else: value = "" - #value = strip_tags($value); - t=t+ "\n" % (arr[2],color,arr[0],value); - t=t+"
      %s%s
      " - return t + val['value'] = value + values.append(val) + + return websubmit_templates.tmpl_submit_summary( + ln = ln, + values = values, + images = images, + ) diff --git a/modules/websubmit/web/yourapprovals.py b/modules/websubmit/web/yourapprovals.py index 6a2789df0..a5067d485 100644 --- a/modules/websubmit/web/yourapprovals.py +++ b/modules/websubmit/web/yourapprovals.py @@ -1,95 +1,110 @@ ## $Id$ -## + ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## import interesting modules: import os import sys - from cdsware.config import weburl,cdsname,cdslang from cdsware.dbquery import run_sql from cdsware.access_control_engine import acc_authorize_action from cdsware.access_control_admin import * from cdsware.webpage import page, create_error_box from cdsware.webuser import getUid, get_email, list_registered_users, page_not_authorized from cdsware.messages import * from cdsware.websubmit_config import * from cdsware.search_engine import search_pattern from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE +from cdsware.messages import gettext_set_language + +import cdsware.template +websubmit_templates = cdsware.template.load('websubmit') + def index(req,c=cdsname,ln=cdslang,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") u_email = get_email(uid) except MySQLdb.Error, e: - return errorMsg(e.value,req) - t+=""" - - - - - - " - return page(title="Your Approvals", - navtrail="""Your Account""" % weburl, + categories.append({ + 'id' : category, + 'name' : categname, + }) + referees.append({ + 'doctype' : doctype, + 'docname' : docname, + 'categories' : categories + }) + + + t = websubmit_templates.tmpl_yourapprovals( + ln = ln, + referees = referees + ) + return page(title=_("Your Approvals"), + navtrail= """%(account)s""" % { + 'weburl' : weburl, + 'account' : _("Your Account"), + }, body=t, description="", keywords="", uid=uid, language=ln, urlargs=req.args) def isReferee(uid,doctype="",categ=""): (auth_code, auth_message) = acc_authorize_action(uid, "referee",verbose=0,doctype=doctype, categ=categ) if auth_code == 0: return 1 else: return 0 def errorMsg(title,req,c=cdsname,ln=cdslang): return page(title="error", body = create_error_box(req, title=title,verbose=0, ln=ln), - description="%s - Internal Error" % c, + description="%s - Internal Error" % c, keywords="%s, CDSware, Internal Error" % c, language=ln, urlargs=req.args) diff --git a/modules/websubmit/web/yoursubmissions.py b/modules/websubmit/web/yoursubmissions.py index 1f4e04523..995233553 100644 --- a/modules/websubmit/web/yoursubmissions.py +++ b/modules/websubmit/web/yoursubmissions.py @@ -1,204 +1,198 @@ ## $Id$ -## + ## This file is part of the CERN Document Server Software (CDSware). ## Copyright (C) 2002, 2003, 2004, 2005 CERN. ## ## The CDSware is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## The CDSware is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDSware; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ## import interesting modules: import string import os import sys import time import types import re import MySQLdb import shutil import operator - from cdsware.config import weburl,cdsname,cdslang from cdsware.dbquery import run_sql from cdsware.access_control_engine import acc_authorize_action from cdsware.access_control_admin import * from cdsware.webpage import page, create_error_box from cdsware.webuser import getUid, get_email, list_registered_users, page_not_authorized from cdsware.messages import * from cdsware.websubmit_config import * from cdsware.search_engine import search_pattern from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE +from cdsware.messages import gettext_set_language + +import cdsware.template +websubmit_templates = cdsware.template.load('websubmit') + def index(req,c=cdsname,ln=cdslang,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, "../yoursubmissions.py/index") u_email = get_email(uid) except MySQLdb.Error, e: - return errorMsg(e.value,req) + return errorMsg(e.value, req, ln) + + if u_email == "guest" or u_email == "": + return warningMsg(websubmit_templates.tmpl_warning_message( + ln = ln, + msg = _("You first have to login before using this feature. Use the left menu to log in."), + ),req, ln = ln) + + if deletedId != "": - t+=deleteSubmission(deletedId,deletedAction,deletedDoctype,u_email) - t+=""" -
      - -
      -""" % order - t+=""" - - - - - -
      " - + + submissions.append({ + 'docname' : ldocname, + 'actname' : lactname, + 'status' : status, + 'cdate' : row[6], + 'mdate' : row[7], + 'reference' : row[5], + 'id' : row[4], + 'act' : currentaction, + 'doctype' : currentdoctype, + 'pending' : (row[3] == "pending") + }) + # display + t += websubmit_templates.tmpl_yoursubmissions( + ln = ln, + weburl = weburl, + images = images, + order = order, + doctypes = doctypes, + submissions = submissions, + ) + return page(title="Your Submissions", - navtrail="""Your Account""" % weburl, + navtrail= """%(account)s""" % { + 'weburl' : weburl, + 'account' : _("Your Account"), + }, body=t, description="", keywords="", uid=uid, language=ln, urlargs=req.args) - + def deleteSubmission(id, action, doctype, u_email): global storage run_sql("delete from sbmSUBMISSIONS WHERE doctype=%s and action=%s and email=%s and status='pending' and id=%s",(doctype,action,u_email,id,)) res = run_sql("select dir from sbmACTION where sactname=%s",(action,)) dir = res[0][0] if re.search("\.\.",doctype) == None and re.search("\.\.",id) == None and id != "": if os.path.exists("%s/%s/%s/%s" % (storage,dir,doctype,id)): os.rmdir("%s/%s/%s/%s" % (storage,dir,doctype,id)) return "" def warningMsg(title,req,c=cdsname,ln=cdslang): return page(title="warning", - body = title, - description="%s - Internal Error" % c, - keywords="%s, CDSware, Internal Error" % c, - language=ln, - urlargs=req.args) + body = title, + description="%s - Internal Error" % c, + keywords="%s, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args) def errorMsg(title,req,c=cdsname,ln=cdslang): return page(title="error", - body = create_error_box(req, title=title,verbose=0, ln=ln), - description="%s - Internal Error" % c, - keywords="%s, CDSware, Internal Error" % c, - language=ln, - urlargs=req.args) + body = create_error_box(req, title=title,verbose=0, ln=ln), + description="%s - Internal Error" % c, + keywords="%s, CDSware, Internal Error" % c, + language=ln, + urlargs=req.args)