def Get_Sysno(parameters, curdir, form, user_info=None): """ **Deprecated - Use Get_Recid Instead** """ global rn, sysno # initialize sysno variable sysno = "" if os.path.exists("%s/SN" % curdir): fp = open("%s/SN" % curdir, "r") sysno = fp.read() fp.close() else: searchresults = list(search_pattern(req=None, p=rn, f="reportnumber")) if len(searchresults) == 0: raise InvenioWebSubmitFunctionStop( "<SCRIPT>document.forms[0].action=\"/submit\";document.forms[0].curpage.value=1;document.forms[0].step.value=0;user_must_confirm_before_leaving_page = false;document.forms[0].submit();alert('The report %s cannot be found in our database.\\nPerhaps it has not been integrated yet?\\nAnyway, you can choose another report number if you wish.\\n Or retry this action in a few minutes.');</SCRIPT>" % rn) elif len(searchresults) > 1: raise InvenioWebSubmitFunctionStop( "<SCRIPT>document.forms[0].action=\"/submit\";document.forms[0].curpage.value=1;document.forms[0].step.value=0;user_must_confirm_before_leaving_page = false;document.forms[0].submit();alert('Multiple documents have been found with report number %s\\nYou can try with another report number if you wish.\\n Or retry this action in a few minutes.');</SCRIPT>" % rn) else: sysno = searchresults[0] # save resultin a file fp = open("%s/SN" % curdir, "w") fp.write(str(sysno)) fp.close() return ""
def Is_Referee(parameters, curdir, form, user_info=None): """ This function checks whether the currently logged user is a referee for this document. """ global uid_email,sysno,rn,uid doctype = form['doctype'] # Get document category res = run_sql("SELECT categ FROM sbmAPPROVAL WHERE rn=%s", (rn,)) if len(res) >0: categ = res[0][0] if categ == "unknown": ## FIXME: This was necessary for document types without categories, ## such as DEMOBOO: categ = "*" else: categ="" # Try to retrieve the referee's email from the referee's database (auth_code, auth_message) = acc_authorize_action(user_info, "referee",doctype=doctype, categ=categ) if auth_code != 0: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); alert('Sorry you (%s) have not been recognized as a referee for this type of document.\\nIf you think this is an error, please contact %s'); </SCRIPT>""" % (uid_email,CFG_SITE_SUPPORT_EMAIL)) return ""
def Is_Original_Submitter(parameters, curdir, form, user_info=None): """ This function compares the current logged in user email with the email of the original submitter of the record. If it is the same (or if the current user has superuser rights), we go on. If it differs, an error message is issued. """ global uid_email,sysno,uid doctype = form['doctype'] act = form['act'] email = Get_Field("8560_f",sysno) email = re.sub("[\n\r ]+","",email) uid_email = re.sub("[\n\r ]+","",uid_email) (auth_code, auth_message) = acc_authorize_action(user_info, "submit",verbose=0,doctype=doctype, act=act) if re.search(uid_email,email,re.IGNORECASE) is None and auth_code != 0: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).'); </SCRIPT>""" % (uid_email,email)) elif re.search(uid_email,email, re.IGNORECASE) is None and \ auth_code == 0: if not os.path.exists(os.path.join(curdir, 'is_original_submitter_warning')): write_file(os.path.join(curdir, 'is_original_submitter_warning'), '') return (""" <SCRIPT> alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).\\n\\nAnyway, as you have a special authorization for this type of documents,\\nyou are allowed to proceed! Watch out your actions!'); </SCRIPT>""" % (uid_email,email)) return ""
def Test_Status(parameters, curdir, form, user_info=None): """ This function checks whether the considered document has been requested for approval and is still waiting for approval. It also checks whether the password stored in file 'password' of the submission directory corresponds to the password associated with the document. """ global rn res = run_sql("SELECT status, access FROM sbmAPPROVAL WHERE rn=%s", (rn, )) if len(res) == 0: raise InvenioWebSubmitFunctionStop(printNotRequested(rn)) else: if res[0][0] == "approved": raise InvenioWebSubmitFunctionStop(printApproved(rn)) elif res[0][0] == "rejected": raise InvenioWebSubmitFunctionStop(printRejected(rn)) return ""
def DocumentNotFound(repno): raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; alert('The document %s cannot be found in our database.\\nAnyway, you can still choose another document if you wish.'); document.forms[0].submit(); </SCRIPT>""" % repno) return 0
def Check_Group(parameters, curdir, form, user_info=None): """ Check that a group exists. Read from file "/curdir/Group" If the group does not exist, switch to page 1, step 0 """ #Path of file containing group if os.path.exists("%s/%s" % (curdir, 'Group')): fp = open("%s/%s" % (curdir, 'Group'), "r") group = fp.read() group = group.replace("/", "_") group = re.sub("[\n\r]+", "", group) res = run_sql("""SELECT id FROM usergroup WHERE name = %s""", (group, )) if len(res) == 0: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); alert('The given group name (%s) is invalid.'); </SCRIPT>""" % (group, )) else: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); alert('The given group name (%s) is invalid.'); </SCRIPT>""" % (group, )) return ""
def Get_Recid(parameters, curdir, form, user_info=None): """ Given the report number of a record (the global "rn"), retrieve the "recid" (001). The function first of all checks for the existence of the file "SN" in the current submission's working directory. If it exists, it is read in and used as the "recid". Otherwise, this function will contact the database in order to obtain the recid of a record. In this case, a check will be done in order to assure that the recid can be handled by this submission. Parameters: record_search_pattern - this enforces restrictions on which type of documents can be modified via a certain submission interface. If the record_search_pattern is not defined, no restriction will be enforced. The record_search_pattern can be anything that can be used by search_pattern to search for. Also, one can use variables stored locally, like <comboDEMOJRN> to denote the category or subcategory. Ex: reportnumber:DEMO-<comboDEMOJRN>-* collection:ATLANTISTIMESNEWS reportnumber:DEMO-<comboDEMOJRN>-* | collection:ATLANTISTIMESNEWS As a note, you can test your pattern, using the search engine and see if it retrieves the expected results. Unless file curdir/SN exists, the function depends upon the global value 'rn' having been set (for eg. by calling Get_Report_Number' prior to this function) It will use this value when searching for a record. Note: If 'rn' is empty, the search for the document will not be conducted. Exceptions raised: + InvenioWebSubmitFunctionError: - if unable to open curdir/SN for reading; - if unable to open curdir/SN for writing; + InvenioWebSubmitFunctionStop: - if the global 'rn' is empty (no rn to search with); - if no recid found for 'rn' value; - if multiple recids found for 'rn' value; - if recid should not be handled by the current submission; """ global rn, sysno ## initialize sysno sysno = "" if access("%s/SN" % curdir, F_OK | R_OK): ## SN exists and should contain the recid; get it from there. try: fptr = open("%s/SN" % curdir, "r") except IOError: ## Unable to read the SN file's contents msg = """Unable to correctly read the current submission's recid""" raise InvenioWebSubmitFunctionError(msg) else: ## read in the submission details: sysno = fptr.read().strip() fptr.close() else: ## SN doesn't exist; Check the DB for a record with this reportnumber. ## First, if rn is empty, don't conduct the search: if rn.strip() in ("", None): ## No report-numer provided: raise InvenioWebSubmitFunctionStop(CFG_ALERT_DOCUMENT_NOT_FOUND \ % "NO REPORT NUMBER PROVIDED") ## Get a list of recids of LIVE records associated with the report num recids = get_existing_records_for_reportnumber(rn) ## There should only be 1 _existing_ record for the report-number: if len(recids) == 1: ## Only one record found - save it to a text file called SN ## in the current submission's working directory: try: fptr = open("%s/SN" % curdir, "w") except IOError: ## Unable to read the SN file's contents msg = """Unable to save the recid for report [%s]""" \ % rn raise InvenioWebSubmitFunctionError(msg) else: ## Save recid to SN and to the global scope: sysno = recids[0] fptr.write("%s" % sysno) fptr.flush() fptr.close() elif len(recids) < 1: ## No recid found for this report number: msg = CFG_ALERT_DOCUMENT_NOT_FOUND % rn raise InvenioWebSubmitFunctionStop(msg) else: ## Multiple recids found for this report-number: msg = CFG_ALERT_MULTIPLE_DOCUMENTS_FOUND % rn raise InvenioWebSubmitFunctionStop(msg) ## Everything seems to have run smoothly: ## check if the record needs to comply to any restriction ## basically checks if this record can/should be handled by this submission if parameters['record_search_pattern']: if not is_record_matching_pattern( parameters['record_search_pattern'], sysno, curdir): # delete the SN file and reset the sysno, # because this record is not the good record to be hadled by this submission rename("%s/SN" % curdir, "%s/SN_WRONG" % curdir) sysno = "" raise InvenioWebSubmitFunctionStop( CFG_ALERT_WRONG_RECORD_FOR_THIS_SUBMISSION) return ""
def User_is_Record_Owner_or_Curator(parameters, curdir, form, user_info=None): """ Check that user is either the original submitter, or that it belongs to the role(s) given as parameter. This enables collaborative editing of records, so that collections can be curated by a group of people in addition to the original submitter. If the user has permission, the function ends silently. If not, it will raise an InvenioWebSubmitFunctionStop, informing the user that they don't have rights and sending them back to the submission web form. This function makes it unnecessary to protect the submission with WebAccess (i.e. 'submit' action): the function can check authorizations by itself. However if the case the action in which this function is used is still protected with WebAccess (eg. an authorization exists for the 'submit' action, in 'MBI'), ALL the possible submitters AND the curators groups must be linked to the authorization in order for WebSubmit to let users reach this function: this function then ensures that only curators or submitters of the record will be able to continue further. A record owner must have her email in the record metadata. A record curator must be in the role given as parameter to this function. WARNING: you must remember that category-based restrictions require you to check that the selected category matches the document to modify: one can select category 'foo' to modify a document submitted in category 'bar', given that submissions are indepedendant of the record they create. WARNING: for backward compatibility reasons, if no role is given as parameter, the function simply check against the WebAccess 'submit' action, with this submission parameters. It then means that anybody connected to the authorization will be able to modify ANY of the records this submission can handle. @parameters: - curator_role: a role or mapping of roles that determine if user is a curator or not. The parameter can simply be the name of a WebAccess role. For eg: curator_photo where 'curator_photo' is a WebAccess role matching curator users for this submission. The parameter can also map the submission categories to different roles, so that different curator groups can be defined. For eg: ARTICLE=curator_art|REPORT=curator_rep|*=curator_gen (syntax: '|' to split mappings, and '=' to map category->role) This specifies that role 'curator_art' is used when category 'Article' is selected (code for this category is 'ARTICLE'), 'curator_rep' when 'Report' ('REPORT' code) is selected, and curator_gen in all other cases. * matches all categories. When defining a mapping category->role, and category cannot be retrieved (for eg. with /submit/direct URLs that do not specify category), only the * rule/role is matched. Eg: foo=role1|*=role2 matches role2 only When no role is defined or matched, the curator role is checked against the WebAccess 'submit' action, for current WebSubmit doctype, action and category. - curator_flag: the name of a file in which '1' is written if current submitter is a curator. Otherwise, an empty file is written. If no value is given, no file is written. @return: Empty string. @Exceptions raised: InvenioWebSubmitFunctionStop when user is denied permission to work with the record. """ global sysno # Get current doctype doctype_fd = open(os.path.join(curdir, 'doctype')) doctype = doctype_fd.read() doctype_fd.close() # Get current action act_fd = open(os.path.join(curdir, 'act')) act = act_fd.read() act_fd.close() # Get category. This one might not exist category = None if os.path.exists(os.path.join(curdir, 'combo%s' % doctype)): category_fd = open(os.path.join(curdir, 'combo%s' % doctype)) category = category_fd.read() category_fd.close() # Get role to belong to in order to be curator. If not specifed, # we simply check against 'submit' WebAccess action for the current # WebSubmit action (for eg. 'MBI') curator_roles = [] try: curator_role = parameters['curator_role'] except: curator_role = '' if '=' in curator_role: # Admin specifed a different role for different category. # For eg: general=curator_gen|photo=curator_photo|*=curator_other curator_roles = [categ_and_role.split('=', 1)[1].strip() \ for categ_and_role in curator_role.split('|') if \ len(categ_and_role.split('=', 1)) == 2 and \ categ_and_role.split('=', 1)[0].strip() in (category, '*')] elif curator_role: curator_roles = [curator_role] ## Get the current user's e-mail address: user_email = user_info["email"].lower() ## Now get the email address(es) of the record submitter(s)/owner(s) from ## the record itself: record_owners_list = [email.lower().strip() for email in \ get_fieldvalues(sysno, CFG_WEBSUBMIT_RECORD_OWNER_EMAIL)] ## Now determine whether this user is listed in the record as an "owner" ## (or submitter): user_has_permission = False user_msg = "" if user_email not in ("", "guest") and user_email in record_owners_list: ## This user's email address is listed in the record. She should ## be allowed to work with it: user_has_permission = True # Check if user is curator is_curator = False if curator_roles: # Check against roles for role in curator_roles: if not acc_get_role_id(role): # Role is not defined continue if acc_is_user_in_role(user_info, acc_get_role_id(role)): # One matching role found user_has_permission = True is_curator = True break else: # Check against authorization for 'submit' (for backward compatibility) (auth_code, dummy) = acc_authorize_action(user_info, \ "submit", \ verbose=0, \ doctype=doctype, \ act=act) if auth_code == 0: ## The user is a curator for this ## submission/collection. Do not prevent access. is_curator = True user_has_permission = True try: curator_flag = parameters['curator_flag'] if curator_flag: flag_fd = open(os.path.join(curdir, curator_flag), 'w') flag_fd.write(is_curator and '1' or '0') flag_fd.close() except: pass ## Finally, if the user still doesn't have permission to work with this ## record, raise an InvenioWebSubmitFunctionStop exception sending the ## user back to the form. if not user_has_permission: raise InvenioWebSubmitFunctionStop(CFG_MSG_USER_NOT_AUTHORIZED) return ""
def Ask_For_Record_Details_Confirmation(parameters, \ curdir, \ form, \ user_info=None): """ Display the details of a record on which some operation is to be carried out and prompt for the user's confirmation that it is the correct record. Upon the clicking of the confirmation button, augment step by one. Given the "recid" (001) of a record, retrieve the basic metadata (title, report-number(s) and author(s)) and display them in the user's browser along with a prompt asking them to confirm that it is indeed the record that they expected to see. The function depends upon the presence of the "sysno" global and the presence of the "step" field in the "form" parameter. When the user clicks on the "confirm" button, step will be augmented by 1 and the form will be submitted. @parameters: None. @return: None. @Exceptions raise: InvenioWebSubmitFunctionError if problems are encountered; InvenioWebSubmitFunctionStop in order to display the details of the record and the confirmation message. """ global sysno ## Make sure that we know the current step: try: current_step = int(form['step']) except TypeError: ## Can't determine step. msg = "Unable to determine submission step. Cannot continue." raise InvenioWebSubmitFunctionError(msg) else: newstep = current_step + 1 ## Make sure that the sysno is valid: try: working_recid = int(sysno) except TypeError: ## Unable to find the details of this record - cannot query the database msg = "Unable to retrieve details of record - record id was invalid." raise InvenioWebSubmitFunctionError(msg) if not record_exists(working_recid): ## Record doesn't exist. msg = "Unable to retrieve details of record [%s] - record does not " \ "exist." % working_recid raise InvenioWebSubmitFunctionError(msg) ## Retrieve the details to be displayed: ## ## Author(s): rec_authors = "" rec_first_author = print_record(int(sysno), 'tm', "100__a") rec_other_authors = print_record(int(sysno), 'tm', "700__a") if rec_first_author != "": rec_authors += "".join(["%s<br />\n" % cgi.escape(author.strip()) for \ author in rec_first_author.split("\n")]) if rec_other_authors != "": rec_authors += "".join(["%s<br />\n" % cgi.escape(author.strip()) for \ author in rec_other_authors.split("\n")]) ## Title: rec_title = "".join(["%s<br />\n" % cgi.escape(title.strip()) for title in \ print_record(int(sysno), 'tm', "245__a").split("\n")]) ## Report numbers: rec_reportnums = "" rec_reportnum = print_record(int(sysno), 'tm', "037__a") rec_other_reportnums = print_record(int(sysno), 'tm', "088__a") if rec_reportnum != "": rec_reportnums += "".join(["%s<br />\n" % cgi.escape(repnum.strip()) \ for repnum in rec_reportnum.split("\n")]) if rec_other_reportnums != "": rec_reportnums += "".join(["%s<br />\n" % cgi.escape(repnum.strip()) \ for repnum in \ rec_other_reportnums.split("\n")]) raise InvenioWebSubmitFunctionStop(CFG_DOCUMENT_DETAILS_MESSAGE % \ { 'report-numbers' : rec_reportnums, \ 'title' : rec_title, \ 'author' : rec_authors, \ 'newstep' : newstep, \ 'admin-email' : CFG_SITE_ADMIN_EMAIL, \ } )
def CaseEDS(parameters, curdir, form, user_info=None): """ This function compares the content of a file to different values and directly goes to a different step in the action according to the value. This function may be used if the treatment to be done after a submission depends on a field entered by the user. Typically this is used in an approval interface. If the referee approves then we do this. If he rejects, then we do other thing. More specifically, the function gets the value from the file named [casevariable] and compares it with the values stored in [casevalues]. If a value matches, the function directly goes to the corresponding step stored in [casesteps]. If no value is matched, it goes to step [casedefault]. @param parameters: (dictionary) of parameters (relating to the given doctype/action) that are to be passed to the function: + casevariable: This parameters contains the name of the file in which the function will get the chosen value. Eg:"decision" + casevalues: Contains the list of recognized values to match with the chosen value. Should be a comma separated list of words. Eg:"approve,reject" + casesteps: Contains the list of steps corresponding to the values matched in [casevalue]. It should be a comma separated list of numbers. Eg:"2,3" In this example, if the value stored in the file named"decision" is "approved", then the function launches step 2 of this action. If it is "reject", then step 3 is launched. + casedefault: Contains the step number to go by default if no match is found. Eg:"4" In this example, if the value stored in the file named "decision" is not "approved" nor "reject", then step 4 is launched. @return: (string) - empty string """ ## Get the values of the parameters passed to this function via the ## parameters array: casevariable = parameters['casevariable'] casevalue = parameters['casevalues'] casestep = parameters['casesteps'] casedefault = parameters['casedefault'] casevalues = casevalue.split(",") casesteps = casestep.split(",") cases = {} for a, b in map(None, casevalues, casesteps): cases[a] = b nextstep = "" if not os.path.exists("%s/%s" % (curdir, casevariable)): nextstep = casedefault else: fp = open("%s/%s" % (curdir, casevariable), "r") value = fp.read() fp.close() if cases.has_key(value): nextstep = cases[value] else: nextstep = casedefault if nextstep != "": t = "<b>Please wait...</b>" t = """ <SCRIPT LANGUAGE="JavaScript1.1"> document.forms[0].action="/submit"; document.forms[0].step.value=%s; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); </SCRIPT>""" % nextstep raise InvenioWebSubmitFunctionStop(t) else: raise InvenioWebSubmitFunctionError("Case function: Could not " \ "determine next action step") return ""
def Export_Via_SWORD(parameters, curdir, form, user_info=None): ''' This function get informations about the SWORD remote server where to export the given record. If a marcxml file is given in parameters, it use it as metadata source. If no marcxml file is given, it get the marcxml file using the given recid. If a list of file is given in parameters, it export those file. If not, it get fulltext files from the URL found in the marcxml file ''' global sysno, rn metadata = {'id_record': rn} #--------------------------------------------------------------------------- # get remote server id #--------------------------------------------------------------------------- #Path of file containing remote server id if os.path.exists("%s/%s" % (curdir, parameters['serverid'])): tmp_file = open("%s/%s" % (curdir, parameters['serverid']), "r") serverid = tmp_file.read() serverid = re.sub("[\n\r ]+", "", serverid) else: return 'Collection not found !' #--------------------------------------------------------------------------- # get collection's url and id #--------------------------------------------------------------------------- #Path of file containing primary category url if os.path.exists("%s/%s" % (curdir, parameters['collection'])): tmp_file = open("%s/%s" % (curdir, parameters['collection']), "r") col = tmp_file.read() col = re.sub("[\n\r ]+", "", col) else: return 'Collection not found !' selected_collection = {} collections = list_collections_from_server(serverid) for collection in collections: if col == collection['url']: selected_collection = collection #--------------------------------------------------------------------------- # get selected primary category url and label #--------------------------------------------------------------------------- #Path of file containing primary category url if os.path.exists("%s/%s" % (curdir, parameters['primary'])): tmp_file = open("%s/%s" % (curdir, parameters['primary']), "r") pc_from_param = tmp_file.read() pc_from_param = re.sub("[\n\r ]+", "", pc_from_param) else: return 'Primary category not found !' primary_categories = \ list_mandated_categories(str(serverid), selected_collection['id']) for primary_category in primary_categories: if pc_from_param == primary_category['url']: metadata['primary_url'] = primary_category['url'] metadata['primary_label'] = primary_category['label'] #--------------------------------------------------------------------------- # get selected secondary categories url and label (if any) #--------------------------------------------------------------------------- metadata['categories'] = [] #Path of file containing primary category url if os.path.exists("%s/%s" % (curdir, parameters['secondary'])): tmp_file = open("%s/%s" % (curdir, parameters['secondary']), "r") sc_from_param = tmp_file.read() sc_from_param = re.sub("\+", "\n", sc_from_param) list_sc_from_param = sc_from_param.split('\n') secondary_categories = \ list_optional_categories(str(serverid), selected_collection['id']) for secondary_category in secondary_categories: for sc_element in list_sc_from_param: if sc_element == secondary_category['url']: secondary = {} secondary['url'] = secondary_category['url'] secondary['label'] = secondary_category['label'] metadata['categories'].append(secondary) #--------------------------------------------------------------------------- # get the marcxml file #--------------------------------------------------------------------------- #if os.path.exists("%s/%s" % (curdir, parameters['marcxml'])): # tmp_file = open("%s/%s" % (curdir, parameters['marcxml']),"r") # marcxml = tmp_file.read() #else : marcxml = get_marcxml_from_record(sysno) #--------------------------------------------------------------------------- # get the media file #--------------------------------------------------------------------------- media_paths = [] if os.path.exists("%s/%s" % (curdir, 'media')): tmp_file = open("%s/%s" % (curdir, 'media'), "r") path_medias_from_file = tmp_file.read() path_medias_list = re.sub("\+", "\n", path_medias_from_file) media_paths = path_medias_from_file.split("\n") if os.path.exists("%s/%s" % (curdir, 'DEMOSWR_UPLOAD')): tmp_file = open("%s/%s" % (curdir, 'DEMOSWR_UPLOAD'), "r") uploaded_file = tmp_file.read() path_uploaded_media = re.sub("\+", "\n", uploaded_file) media_paths.append("%s/files/DEMOSWR_UPLOAD/%s" % (curdir, path_uploaded_media.split('\n')[0])) temp_file = open('/tmp/result.txt', 'w') for media_path in media_paths: temp_file.write(media_path) #--------------------------------------------------------------------------- # format user infos #--------------------------------------------------------------------------- user = {} user['id'] = user_info['uid'] user['nickname'] = user_info['nickname'] user['email'] = user_info['email'] result = perform_submission_process(serverid, selected_collection['url'], sysno, user, metadata, media_paths, marcxml) if result['error'] == '': bibsword_templates = BibSwordTemplate() return bibsword_templates.tmpl_display_submit_ack( result['remote_id'], result['links']) else: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 2; user_must_confirm_before_leaving_page = false; document.forms[0].submit(); alert('%s'); </SCRIPT>""" % result['error']) return ""
def Withdraw_Approval_Request(parameters, curdir, form, user_info=None): """ This function is used in a "withdraw approval request" submission in order to register the withdral of the request in the WebSubmit "Approvals" DB (sbmAPPROVAL). At the time of the approval request withdrawal, the document could be in one of several different approval "states" and depending upon that state, the action taken by this function differs. The states are as follows: * Approval of the document has previously been requested and it is still in the "waiting" state. -> In this case, the status of the document in the sbmAPPROVAL table is set to "withdrawn". * Approval for the document has never been requested. -> In this case, there is nothing to do. * Approval of the document has previously been requested, but the document was rejected. -> In this case, it's too late to withdraw the approval request and there is nothing left to do. * Approval of the document has previously been requested and it has been approved. -> In this case, it's too late to withdraw the approval request and there is nothing left to do. * Approval of the document has previously been requested, but the request withdrawn. -> In this case, there is nothing to do. @param categ_file_withd: (string) - some document types are separated into different categories, each of which has its own referee(s). In such document types, it's necessary to know the document- type's category in order to choose the referee. This parameter provides a means by which the category information can be extracted from a file in the current submission's working directory. It should therefore be a filename. @param categ_rnseek_withd: (string) - some document types are separated into different categories, each of which has its own referee(s). In such document types, it's necessary to know the document- type's category in order to choose the referee. This parameter provides a means by which the category information can be extracted from the document's reference number. It is infact a string that will be compiled into a regexp and an attempt will be made to match it agains the document's reference number starting from the left-most position. The only pre-requisite is that the segment in which the category is sought should be indicated with <CATEGORY>. Thus, an example might be as follows: ATL(-COM)?-<CATEGORY>-.+ This would allow "PHYS" in the following reference number to be recognised as the category: ATL-COM-PHYS-2008-001 @return: (string) - a message for the user. @Exceptions raised: + InvenioWebSubmitFunctionStop when the submission should be halted. + InvenioWebSubmitFunctionError when an unexpected error has been encountered and execution cannot continue. """ ## Get the reference number (as global rn - sorry!) and the document type: global rn doctype = form['doctype'] ## A string variable to contain any information that should be displayed ## in the user's browser: info_out = "" ######## ## Get the parameters from the list: ######## ## Get the name of the category file: ####### try: ## If it has been provided, get the name of the file in which the ## category is stored: category_file = parameters["categ_file_withd"] except KeyError: ## No value given for the category file: category_file = None else: if category_file is not None: category_file = str(category_file) category_file = os.path.basename(category_file).strip() if category_file == "": category_file = None ######## ## Get the regexp that is used to find the category in the report number: ######## try: ## If it has been provided, get the regexp used for identifying ## a document-type's category from its reference number: category_rn_regexp = parameters["categ_rnseek_withd"] except KeyError: ## No value given for the category regexp: category_rn_regexp = None else: if category_rn_regexp is not None: category_rn_regexp = str(category_rn_regexp).strip() if category_rn_regexp == "": category_rn_regexp = None ####### ## Resolve the document type's category: ## ## This is a long process. The end result is that the category is extracted ## either from a file in curdir, or from the report number. ## If it's taken from the report number, the admin must configure the ## function to accept a regular expression that is used to find the ## category in the report number. ## if category_file is not None and category_rn_regexp is not None: ## It is not valid to have both a category file and a pattern ## describing how to extract the category from a report number. ## raise an InvenioWebSubmitFunctionError msg = "Error in Withdraw_Approval_Request function: received " \ "instructions to search for the document's category in " \ "both its report number AND in a category file. Could " \ "not determine which to use - please notify " \ "%(suppt-email)s." \ % { 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL), } raise InvenioWebSubmitFunctionError(msg) elif category_file is not None: ## Attempt to recover the category information from a file in the ## current submission's working directory: category = ParamFromFile("%s/%s" % (curdir, category_file)) if category is not None: category = category.strip() if category in (None, ""): ## The category cannot be resolved. msg = "Error in Withdraw_Approval_Request function: received " \ "instructions to search for the document's category in " \ "a category file, but could not recover the category " \ "from that file. The approval request therefore cannot " \ "be withdrawn for the document. Please report this " \ "problem to %(suppt-email)s." \ % { 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL), } raise InvenioWebSubmitFunctionError(msg) elif category_rn_regexp is not None: ## Attempt to recover the category information from the document's ## reference number using the regexp in category_rn_regexp: ## ## Does the category regexp contain the key-phrase "<CATEG>"? if category_rn_regexp.find("<CATEG>") != -1: ## Yes. Replace "<CATEG>" with "(?P<category>.+?)". ## For example, this: ## ATL(-COM)?-<CATEG>- ## Will be transformed into this: ## ATL(-COM)?-(?P<category>.+?)- category_rn_final_regexp = \ category_rn_regexp.replace("<CATEG>", r"(?P<category>.+?)", 1) else: ## The regexp for category didn't contain "<CATEG>", but this is ## mandatory. msg = "Error in Withdraw_Approval_Request function: The " \ "[%(doctype)s] submission has been configured to search " \ "for the document type's category in its reference number, " \ "using a poorly formed search expression (no marker for " \ "the category was present.) Since the document's category " \ "therefore cannot be retrieved, its approval request " \ "cannot be withdrawn. Please report this problem to " \ "%(suppt-email)s." \ % { 'doctype' : cgi.escape(doctype), 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL), } raise InvenioWebSubmitFunctionError(msg) ## try: ## Attempt to compile the regexp for finding the category: re_categ_from_rn = re.compile(category_rn_final_regexp) except sre_constants.error: ## The expression passed to this function could not be compiled ## into a regexp. Register this exception and raise an ## InvenioWebSubmitFunctionError: exception_prefix = "Error in Withdraw_Approval_Request function: " \ "The [%(doctype)s] submission has been " \ "configured to search for the document type's " \ "category in its reference number, using the " \ "following regexp: /%(regexp)s/. This regexp, " \ "however, could not be compiled correctly " \ "(created it from %(categ-search-term)s.)" \ % { 'doctype' : doctype, \ 'regexp' : category_rn_final_regexp, \ 'categ-search-term' : category_rn_regexp, } register_exception(prefix=exception_prefix) msg = "Error in Withdraw_Approval_Request function: The " \ "[%(doctype)s] submission has been configured to search " \ "for the document type's category in its reference number, " \ "using a poorly formed search expression. Since the " \ "document's category therefore cannot be retrieved, its " \ "approval request cannot be withdrawn. Please " \ "report this problem to %(suppt-email)s." \ % { 'doctype' : cgi.escape(doctype), 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL), } raise InvenioWebSubmitFunctionError(msg) else: ## Now attempt to recover the category from the RN string: m_categ_from_rn = re_categ_from_rn.match(rn) if m_categ_from_rn is not None: ## The pattern matched in the string. ## Extract the category from the match: try: category = m_categ_from_rn.group("category") except IndexError: ## There was no "category" group. That group is mandatory. exception_prefix = \ "Error in Withdraw_Approval_Request function: The " \ "[%(doctype)s] submission has been configured to " \ "search for the document type's category in its " \ "reference number using the following regexp: " \ "/%(regexp)s/. The search produced a match, but " \ "there was no \"category\" group in the match " \ "object although this group is mandatory. The " \ "regexp was compiled from the following string: " \ "[%(categ-search-term)s]." \ % { 'doctype' : doctype, \ 'regexp' : category_rn_final_regexp, \ 'categ-search-term' : category_rn_regexp, } register_exception(prefix=exception_prefix) msg = "Error in Withdraw_Approval_Request function: The " \ "[%(doctype)s] submission has been configured to " \ "search for the document type's category in its " \ "reference number, using a poorly formed search " \ "expression (there was no category marker). Since " \ "the document's category therefore cannot be " \ "retrieved, its approval request cannot be " \ "withdrawn. Please report this problem to " \ "%(suppt-email)s." \ % { 'doctype' : cgi.escape(doctype), 'suppt-email' : \ cgi.escape(CFG_SITE_SUPPORT_EMAIL),} raise InvenioWebSubmitFunctionError(msg) else: category = category.strip() if category == "": msg = "Error in Withdraw_Approval_Request function: " \ "The [%(doctype)s] submission has been " \ "configured to search for the document type's " \ "category in its reference number, but no " \ "category was found. The request for approval " \ "cannot be withdrawn. Please report this " \ "problem to %(suppt-email)s." \ % { 'doctype' : cgi.escape(doctype), 'suppt-email' : \ cgi.escape(CFG_SITE_SUPPORT_EMAIL),} raise InvenioWebSubmitFunctionError(msg) else: ## No match. Cannot find the category and therefore cannot ## continue: msg = "Error in Withdraw_Approval_Request function: The " \ "[%(doctype)s] submission has been configured to " \ "search for the document type's category in its " \ "reference number, but no match was made. The request " \ "for approval cannot be withdrawn. Please report " \ "this problem to %(suppt-email)s." \ % { 'doctype' : cgi.escape(doctype), 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL),} raise InvenioWebSubmitFunctionError(msg) else: ## The document type has no category. category = "" ## ## End of category recovery ####### ####### ## ## Query the "approvals" DB table to determine whether approval of this ## document has already been requested: approval_status = get_simple_approval_status(doctype, rn) if approval_status is None: ## Approval has never been requested for this document. ## One cannot withdraw an approval request that was never made. msg = """ <br /> <div> <span style="color: red;">Note:</span> A request for the approval of the document [%s] has never been made.<br /> There is nothing to do. </div> """ % cgi.escape(rn) raise InvenioWebSubmitFunctionStop(msg) elif approval_status.lower() == "approved": ## This document has already been approved. It's too late to withdraw ## the approval request. msg = """ <br /> <div> <span style="color: red;">Note:</span> The document [%s] has already been approved.<br /> It is too late to withdraw the approval request.<br /> If you believe this to be an error, please contact %s, quoting the<br /> document's report-number [%s] and describing the problem. </div> """ % (cgi.escape(rn), cgi.escape(CFG_SITE_SUPPORT_EMAIL), cgi.escape(rn)) raise InvenioWebSubmitFunctionStop(msg) elif approval_status.lower() == "rejected": ## This document has already been rejected. It's too late to withdraw ## the approval request. msg = """ <br /> <div> <span style="color: red;">Note:</span> The document [%s] has already been rejected.<br /> It is too late to withdraw the approval request.<br /> If you believe this to be an error, please contact %s, quoting the<br /> document's report-number [%s] and describing the problem. </div> """ % (cgi.escape(rn), cgi.escape(CFG_SITE_SUPPORT_EMAIL), cgi.escape(rn)) raise InvenioWebSubmitFunctionStop(msg) elif approval_status.lower() == "withdrawn": ## The approval request for this document has already been withdrawn. msg = """ <br /> <div> <span style="color: red;">Note:</span> The approval request for the document [%s] has already been withdrawn.<br /> There is nothing to do. </div> """ % cgi.escape(rn) raise InvenioWebSubmitFunctionStop(msg) elif approval_status.lower() == "waiting": ## Mark the approval request as withdrawn: note = "Withdrawn by [%s]: %s\n#####\n" \ % (cgi.escape(user_info['email']), \ cgi.escape(time.strftime("%d/%m/%Y %H:%M:%S", \ time.localtime()))) update_approval_request_status(doctype, \ rn, \ note=note, \ status="withdrawn") info_out += """ <br /> <div> The approval request for the document [%s] has been withdrawn. </div> """ % cgi.escape(rn) else: ## The document had an unrecognised "status". Raise an error. msg = "Error in Withdraw_Approval_Request function: The " \ "[%(reportnum)s] document has an unknown approval status " \ "(%(status)s). Unable to withdraw the request for its " \ "approval. Please report this problem to the %(suppt-email)s." \ % { 'reportnum' : cgi.escape(rn), 'status' : cgi.escape(approval_status), 'suppt-email' : cgi.escape(CFG_SITE_SUPPORT_EMAIL), } raise InvenioWebSubmitFunctionError(msg) ## ## Finished - return any message to be displayed on the user's screen. return info_out
def DEMOVID_Validation(parameters, curdir, form, user_info=None): """ """ messages = [] malformed = False file_storing_path = os.path.join(curdir, "files", str(user_info['uid']), "NewFile", 'filepath') file_storing_name = os.path.join(curdir, "files", str(user_info['uid']), "NewFile", 'filename') file_storing_aspect = os.path.join(curdir, "DEMOVID_ASPECT") file_storing_title = os.path.join(curdir, "DEMOVID_TITLE") file_storing_description = os.path.join(curdir, "DEMOVID_DESCR") file_storing_author = os.path.join(curdir, "DEMOVID_AU") file_storing_year = os.path.join(curdir, "DEMOVID_YEAR") ## Validate the uploaded video try: fp = open(file_storing_path) fullpath = fp.read() fp.close() fp = open(file_storing_name) filename = fp.read() fp.close() if not probe(fullpath) or os.path.splitext(filename)[1] in [ 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'png', 'tga' ]: malformed = True messages.append( "The uploaded file is not a supported video format.") except: malformed = True messages.append("Please upload a video.") ## Validate the title try: fp = open(file_storing_title) title = fp.read() fp.close() if len(title) < 2 or len(title) > 50: malformed = True messages.append( "The title is too short, please enter at least 2 characters.") except: malformed = True messages.append("Please enter a title.") ## Validate the description try: fp = open(file_storing_description) description = fp.read() fp.close() if len(description) < 10: malformed = True messages.append( "The description must be at least 10 characters long.") except: malformed = True messages.append("Please enter a description.") ## Validate author try: fp = open(file_storing_author) author = fp.read() fp.close() except: malformed = True messages.append("Please enter at least one author.") ## Validate year try: fp = open(file_storing_year) year = fp.read() fp.close() except: malformed = True messages.append("Please enter a year.") try: if int(year) < 1000 or int(year) > 9999: malformed = True messages.append( "Please enter a valid year. It must consist of 4 digits.") except: malformed = True messages.append( "Please enter a valid year. It must consist of 4 digits.") ## Validate the aspect ratio try: fp = open(file_storing_aspect) aspect = fp.read() fp.close() try: aspectx, aspecty = aspect.split(':') aspectx = int(aspectx) aspecty = int(aspecty) except: malformed = True messages.append( "Aspect ratio was not provided as 'Number:Number' format") except: malformed = True messages.append("Please enter an aspect ratio.") if malformed: raise InvenioWebSubmitFunctionStop(""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; alert('%s'); document.forms[0].submit(); </SCRIPT>""" % "\\n".join(messages)) else: return
def Register_Referee_Decision(parameters, curdir, form, user_info=None): """ A referee may either "accept" or "reject" a refereed document. The referee's decision is stored in a file in the submission's working directory and it is this function's job to read the contents of that file and update the status of the document's entry in the approvals table (sbmAPPROVAL) to be either "accepted" or "rejected" depending upon the referee's decision. @param decision_file: (string) - the name of the file in which the referee's decision is to be found. NOTE: A referee's decision _MUST_ be either "accept" or "reject". If not, an InvenioWebSubmitFunctionError will be raised. If a document's "approval status" is not "waiting" at the time of the referee's decision, the decision will not be taken into account and the submission will be halted. (This is because it's not appropriate to approve a document that has already been approved or rejected, has been withdrawn, etc.) @return: empty string. @Exceptions raised: InvenioWebSubmitFunctionError on unexpected error. InvenioWebSubmitFunctionStop in the case where the approval should be stopped for whatever reason. (E.g. when it has already been approved.) """ global rn doctype = form['doctype'] ######## ## Get the parameters from the list: ######## ## Get the name of the "decision" file and read its value: ######## decision = "" ## variable to hold the referee's decision try: decision_file = parameters["decision_file"] except KeyError: ## No value given for the decision file: decision_file = None else: if decision_file is not None: decision_file = os.path.basename(decision_file).strip() if decision_file == "": decision_file = None if decision_file is None: ## Unable to obtain the name of the file in which the referee's ## decision is stored. Halt. err_msg = "Error in Register_Referee_Decision: Function was not " \ "configured with a valid value for decision_file - the " \ "file in which the referee's decision is stored. " \ "The referee's decision has not been processed for " \ "[%s]. Please inform the administrator." \ % rn raise InvenioWebSubmitFunctionError(err_msg) ## Read in the referee's decision: decision = ParamFromFile("%s/%s" % (curdir, decision_file)).lower() ## ######## if decision not in ("approve", "reject"): ## Invalid value for the referee's decision. err_msg = "Error in Register_Referee_Decision: The value for the " \ "referee's decision (%s) was invalid. Please inform the " \ "administrator." % decision raise InvenioWebSubmitFunctionError(err_msg) ## ## Get the status of the approval request for this document from the DB: document_status = get_simple_approval_status(doctype, rn) if document_status is None: ## No information about this document in the approval database. ## Its approval has never been requested. msg = """ <br /> <div> <span style="color: red;">Note:</span> No details about an approval request for the document [%s] have been found in the database.<br /> Before a decision can be made about it, a request for its approval must have been submitted.<br /> If you feel that there is a problem, please contact <%s>, quoting the document's report number. </div>""" % (cgi.escape(rn), cgi.escape(CFG_SITE_SUPPORT_EMAIL)) raise InvenioWebSubmitFunctionStop(msg) elif document_status in ("approved", "rejected"): ## If a document was already approved or rejected, halt the approval ## process with a message for the referee: msg = """ <br /> <div> <span style="color: red;">Note:</span> The document [%s] has already been %s.<br /> There is nothing more to be done in this case and your decision has <b>NOT</b> been taken into account.<br /> If you believe this to be an error, please contact <%s>, quoting the<br /> document's report-number [%s] and describing the problem. </div>""" % (cgi.escape(rn), \ cgi.escape(document_status), \ cgi.escape(CFG_SITE_SUPPORT_EMAIL), \ cgi.escape(rn)) raise InvenioWebSubmitFunctionStop(msg) elif document_status == "withdrawn": ## Somebody had withdrawn the approval request for this document ## before the referee made this decision. Halt the approval process ## with a message for the referee: msg = """ <br /> <div> <span style="color: red;">Note:</span> The request for the approval of the document [%s] had been withdrawn prior to the submission of your decision.<br /> Before a decision can be made regarding its status, a new request for its approval must be submitted by the author.<br /> Your decision has therefore <b>NOT</b> been taken into account.<br /> If you believe this to be an error, please contact <%s>, quoting the document's report-number [%s] and describing the problem. </div> """ % (cgi.escape(rn), \ cgi.escape(CFG_SITE_SUPPORT_EMAIL), \ cgi.escape(rn)) raise InvenioWebSubmitFunctionStop(msg) elif document_status == "waiting": ## The document is awaiting approval. Register the referee's decision: if decision == "approve": ## Register the approval: update_approval_request_status(doctype, \ rn, \ note="", status="approved") else: ## Register the rejection: update_approval_request_status(doctype, \ rn, \ note="", status="rejected") ## Now retrieve the status of the document once more and check that ## it is either approved or rejected. If not, the decision couldn't ## be registered and an error should be raised. status_after_update = get_simple_approval_status(doctype, rn) if status_after_update not in ("approved", "rejected"): msg = "Error in Register_Referee_Decision function: It was " \ "not possible to update the approvals database when " \ "trying to register the referee's descision of [%s] " \ "for the document [%s]. Please report this this " \ "problem to [%s], quoting the document's " \ "report-number [%s]." \ % (decision, rn, CFG_SITE_SUPPORT_EMAIL, rn) raise InvenioWebSubmitFunctionError(msg) else: ## The document had an unrecognised "status". Halt with an error. msg = "Error in Register_Referee_Decision function: The " \ "document [%s] has an unknown approval status " \ "[%s]. Unable to process the referee's decision. Please " \ "report this problem to [%s], quoting the document's " \ "report-number [%s] and describing the problem." \ % (rn, document_status, CFG_SITE_SUPPORT_EMAIL, rn) raise InvenioWebSubmitFunctionError(msg) ## Finished. return ""
def User_is_Record_Owner_or_Curator(parameters, curdir, form, user_info=None): """ Check that user is either the original submitter, or that it has been granted access to carry out the action via Webaccess. This enables collaborative editing of records, so that collections can be curated by a group of people in addition to the original submitter. If the user has permission, the function ends silently. If not, it will raise an InvenioWebSubmitFunctionStop, informing the user that they don't have rights and sending them back to the submission web form. Note that the original author must also be authorized by WebAccess in order to modify the record. WARNING: you have to understand that wherever you use this function, any user authorized via WebAccess for this action will be able to modify any records that can go through this workflow. For eg. when using this function in a DEMOPIC submission, in a 'MBI' action, it is enough that a user is connected to the 'submit' action with the 'DEMOPIC/MBI' parameters to modify any record. @parameters: None. @return: Empty string. @Exceptions raised: InvenioWebSubmitFunctionStop when user is denied permission to work with the record. """ global sysno ## Get the document type and action from the form. They can be used to ## ask webaccess whether the user is a super-user for this doctype/action. doctype = form['doctype'] act = form['act'] ## Get the current user's e-mail address: user_email = user_info["email"].lower() ## Now get the email address(es) of the record submitter(s)/owner(s) from ## the record itself: record_owners = print_record(sysno, 'tm', \ [CFG_WEBSUBMIT_RECORD_OWNER_EMAIL]).strip() if record_owners != "": record_owners_list = record_owners.split("\n") record_owners_list = [email.lower().strip() \ for email in record_owners_list] else: record_owners_list = [] ## Now determine whether this user is listed in the record as an "owner" ## (or submitter): user_has_permission = False user_msg = "" if user_email not in ("", "guest") and user_email in record_owners_list: ## This user's email address is listed in the record. She should ## be allowed to work with it: user_has_permission = True if not user_has_permission: ## The user isn't listed in the record. ## Using WebAccess, test if she is a "curator" for this submission: (auth_code, dummy) = acc_authorize_action(user_info, \ "submit", \ verbose=0, \ doctype=doctype, \ act=act) if auth_code == 0: ## The user is a curator for this submission/collection. Do not ## prevent access. user_has_permission = True ## Finally, if the user still doesn't have permission to work with this ## record, raise an InvenioWebSubmitFunctionStop exception sending the ## user back to the form. if not user_has_permission: raise InvenioWebSubmitFunctionStop(CFG_MSG_USER_NOT_AUTHORIZED) return ""