コード例 #1
0
def visit_for_stamping(visit_for_stamping_arguments, dirname, filenames):
    """Visitor function called by os.path.walk.
       This function takes a directory and a list of files in that directory
       and for each file, calls the websubmit_file_stamper on it.
       When a file is stamped, the original is moved away into a directory
       of unstamped files and the new, stamped version is moved into its
       place.
       @param visit_for_stamping_arguments: (dictionary) of arguments needed
        by this function. Must contain 'curdir', 'user_info' and
        'file_stamper_options' members.
       @param dirname: (string) - the path to the directory in which the
        files are to be stamped.
       @param filenames: (list) - the names of each file in dirname. An
        attempt will be made to stamp each of these files.
       @Exceptions Raised:
         + InvenioWebSubmitFunctionWarning;
         + InvenioWebSubmitFunctionError;
    """
    ## Get the dictionary of options to pass to the stamper:
    file_stamper_options = visit_for_stamping_arguments['file_stamper_options']

    ## Create a directory to store original files before stamping:
    dirname_files_pre_stamping = dirname.replace("/files/", \
                                                 "/files_before_stamping/", 1)
    if not os.path.exists(dirname_files_pre_stamping):
        try:
            os.makedirs(dirname_files_pre_stamping)
        except OSError, err:
            ## Unable to make a directory in which to store the unstamped
            ## files.
            ## Register the exception:
            exception_prefix = "Unable to stamp files in [%s]. Couldn't " \
                               "create directory in which to store the " \
                               "original, unstamped files." \
                               % dirname
            register_exception(prefix=exception_prefix)
            ## Since we can't make a directory for the unstamped files,
            ## we can't continue to stamp them.
            ## Skip the stamping of the contents of this directory by raising
            ## a warning:
            msg = "Warning: A problem occurred when stamping files in [%s]. " \
                  "Unable to create directory to store the original, " \
                  "unstamped files. Got this error: [%s]. This means the " \
                  "files in this directory were not stamped." \
                  % (dirname, str(err))
            raise InvenioWebSubmitFunctionWarning(msg)
