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 = {
+ 'name' : mytype,
+ 'content' : [],
+ }
for bibdoc in bibdocs:
if mytype == bibdoc.getType():
- t+=bibdoc.display(version)
- 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+="" % (version,versiontext)
- t+=""
+ currversion['previous'] = 1
for docfile in docfiles:
if docfile.getVersion() == version:
- t +=docfile.display()
- t+=" |
"
- 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+""
-
- # # # # # # # # # # # # # # # # # # # # # # # # #
- # Fill the fields with the previously saved values
- # # # # # # # # # # # # # # # # # # # # # # # # #
- t=t+"
-
-
"""
- # Display the "back to main menu" button
- t=t+"\n" % mainmenu
- t=t+"
\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+"
-
-
"""
- # Add the "back to main menu" button
- if finished == 0:
- t=t+ " \n" % mainmenu
- else:
- t=t+" \n" % mainmenu
- t=t+"
\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 + """
-
-
-
-
-
-
-
-
-Please select the type of document you want to submit:
-
-
-
-
-"""
- 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 = """
-
-