コード例 #2
0
def Stamp_Replace_Single_File_Approval(parameters, \
                                       curdir, \
                                       form, \
                                       user_info=None):
    """
    This function is intended to be called when a document has been
    approved and needs to be stamped.
    The function should be used when there is ONLY ONE file to be
    stamped after approval (for example, the "main file").
    The name of the file to be stamped should be known and should be stored
    in a file in the submission's working directory (without the extension).
    Generally, this will work our fine as the main file is named after the
    report number of the document, this will be stored in the report number
    file.

    @param parameters: (dictionary) - must contain:

         + latex_template: (string) - the name of the LaTeX template that
            should be used for the creation of the stamp.

         + latex_template_vars: (string) - a string-ified dictionary
            of variables to be replaced in the LaTeX template and the
            values (or names of files in curdir containing the values)
            with which to replace them. Use prefix 'FILE:' to specify
            that the stamped value must be read from a file in
            submission directory instead of being a fixed value to
            stamp.
            E.G.:
               { 'TITLE' : 'FILE:DEMOTHESIS_TITLE',
                 'DATE'  : 'FILE:DEMOTHESIS_DATE'
               }

         + file_to_be_stamped: (string) - this is the name of a file in the
            submission's working directory that contains the name of the
            bibdocfile that is to be stamped.

         + new_file_name: (string) - this is the name of a file in the
            submission's working directory that contains the name that is to
            be given to the file after it has been stamped. If empty, or if
            that file doesn't exist, the file will not be renamed after
            stamping.

         + switch_file: (string) - when this value is set, specifies
            the name of a file that will swith on/off the
            stamping. The stamp will be applied if the file exists in
            the submission directory and is not empty. If the file
            cannot be found or is empty, the stamp is not applied.
            Useful for eg. if you want to let your users control the
            stamping with a checkbox on your submission page.
            Leave this parameter empty to always stamp by default.

         + stamp: (string) - the type of stamp to be applied to the file.
            should be one of:
              + first (only the first page is stamped);
              + all (all pages are stamped);
              + coverpage (a separate cover-page is added to the file as a
                 first page);

         + layer: (string) - the position of the stamp. Should be one of:
              + background (invisible if original file has a white
                -not transparent- background layer)
              + foreground (on top of the stamped file.  If the stamp
                does not have a transparent background, will hide all
                of the document layers)
           The default value is 'background'.
    """
    ############
    ## Definition of important variables:
    ############
    ## The file stamper needs to be called with a dictionary of options of
    ## the following format:
    ##  { 'latex-template'      : "", ## TEMPLATE_NAME
    ##    'latex-template-var'  : {}, ## TEMPLATE VARIABLES
    ##    'input-file'          : "", ## INPUT FILE
    ##    'output-file'         : "", ## OUTPUT FILE
    ##    'stamp'               : "", ## STAMP TYPE
    ##    'layer'               : "", ## LAYER TO STAMP
    ##    'verbosity'           : 0,  ## VERBOSITY (we don't care about it)
    ##  }
    file_stamper_options = {
        'latex-template': "",
        'latex-template-var': {},
        'input-file': "",
        'output-file': "",
        'stamp': "",
        'layer': "",
        'verbosity': 0,
    }

    ## Check if stamping is enabled
    switch_file = parameters.get('switch_file', '')
    if switch_file:
        # Good, a "switch file" was specified. Check if it exists, and
        # it its value is not empty.
        if not _read_in_file(os.path.join(curdir, switch_file)):
            # File does not exist, or is emtpy. Silently abort
            # stamping.
            return ""

    ## Submission access number:
    access = _read_in_file("%s/access" % curdir)
    ## record ID for the current submission. It is found in the special file
    ## "SN" (sysno) in curdir:
    recid = _read_in_file("%s/SN" % curdir)
    try:
        recid = int(recid)
    except ValueError:
        ## No record ID. Cannot continue.
        err_msg = "Error in Stamp_Replace_Single_File_Approval: " \
                  "Cannot recover record ID from the submission's working " \
                  "directory. Stamping cannot be carried out. The " \
                  "submission ID is [%s]." % cgi.escape(access)
        register_exception(prefix=err_msg)
        raise InvenioWebSubmitFunctionError(err_msg)
    ############
    ## Resolution of function parameters:
    ############
    ## The name of the LaTeX template to be used for stamp creation:
    latex_template = "%s" % ((type(parameters['latex_template']) is str \
                              and parameters['latex_template']) or "")
    ## A string containing the variables/values that should be substituted
    ## in the final (working) LaTeX template:
    latex_template_vars_string = "%s" % \
                       ((type(parameters['latex_template_vars']) is str \
                         and parameters['latex_template_vars']) or "")
    ## The type of stamp to be applied to the file(s):
    stamp = "%s" % ((type(parameters['stamp']) is str and \
                     parameters['stamp'].lower()) or "")
    ## The layer to use for stamping:
    try:
        layer = parameters['layer']
    except KeyError:
        layer = "background"
    if not layer in ('background', 'foreground'):
        layer = "background"
    ## Get the name of the file to be stamped from the file indicated in
    ## the file_to_be_stamped parameter:
    try:
        file_to_stamp_file = parameters['file_to_be_stamped']
    except KeyError:
        file_to_stamp_file = ""
    else:
        if file_to_stamp_file is None:
            file_to_stamp_file = ""
    ## Get the "basename" for the file to be stamped (it's mandatory that it
    ## be in curdir):
    file_to_stamp_file = os.path.basename(file_to_stamp_file).strip()
    name_file_to_stamp = _read_in_file("%s/%s" % (curdir, file_to_stamp_file))
    name_file_to_stamp.replace("\n", "").replace("\r", "")
    ##
    ## Get the name to be given to the file after it has been stamped (if there
    ## is one.) Once more, it will be found in a file in curdir:
    try:
        new_file_name_file = parameters['new_file_name']
    except KeyError:
        new_file_name_file = ""
    else:
        if new_file_name_file is None:
            new_file_name_file = ""
    ## Get the "basename" for the file containing the new file name. (It's
    ## mandatory that it be in curdir):
    new_file_name_file = os.path.basename(new_file_name_file).strip()
    new_file_name = _read_in_file("%s/%s" % (curdir, new_file_name_file))

    ############
    ## Begin:
    ############
    ##
    ## If no name for the file to stamp, warning.
    if name_file_to_stamp == "":
        wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                  "It was not possible to recover a valid name for the " \
                  "file to be stamped. Stamping could not, therefore, be " \
                  "carried out. The submission ID is [%s]." \
                  % access
        raise InvenioWebSubmitFunctionWarning(wrn_msg)
    ##
    ## The file to be stamped is a bibdoc. We will only stamp it (a) if it
    ## exists; and (b) if it is a PDF file. So, get the path (in the bibdocs
    ## tree) to the file to be stamped:
    ##
    ## First get the object representing the bibdocs belonging to this record:
    bibrecdocs = BibRecDocs(recid)
    try:
        bibdoc_file_to_stamp = bibrecdocs.get_bibdoc("%s" % name_file_to_stamp)
    except InvenioBibDocFileError:
        ## Couldn't get a bibdoc object for this filename. Probably the file
        ## that we wanted to stamp wasn't attached to this record.
        wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                  "It was not possible to recover a bibdoc object for the " \
                  "filename [%s] when trying to stamp the main file. " \
                  "Stamping could not be carried out. The submission ID is " \
                  "[%s] and the record ID is [%s]." \
                  % (name_file_to_stamp, access, recid)
        register_exception(prefix=wrn_msg)
        raise InvenioWebSubmitFunctionWarning(wrn_msg)
    ## Get the BibDocFile object for the PDF version of the bibdoc to be
    ## stamped:
    try:
        bibdocfile_file_to_stamp = bibdoc_file_to_stamp.get_file("pdf")
    except InvenioBibDocFileError:
        ## This bibdoc doesn't have a physical file with the extension ".pdf"
        ## (take note of the lower-case extension - the bibdocfile library
        ## is case-sensitive with respect to filenames.  Log that there was
        ## no "pdf" and check for a file with extension "PDF":
        wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                  "It wasn't possible to recover a PDF BibDocFile object " \
                  "for the file with the name [%s], using the extension " \
                  "[pdf] - note the lower case - the bibdocfile library " \
                  "relies upon the case of an extension. The submission ID " \
                  "is [%s] and the record ID is [%s]. Going to try " \
                  "looking for a file with a [PDF] extension before giving " \
                  "up . . . " \
                  % (name_file_to_stamp, access, recid)
        register_exception(prefix=wrn_msg)
        try:
            bibdocfile_file_to_stamp = bibdoc_file_to_stamp.get_file("PDF")
        except InvenioBibDocFileError:
            wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                      "It wasn't possible to recover a PDF " \
                      "BibDocFile object for the file with the name [%s], " \
                      "using the extension [PDF] - note the upper case. " \
                      "Had previously tried searching for [pdf] - now " \
                      "giving up. Stamping could not be carried out. " \
                      "The submission ID is [%s] and the record ID is [%s]." \
                      % (name_file_to_stamp, access, recid)
            register_exception(prefix=wrn_msg)
            raise InvenioWebSubmitFunctionWarning(wrn_msg)
    ############
    ## Go ahead and prepare the details for the LaTeX stamp template and its
    ## variables:
    ############
    ## Strip the LaTeX filename into the basename (All templates should be
    ## in the template repository):
    latex_template = os.path.basename(latex_template)

    ## Convert the string of latex template variables into a dictionary
    ## of search-term/replacement-term pairs:
    latex_template_vars = get_dictionary_from_string(
        latex_template_vars_string)
    ## For each of the latex variables, check in `CURDIR' for a file with that
    ## name. If found, use it's contents as the template-variable's value.
    ## If not, just use the raw value string already held by the template
    ## variable:
    latex_template_varnames = latex_template_vars.keys()
    for varname in latex_template_varnames:
        ## Get this variable's value:
        varvalue = latex_template_vars[varname].strip()
        if not ((varvalue.find("date(") == 0 and varvalue[-1] == ")") or \
                (varvalue.find("include(") == 0 and varvalue[-1] == ")")) \
                and varvalue != "":
            ## We don't want to interfere with date() or include() directives,
            ## so we only do this if the variable value didn't contain them:
            ##
            ## Is this variable value the name of a file in the current
            ## submission's working directory, from which a literal value for
            ## use in the template should be extracted? If yes, it will
            ## begin with "FILE:". If no, we leave the value exactly as it is.
            if varvalue.upper().find("FILE:") == 0:
                ## The value to be used is to be taken from a file. Clean the
                ## file name and if it's OK, extract that value from the file.
                ##
                seekvalue_fname = varvalue[5:].strip()
                seekvalue_fname = os.path.basename(seekvalue_fname).strip()
                if seekvalue_fname != "":
                    ## Attempt to extract the value from the file:
                    if os.access("%s/%s" % (curdir, seekvalue_fname), \
                                 os.R_OK|os.F_OK):
                        ## The file exists. Extract its value:
                        try:
                            repl_file_val = \
                              open("%s/%s" \
                                   % (curdir, seekvalue_fname), "r").readlines()
                        except IOError:
                            ## The file was unreadable.
                            err_msg = "Error in Stamp_Replace_Single_File_" \
                                      "Approval: The function attempted to " \
                                      "read a LaTex template variable " \
                                      "value from the following file in the " \
                                      "current submission's working " \
                                      "directory: [%s]. However, an " \
                                      "unexpected error was encountered " \
                                      "when doing so. Please inform the " \
                                      "administrator." \
                                      % seekvalue_fname
                            register_exception(req=user_info['req'])
                            raise InvenioWebSubmitFunctionError(err_msg)
                        else:
                            final_varval = ""
                            for line in repl_file_val:
                                final_varval += line
                            final_varval = final_varval.rstrip()
                            ## Replace the variable value with that which has
                            ## been read from the file:
                            latex_template_vars[varname] = final_varval
                    else:
                        ## The file didn't actually exist in the current
                        ## submission's working directory. Use an empty
                        ## value:
                        latex_template_vars[varname] = ""
                else:
                    ## The filename was not valid.
                    err_msg = "Error in Stamp_Replace_Single_File_Approval: " \
                              "The function was configured to read a LaTeX " \
                              "template variable from a file with the " \
                              "following instruction: [%s --> %s]. The " \
                              "filename, however, was not considered valid. " \
                              "Please report this to the administrator." \
                              % (varname, varvalue)
                    raise InvenioWebSubmitFunctionError(err_msg)

    ## Put the 'fixed' values into the file_stamper_options dictionary:
    file_stamper_options['latex-template'] = latex_template
    file_stamper_options['latex-template-var'] = latex_template_vars
    file_stamper_options['stamp'] = stamp
    file_stamper_options['layer'] = layer

    ## Put the input file and output file into the file_stamper_options
    ## dictionary:
    file_stamper_options['input-file'] = bibdocfile_file_to_stamp.fullpath
    file_stamper_options[
        'output-file'] = bibdocfile_file_to_stamp.get_full_name()
    ##
    ## Before attempting to stamp the file, log the dictionary of arguments
    ## that will be passed to websubmit_file_stamper:
    try:
        fh_log = open("%s/websubmit_file_stamper-calls-options.log" \
                      % curdir, "a+")
        fh_log.write("%s\n" % file_stamper_options)
        fh_log.flush()
        fh_log.close()
    except IOError:
        ## Unable to log the file stamper options.
        exception_prefix = "Unable to write websubmit_file_stamper " \
                           "options to log file " \
                           "%s/websubmit_file_stamper-calls-options.log" \
                           % curdir
        register_exception(prefix=exception_prefix)

    try:
        ## Try to stamp the file:
        (stamped_file_path_only, stamped_file_name) = \
                websubmit_file_stamper.stamp_file(file_stamper_options)
    except InvenioWebSubmitFileStamperError:
        ## It wasn't possible to stamp this file.
        ## Register the exception along with an informational message:
        wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                  "There was a problem stamping the file with the name [%s] " \
                  "and the fullpath [%s]. The file has not been stamped. " \
                  "The submission ID is [%s] and the record ID is [%s]." \
                  % (name_file_to_stamp, \
                     file_stamper_options['input-file'], \
                     access, \
                     recid)
        register_exception(prefix=wrn_msg)
        raise InvenioWebSubmitFunctionWarning(wrn_msg)
    else:
        ## Stamping was successful. The BibDocFile must now be revised with
        ## the latest (stamped) version of the file:
        file_comment = "Stamped by WebSubmit: %s" \
                       % time.strftime("%d/%m/%Y", time.localtime())
        try:
            dummy = \
                  bibrecdocs.add_new_version("%s/%s" \
                                             % (stamped_file_path_only, \
                                                stamped_file_name), \
                                                name_file_to_stamp, \
                                                comment=file_comment, \
                                                flags=('STAMPED', ))
        except InvenioBibDocFileError:
            ## Unable to revise the file with the newly stamped version.
            wrn_msg = "Warning in Stamp_Replace_Single_File_Approval: " \
                      "After having stamped the file with the name [%s] " \
                      "and the fullpath [%s], it wasn't possible to revise " \
                      "that file with the newly stamped version. Stamping " \
                      "was unsuccessful. The submission ID is [%s] and the " \
                      "record ID is [%s]." \
                      % (name_file_to_stamp, \
                         file_stamper_options['input-file'], \
                         access, \
                         recid)
            register_exception(prefix=wrn_msg)
            raise InvenioWebSubmitFunctionWarning(wrn_msg)
        else:
            ## File revised. If the file should be renamed after stamping,
            ## do so.
            if new_file_name != "":
                try:
                    bibrecdocs.change_name(newname=new_file_name,
                                           docid=bibdoc_file_to_stamp.id)
                except (IOError, InvenioBibDocFileError):
                    ## Unable to change the name
                    wrn_msg = "Warning in Stamp_Replace_Single_File_Approval" \
                              ": After having stamped and revised the file " \
                              "with the name [%s] and the fullpath [%s], it " \
                              "wasn't possible to rename it to [%s]. The " \
                              "submission ID is [%s] and the record ID is " \
                              "[%s]." \
                              % (name_file_to_stamp, \
                                 file_stamper_options['input-file'], \
                                 new_file_name, \
                                 access, \
                                 recid)
    ## Finished.
    return ""
コード例 #3
0
def Mail_Approval_Withdrawn_to_Referee(parameters, \
                                       curdir, \
                                       form, \
                                       user_info=None):
    """
    This function sends an email to the referee of a document informing
    him/her that the request for its approval has been withdrawn.

    @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) - empty string.
    """
    ## Get the reference number (as global rn - sorry!) and the document type:
    global sysno, rn
    doctype = form['doctype']

    ########
    ## 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 InvenioWebSubmitFunctionWarning:
        msg = "Error in Mail_Approval_Withdrawn_to_Referee 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 the " \
              "administrator."
        raise InvenioWebSubmitFunctionWarning(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 Mail_Approval_Withdrawn_to_Referee function: " \
                  "received instructions to search for the document's " \
                  "category in a category file, but could not recover the " \
                  "category from that file. The referee cannot be notified " \
                  "of the approval request withdrawal by mail."
            raise InvenioWebSubmitFunctionWarning(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 Mail_Approval_Withdrawn_to_Referee 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 " \
                  "cannot be retrieved, the referee cannot be " \
                  "notified of the approval request withdrawal by mail." \
                  % { 'doctype' : doctype, }
            raise InvenioWebSubmitFunctionWarning(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
            ## InvenioWebSubmitFunctionWarning:
            exception_prefix = "Error in Mail_Approval_Withdrawn_to_Referee " \
                               "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 Mail_Approval_Withdrawn_to_Referee 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 cannot be retrieved, the referee" \
                  "cannot be notified of the approval request withdrawal by " \
                  "mail." \
                  % { 'doctype' : doctype, }
            raise InvenioWebSubmitFunctionWarning(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 Mail_Approval_Withdrawn_to_Referee " \
                       "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 Mail_Approval_Withdrawn_to_Referee " \
                          "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, the referee cannot be " \
                          "notified of the approval request withdrawal " \
                          "by mail." \
                          % { 'doctype' : doctype, }
                    raise InvenioWebSubmitFunctionWarning(msg)
                else:
                    category = category.strip()
                    if category == "":
                        msg = "Error in Mail_Approval_Withdrawn_to_Referee " \
                              "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 referee cannot be " \
                              "notified of the approval request withdrawal " \
                              "by mail." \
                              % { 'doctype' : doctype, }
                        raise InvenioWebSubmitFunctionWarning(msg)
            else:
                ## No match. Cannot find the category and therefore cannot
                ## continue:
                msg = "Error in Mail_Approval_Withdrawn_to_Referee 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 referee " \
                      "cannot be notified of the approval request " \
                      "withdrawal by mail." \
                      % { 'doctype' : doctype, }
                raise InvenioWebSubmitFunctionWarning(msg)
    else:
        ## The document type has no category.
        category = ""
    ##
    ## End of category recovery
    #######

    ## Get the referee email address:
    if CFG_CERN_SITE:
        ## The referees system in CERN now works with listbox membership.
        ## List names should take the format
        ## "*****@*****.**"
        ## Make sure that your list exists!
        ## FIXME - to be replaced by a mailing alias in webaccess in the
        ## future.
        ## see if was a PROC request or not
        notes = get_approval_request_notes(doctype, rn)
        was_proc = 'n'
        was_slide = 'n'
        if notes:
            note_lines = notes.split('\n')
            for note_line in note_lines:
                if note_line.find('Requested Note Classification:') == 0:
                    note_type = note_line.split()[-1]
                    if note_type == 'PROC':
                        was_proc = 'y'
                    elif note_type == 'SLIDE':
                        was_slide = 'y'
                    break  # there may be more than one - just take the first
        if was_proc == 'y':
            referee_listname = "service-cds-referee-%s" % doctype.lower()
            referee_listname += "-%s" % 'proc'
        elif was_slide == 'y':
            referee_listname = "atlas-speakers-comm"
        else:
            referee_listname = "service-cds-referee-%s" % doctype.lower()
            if category != "":
                referee_listname += "-%s" % category.lower()
        referee_listname += "@cern.ch"
        mailto_addresses = referee_listname
        if category == 'CDSTEST':  ## our special testing category
            referee_listname = "service-cds-referee-%s" % doctype.lower()
            referee_listname += "-%s" % category.lower()
            mailto_addresses = referee_listname + "@cern.ch"
    else:
        referee_address = ""
        ## Try to retrieve the referee's email from the referee's database:
        for user in \
            acc_get_role_users(acc_get_role_id("referee_%s_%s" \
                                               % (doctype, category))):
            referee_address += user[1] + ","
        ## And if there are general referees:
        for user in \
            acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
            referee_address += user[1] + ","
        referee_address = re.sub(",$", "", referee_address)
        # Creation of the mail for the referee
        mailto_addresses = ""
        if referee_address != "":
            mailto_addresses = referee_address + ","
        else:
            mailto_addresses = re.sub(",$", "", mailto_addresses)
    ##
    ## Send the email:
    mail_subj = "Request for approval of [%s] withdrawn" % rn
    mail_body = CFG_MAIL_BODY % \
                { 'site-name'               : CFG_SITE_NAME,
                  'report-number'           : rn,
                }
    send_email(CFG_SITE_SUPPORT_EMAIL,
               mailto_addresses,
               mail_subj,
               mail_body,
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    ##
    return ""
コード例 #4
0
def Move_Files_to_Storage(parameters, curdir, form, user_info=None):
    """
    The function moves files received from the standard submission's
    form through file input element(s). The document are assigned a
    'doctype' (or category) corresponding to the file input element
    (eg. a file uploaded throught 'DEMOPIC_FILE' will go to
    'DEMOPIC_FILE' doctype/category).

    Websubmit engine builds the following file organization in the
    directory curdir/files:

                  curdir/files
                        |
      _____________________________________________________________________
            |                                   |                          |
      ./file input 1 element's name      ./file input 2 element's name    ....
         (for eg. 'DEMOART_MAILFILE')       (for eg. 'DEMOART_APPENDIX')
         |                                     |
      test1.pdf                             test2.pdf


    There is only one instance of all possible extension(pdf, gz...) in each part
    otherwise we may encounter problems when renaming files.

    + parameters['rename']: if given, all the files in curdir/files
      are renamed.  parameters['rename'] is of the form:
      <PA>elemfilename[re]</PA>* where re is an regexp to select(using
      re.sub) what part of the elem file has to be selected.
      e.g: <PA>file:TEST_FILE_RN</PA>

    + parameters['documenttype']: if given, other formats are created.
      It has 2 possible values: - if "picture" icon in gif format is created
                                - if "fulltext" ps, gz .... formats are created

    + parameters['paths_and_suffixes']: directories to look into and
      corresponding suffix to add to every file inside. It must have
      the same structure as a Python dictionnary of the following form
      {'FrenchAbstract':'french', 'EnglishAbstract':''}

      The keys are the file input element name from the form <=>
      directories in curdir/files The values associated are the
      suffixes which will be added to all the files in
      e.g. curdir/files/FrenchAbstract

    + parameters['iconsize'] need only if 'icon' is selected in
      parameters['documenttype']

    + parameters['paths_and_restrictions']: the restrictions to apply
      to each uploaded file. The parameter must have the same
      structure as a Python dictionnary of the following form:
      {'DEMOART_APPENDIX':'restricted'}
      Files not specified in this parameter are not restricted.
      The specified restrictions can include a variable that can be
      replaced at runtime, for eg:
      {'DEMOART_APPENDIX':'restricted to <PA>file:SuE</PA>'}

    + parameters['paths_and_doctypes']: if a doctype is specified,
      the file will be saved under the 'doctype/collection' instead
      of under the default doctype/collection given by the name
      of the upload element that was used on the websubmit interface.
      to configure the doctype in websubmit, enter the value as in a
      dictionnary, for eg:
      {'PATHS_SWORD_UPL' : 'PUSHED_TO_ARXIV'} -> from
      Demo_Export_Via_Sword [DEMOSWR] Document Types
    """

    global sysno
    paths_and_suffixes = parameters['paths_and_suffixes']
    paths_and_restrictions = parameters['paths_and_restrictions']
    rename = parameters['rename']
    documenttype = parameters['documenttype']
    iconsizes = parameters['iconsize'].split(',')
    paths_and_doctypes = parameters['paths_and_doctypes']

    ## Create an instance of BibRecDocs for the current recid(sysno)
    bibrecdocs = BibRecDocs(sysno)

    paths_and_suffixes = get_dictionary_from_string(paths_and_suffixes)

    paths_and_restrictions = get_dictionary_from_string(paths_and_restrictions)

    paths_and_doctypes = get_dictionary_from_string(paths_and_doctypes)

    ## Go through all the directories specified in the keys
    ## of parameters['paths_and_suffixes']
    for path in paths_and_suffixes.keys():
        ## Check if there is a directory for the current path
        if os.path.exists("%s/files/%s" % (curdir, path)):
            ## Retrieve the restriction to apply to files in this
            ## directory
            restriction = paths_and_restrictions.get(path, '')
            restriction = re.sub('<PA>(?P<content>[^<]*)</PA>',
                                 get_pa_tag_content, restriction)

            ## Go through all the files in curdir/files/path
            for current_file in os.listdir("%s/files/%s" % (curdir, path)):
                ## retrieve filename and extension
                dummy, filename, extension = decompose_file(current_file)
                if extension and extension[0] != ".":
                    extension = '.' + extension
                if len(paths_and_suffixes[path]) != 0:
                    extension = "_%s%s" % (paths_and_suffixes[path], extension)
                ## Build the new file name if rename parameter has been given
                if rename:
                    filename = re.sub('<PA>(?P<content>[^<]*)</PA>', \
                                      get_pa_tag_content, \
                                      parameters['rename'])

                if rename or len(paths_and_suffixes[path]) != 0:
                    ## Rename the file
                    try:
                        # Write the log rename_cmd
                        fd = open("%s/rename_cmd" % curdir, "a+")
                        fd.write("%s/files/%s/%s" % (curdir, path, current_file) + " to " +\
                                  "%s/files/%s/%s%s" % (curdir, path, filename, extension) + "\n\n")
                        ## Rename
                        os.rename("%s/files/%s/%s" % (curdir, path, current_file), \
                                  "%s/files/%s/%s%s" % (curdir, path, filename, extension))

                        fd.close()
                        ## Save the new name in a text file in curdir so that
                        ## the new filename can be used by templates to created the recmysl
                        fd = open("%s/%s_RENAMED" % (curdir, path), "w")
                        fd.write("%s%s" % (filename, extension))
                        fd.close()
                    except OSError, err:
                        msg = "Cannot rename the file.[%s]"
                        msg %= str(err)
                        raise InvenioWebSubmitFunctionWarning(msg)
                fullpath = "%s/files/%s/%s%s" % (curdir, path, filename,
                                                 extension)
                ## Check if there is any existing similar file
                if not bibrecdocs.check_file_exists(fullpath):
                    bibdoc = bibrecdocs.add_new_file(
                        fullpath,
                        doctype=paths_and_doctypes.get(path, path),
                        never_fail=True)
                    bibdoc.set_status(restriction)
                    ## Fulltext
                    if documenttype == "fulltext":
                        additionalformats = createRelatedFormats(fullpath)
                        if len(additionalformats) > 0:
                            for additionalformat in additionalformats:
                                try:
                                    bibrecdocs.add_new_format(additionalformat)
                                except InvenioWebSubmitFileError:
                                    pass
                    ## Icon
                    elif documenttype == "picture":
                        has_added_default_icon_subformat_p = False
                        for iconsize in iconsizes:
                            try:
                                iconpath, iconname = create_icon({
                                    'input-file':
                                    fullpath,
                                    'icon-scale':
                                    iconsize,
                                    'icon-name':
                                    None,
                                    'icon-file-format':
                                    None,
                                    'multipage-icon':
                                    False,
                                    'multipage-icon-delay':
                                    100,
                                    'verbosity':
                                    0,
                                })
                            except Exception, e:
                                register_exception(
                                    prefix=
                                    'Impossible to create icon for %s (record %s)'
                                    % (fullpath, sysno),
                                    alert_admin=True)
                                continue
                            iconpath = os.path.join(iconpath, iconname)
                            docname = decompose_file(fullpath)[1]
                            try:
                                mybibdoc = bibrecdocs.get_bibdoc(docname)
                            except InvenioWebSubmitFileError:
                                mybibdoc = None
                            if iconpath is not None and mybibdoc is not None:
                                try:
                                    icon_suffix = iconsize.replace(
                                        '>', '').replace('<', '').replace(
                                            '^', '').replace('!', '')
                                    if not has_added_default_icon_subformat_p:
                                        mybibdoc.add_icon(iconpath)
                                        has_added_default_icon_subformat_p = True
                                    else:
                                        mybibdoc.add_icon(
                                            iconpath,
                                            subformat=
                                            CFG_WEBSUBMIT_DEFAULT_ICON_SUBFORMAT
                                            + "-" + icon_suffix)
                                    ## Save the new icon filename in a text file in curdir so that
                                    ## it can be used by templates to created the recmysl
                                    try:
                                        if not has_added_default_icon_subformat_p:
                                            fd = open(
                                                "%s/%s_ICON" % (curdir, path),
                                                "w")
                                        else:
                                            fd = open(
                                                "%s/%s_ICON_%s" %
                                                (curdir, path,
                                                 iconsize + '_' + icon_suffix),
                                                "w")
                                        fd.write(os.path.basename(iconpath))
                                        fd.close()
                                    except OSError, err:
                                        msg = "Cannot store icon filename.[%s]"
                                        msg %= str(err)
                                        raise InvenioWebSubmitFunctionWarning(
                                            msg)
                                except InvenioWebSubmitFileError, e:
                                    # Most probably icon already existed.
                                    pass
                            elif mybibdoc is not None:
                                mybibdoc.delete_icon()