Exemplo n.º 1
0
def email_alert(mapper, connection, target):
    """ Sends email alerts to message recipients. """
    from invenio.ext.template import render_template_to_string
    from invenio.ext.email import send_email, scheduled_send_email
    m = target
    is_reminder =  m.received_date is not None \
                   and m.received_date > datetime.now()

    alert = send_email
    if is_reminder:
        alert = lambda *args, **kwargs: scheduled_send_email(*args,
                    other_bibtasklet_arguments=[
                        m.received_date.strftime(datetext_format)],
                    **kwargs)

    for u in m.recipients:
        if isinstance(u.settings, dict) and \
            u.settings.get('webmessage_email_alert', True):
            try:
                alert(
                    cfg['CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL'],
                    u.email,
                    subject = m.subject,
                    content = render_template_to_string(
                            'messages/email_alert.html',
                            message=m, user=u))
            except:
                # FIXME tests are not in request context
                pass
Exemplo n.º 2
0
def email_alert(mapper, connection, target):
    """ Sends email alerts to message recipients. """
    from invenio.ext.template import render_template_to_string
    from invenio.ext.email import send_email, scheduled_send_email
    m = target
    is_reminder =  m.received_date is not None \
                   and m.received_date > datetime.now()

    alert = send_email
    if is_reminder:
        alert = lambda *args, **kwargs: scheduled_send_email(
            *args,
            other_bibtasklet_arguments=
            [m.received_date.strftime(datetext_format)],
            **kwargs)

    for u in m.recipients:
        if isinstance(u.settings, dict) and \
            u.settings.get('webmessage_email_alert', True):
            try:
                alert(cfg['CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL'],
                      u.email,
                      subject=m.subject,
                      content=render_template_to_string(
                          'messages/email_alert.html', message=m, user=u))
            except:
                # FIXME tests are not in request context
                pass
Exemplo n.º 3
0
    def subscribe(self, user):
        """Subscribe a user to a group (done by users).

        Wrapper around ``add_member()`` which checks subscription policy.

        :param user: User to subscribe.
        :returns: Newly created Membership or None.
        """
        if self.subscription_policy == SubscriptionPolicy.OPEN:
            return self.add_member(user)
        elif self.subscription_policy == SubscriptionPolicy.APPROVAL:
            email_body = render_template_to_string(
                'groups/join_group_email.txt',
                group=self,
            )
            subject = 'New Group Request at LifeWatch Open Science Framework'
            to = [User.query.get(a.admin_id).email for a in self.admins]
            scheduled_send_email(fromaddr=cfg['CFG_SITE_ADMIN_EMAIL'],
                                 toaddr=to,
                                 subject=subject,
                                 content=email_body)
            return self.add_member(user, state=MembershipState.PENDING_ADMIN)
        elif self.subscription_policy == SubscriptionPolicy.CLOSED:
            return None
Exemplo n.º 4
0
    def subscribe(self, user):
        """Subscribe a user to a group (done by users).

        Wrapper around ``add_member()`` which checks subscription policy.

        :param user: User to subscribe.
        :returns: Newly created Membership or None.
        """
        if self.subscription_policy == SubscriptionPolicy.OPEN:
            return self.add_member(user)
        elif self.subscription_policy == SubscriptionPolicy.APPROVAL:
            email_body = render_template_to_string(
                'groups/join_group_email.txt',
                group=self,
            )
            subject = 'New Group Request at LifeWatch Open Science Framework'
            to = [User.query.get(a.admin_id).email for a in self.admins]
            scheduled_send_email(fromaddr=cfg['CFG_SITE_ADMIN_EMAIL'],
                                 toaddr=to,
                                 subject=subject,
                                 content=email_body)
            return self.add_member(user, state=MembershipState.PENDING_ADMIN)
        elif self.subscription_policy == SubscriptionPolicy.CLOSED:
            return None
Exemplo n.º 5
0
def Send_APP_Mail(parameters, curdir, form, user_info=None):
    """
    This function send an email informing the original submitter of a
    document that the referee has approved/ rejected the document. The
    email is also sent to the referee for checking.

    Parameters:

       * addressesAPP: email addresses of the people who will receive
         this email (comma separated list). this parameter may contain
         the <CATEG> string. In which case the variable computed from
         the [categformatAFP] parameter replaces this string.
         eg.: "<CATEG>[email protected]"

       * categformatAPP contains a regular expression used to compute
         the category of the document given the reference of the
         document.
         eg.: if [categformatAFP]="TEST-<CATEG>-.*" and the reference
         of the document is "TEST-CATEGORY1-2001-001", then the computed
         category equals "CATEGORY1"

       * newrnin: Name of the file containing the 2nd reference of the
                  approved document (if any).

       * edsrn: Name of the file containing the reference of the
                approved document.
    """
    global titlevalue, authorvalue, emailvalue, sysno, rn
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)
    sequence_id = bibtask_allocate_sequenceid(curdir)
    doctype = form['doctype']
    titlevalue = titlevalue.replace("\n", " ")
    authorvalue = authorvalue.replace("\n", "; ")
    # variables declaration
    categformat = parameters['categformatAPP']
    otheraddresses = parameters['addressesAPP']
    newrnpath = parameters['newrnin']
    ## Get the name of the decision file:
    try:
        decision_filename = parameters['decision_file']
    except KeyError:
        decision_filename = ""
    ## Get the name of the comments file:
    try:
        comments_filename = parameters['comments_file']
    except KeyError:
        comments_filename = ""

    ## Now try to read the comments from the comments_filename:
    if comments_filename in (None, "", "NULL"):
        ## We don't have a name for the comments file.
        ## For backward compatibility reasons, try to read the comments from
        ## a file called 'COM' in curdir:
        if os.path.exists("%s/COM" % curdir):
            try:
                fh_comments = open("%s/COM" % curdir, "r")
                comment = fh_comments.read()
                fh_comments.close()
            except IOError:
                ## Unable to open the comments file
                exception_prefix = "Error in WebSubmit function " \
                                   "Send_APP_Mail. Tried to open " \
                                   "comments file [%s/COM] but was " \
                                   "unable to." % curdir
                register_exception(prefix=exception_prefix)
                comment = ""
            else:
                comment = comment.strip()
        else:
            comment = ""
    else:
        ## Try to read the comments from the comments file:
        if os.path.exists("%s/%s" % (curdir, comments_filename)):
            try:
                fh_comments = open("%s/%s" % (curdir, comments_filename), "r")
                comment = fh_comments.read()
                fh_comments.close()
            except IOError:
                ## Oops, unable to open the comments file.
                comment = ""
                exception_prefix = "Error in WebSubmit function " \
                                "Send_APP_Mail. Tried to open comments " \
                                "file [%s/%s] but was unable to." \
                                % (curdir, comments_filename)
                register_exception(prefix=exception_prefix)
            else:
                comment = comment.strip()
        else:
            comment = ""

    ## Now try to read the decision from the decision_filename:
    if decision_filename in (None, "", "NULL"):
        ## We don't have a name for the decision file.
        ## For backward compatibility reasons, try to read the decision from
        ## a file called 'decision' in curdir:
        if os.path.exists("%s/decision" % curdir):
            try:
                fh_decision = open("%s/decision" % curdir, "r")
                decision = fh_decision.read()
                fh_decision.close()
            except IOError:
                ## Unable to open the decision file
                exception_prefix = "Error in WebSubmit function " \
                                   "Send_APP_Mail. Tried to open " \
                                   "decision file [%s/decision] but was " \
                                   "unable to." % curdir
                register_exception(prefix=exception_prefix)
                decision = ""
            else:
                decision = decision.strip()
        else:
            decision = ""
    else:
        ## Try to read the decision from the decision file:
        try:
            fh_decision = open("%s/%s" % (curdir, decision_filename), "r")
            decision = fh_decision.read()
            fh_decision.close()
        except IOError:
            ## Oops, unable to open the decision file.
            decision = ""
            exception_prefix = "Error in WebSubmit function " \
                               "Send_APP_Mail. Tried to open decision " \
                               "file [%s/%s] but was unable to." \
                               % (curdir, decision_filename)
            register_exception(prefix=exception_prefix)
        else:
            decision = decision.strip()

    if os.path.exists("%s/%s" % (curdir, newrnpath)):
        fp = open("%s/%s" % (curdir, newrnpath), "r")
        newrn = fp.read()
        fp.close()
    else:
        newrn = ""
    # Document name
    res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s",
                  (doctype, ))
    docname = res[0][0]
    # retrieve category
    categformat = categformat.replace("<CATEG>", "([^-]*)")
    m_categ_search = re.match(categformat, rn)
    if m_categ_search is not None:
        if len(m_categ_search.groups()) > 0:
            ## Found a match for the category of this document. Get it:
            category = m_categ_search.group(1)
        else:
            ## This document has no category.
            category = "unknown"
    else:
        category = "unknown"
    ## 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.
        referee_listname = "service-cds-referee-%s" % doctype.lower()
        if category != "":
            referee_listname += "-%s" % category.lower()
        referee_listname += "@cern.ch"
        addresses = referee_listname
    else:
        # Build referee's email address
        refereeaddress = ""
        # 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))):
            refereeaddress += user[1] + ","
        # And if there is a general referee
        for user in acc_get_role_users(
                acc_get_role_id("referee_%s_*" % doctype)):
            refereeaddress += user[1] + ","
        refereeaddress = re.sub(",$", "", refereeaddress)
        # Creation of the mail for the referee
        otheraddresses = otheraddresses.replace("<CATEG>", category)
        addresses = ""
        if refereeaddress != "":
            addresses = refereeaddress + ","
        if otheraddresses != "":
            addresses += otheraddresses
        else:
            addresses = re.sub(",$", "", addresses)
    ## Add the record's submitter(s) into the list of recipients:
    ## 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:
        #if the record owner can not be retrieved from the metadata
        #(in case the record has not been inserted yet),
        #try to use the global variable emailvalue
        try:
            record_owners_list = [emailvalue]
        except NameError:
            record_owners_list = []
    record_owners = ",".join([owner for owner in record_owners_list])
    if record_owners != "":
        addresses += ",%s" % record_owners

    if decision == "approve":
        mailtitle = "%s has been approved" % rn
        mailbody = "The %s %s has been approved." % (docname, rn)
        mailbody += "\nIt will soon be accessible here:\n\n<%s/%s/%s>" % (
            CFG_SITE_URL, CFG_SITE_RECORD, sysno)
    else:
        mailtitle = "%s has been rejected" % rn
        mailbody = "The %s %s has been rejected." % (docname, rn)
    if rn != newrn and decision == "approve" and newrn != "":
        mailbody += "\n\nIts new reference number is: %s" % newrn
    mailbody += "\n\nTitle: %s\n\nAuthor(s): %s\n\n" % (titlevalue,
                                                        authorvalue)
    if comment != "":
        mailbody += "Comments from the referee:\n%s\n" % comment
    # Send mail to referee if any recipients or copy to admin
    if addresses or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN:
        scheduled_send_email(
            FROMADDR,
            addresses,
            mailtitle,
            mailbody,
            copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,
            other_bibtasklet_arguments=['-I', str(sequence_id)])
    return ""
Exemplo n.º 6
0
def Send_APP_Mail (parameters, curdir, form, user_info=None):
    """
    This function send an email informing the original submitter of a
    document that the referee has approved/ rejected the document. The
    email is also sent to the referee for checking.

    Parameters:

       * addressesAPP: email addresses of the people who will receive
         this email (comma separated list). this parameter may contain
         the <CATEG> string. In which case the variable computed from
         the [categformatAFP] parameter replaces this string.
         eg.: "<CATEG>[email protected]"

       * categformatAPP contains a regular expression used to compute
         the category of the document given the reference of the
         document.
         eg.: if [categformatAFP]="TEST-<CATEG>-.*" and the reference
         of the document is "TEST-CATEGORY1-2001-001", then the computed
         category equals "CATEGORY1"

       * newrnin: Name of the file containing the 2nd reference of the
                  approved document (if any).

       * edsrn: Name of the file containing the reference of the
                approved document.
    """
    global titlevalue,authorvalue, emailvalue,sysno,rn
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
    sequence_id = bibtask_allocate_sequenceid(curdir)
    doctype = form['doctype']
    titlevalue = titlevalue.replace("\n"," ")
    authorvalue = authorvalue.replace("\n","; ")
    # variables declaration
    categformat = parameters['categformatAPP']
    otheraddresses = parameters['addressesAPP']
    newrnpath = parameters['newrnin']
    ## Get the name of the decision file:
    try:
        decision_filename = parameters['decision_file']
    except KeyError:
        decision_filename = ""
    ## Get the name of the comments file:
    try:
        comments_filename = parameters['comments_file']
    except KeyError:
        comments_filename = ""

    ## Now try to read the comments from the comments_filename:
    if comments_filename in (None, "", "NULL"):
        ## We don't have a name for the comments file.
        ## For backward compatibility reasons, try to read the comments from
        ## a file called 'COM' in curdir:
        if os.path.exists("%s/COM" % curdir):
            try:
                fh_comments = open("%s/COM" % curdir, "r")
                comment = fh_comments.read()
                fh_comments.close()
            except IOError:
                ## Unable to open the comments file
                exception_prefix = "Error in WebSubmit function " \
                                   "Send_APP_Mail. Tried to open " \
                                   "comments file [%s/COM] but was " \
                                   "unable to." % curdir
                register_exception(prefix=exception_prefix)
                comment = ""
            else:
                comment = comment.strip()
        else:
            comment = ""
    else:
        ## Try to read the comments from the comments file:
        if os.path.exists("%s/%s" % (curdir, comments_filename)):
            try:
                fh_comments = open("%s/%s" % (curdir, comments_filename), "r")
                comment = fh_comments.read()
                fh_comments.close()
            except IOError:
                ## Oops, unable to open the comments file.
                comment = ""
                exception_prefix = "Error in WebSubmit function " \
                                "Send_APP_Mail. Tried to open comments " \
                                "file [%s/%s] but was unable to." \
                                % (curdir, comments_filename)
                register_exception(prefix=exception_prefix)
            else:
                comment = comment.strip()
        else:
            comment = ""

    ## Now try to read the decision from the decision_filename:
    if decision_filename in (None, "", "NULL"):
        ## We don't have a name for the decision file.
        ## For backward compatibility reasons, try to read the decision from
        ## a file called 'decision' in curdir:
        if os.path.exists("%s/decision" % curdir):
            try:
                fh_decision = open("%s/decision" % curdir, "r")
                decision = fh_decision.read()
                fh_decision.close()
            except IOError:
                ## Unable to open the decision file
                exception_prefix = "Error in WebSubmit function " \
                                   "Send_APP_Mail. Tried to open " \
                                   "decision file [%s/decision] but was " \
                                   "unable to." % curdir
                register_exception(prefix=exception_prefix)
                decision = ""
            else:
                decision = decision.strip()
        else:
            decision = ""
    else:
        ## Try to read the decision from the decision file:
        try:
            fh_decision = open("%s/%s" % (curdir, decision_filename), "r")
            decision = fh_decision.read()
            fh_decision.close()
        except IOError:
            ## Oops, unable to open the decision file.
            decision = ""
            exception_prefix = "Error in WebSubmit function " \
                               "Send_APP_Mail. Tried to open decision " \
                               "file [%s/%s] but was unable to." \
                               % (curdir, decision_filename)
            register_exception(prefix=exception_prefix)
        else:
            decision = decision.strip()

    if os.path.exists("%s/%s" % (curdir,newrnpath)):
        fp = open("%s/%s" % (curdir,newrnpath) , "r")
        newrn = fp.read()
        fp.close()
    else:
        newrn = ""
    # Document name
    res = run_sql("SELECT ldocname FROM sbmDOCTYPE WHERE sdocname=%s", (doctype,))
    docname = res[0][0]
    # retrieve category
    categformat = categformat.replace("<CATEG>", "([^-]*)")
    m_categ_search = re.match(categformat, rn)
    if m_categ_search is not None:
        if len(m_categ_search.groups()) > 0:
            ## Found a match for the category of this document. Get it:
            category = m_categ_search.group(1)
        else:
            ## This document has no category.
            category = "unknown"
    else:
        category = "unknown"
    ## 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.
        referee_listname = "service-cds-referee-%s" % doctype.lower()
        if category != "":
            referee_listname += "-%s" % category.lower()
        referee_listname += "@cern.ch"
        addresses = referee_listname
    else:
        # Build referee's email address
        refereeaddress = ""
        # 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))):
            refereeaddress += user[1] + ","
        # And if there is a general referee
        for user in acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
            refereeaddress += user[1] + ","
        refereeaddress = re.sub(",$","",refereeaddress)
        # Creation of the mail for the referee
        otheraddresses = otheraddresses.replace("<CATEG>",category)
        addresses = ""
        if refereeaddress != "":
            addresses = refereeaddress + ","
        if otheraddresses != "":
            addresses += otheraddresses
        else:
            addresses = re.sub(",$","",addresses)
    ## Add the record's submitter(s) into the list of recipients:
    ## 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:
        #if the record owner can not be retrieved from the metadata
        #(in case the record has not been inserted yet), 
        #try to use the global variable emailvalue
        try:
            record_owners_list = [emailvalue]
        except NameError:
            record_owners_list = []
    record_owners = ",".join([owner for owner in record_owners_list])
    if record_owners != "":
        addresses += ",%s" % record_owners

    if decision == "approve":
        mailtitle = "%s has been approved" % rn
        mailbody = "The %s %s has been approved." % (docname,rn)
        mailbody += "\nIt will soon be accessible here:\n\n<%s/%s/%s>" % (CFG_SITE_URL,CFG_SITE_RECORD,sysno)
    else:
        mailtitle = "%s has been rejected" % rn
        mailbody = "The %s %s has been rejected." % (docname,rn)
    if rn != newrn and decision == "approve" and newrn != "":
        mailbody += "\n\nIts new reference number is: %s" % newrn
    mailbody += "\n\nTitle: %s\n\nAuthor(s): %s\n\n" % (titlevalue,authorvalue)
    if comment != "":
        mailbody += "Comments from the referee:\n%s\n" % comment
    # Send mail to referee if any recipients or copy to admin
    if addresses or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN:
        scheduled_send_email(FROMADDR, addresses, mailtitle, mailbody,
                             copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,
                             other_bibtasklet_arguments=['-I', str(sequence_id)])
    return ""
Exemplo n.º 7
0
def Mail_New_Record_Notification(parameters, curdir, form, user_info=None):
    """
    This function sends a mail giving notification about the submission
    of a new item to the relevant recipients, including:
       + The record's Submitter(s);
       + The site ADMIN;
       + The record-type's "managers" (signified by the "submit_managers"
           parameter);

    The mail contains details of the new item's reference number(s), its
    title and its author(s). It also contains a link to the item in the
    Invenio repository.

    @param parameters: (dictionary) - contains the following parameter
         strings used by this function:

          + item_status: (string) - the status of the new item. It can be
            either "ADDED" (in which case the new item has been integrated
            into the repository), or "APPROVAL" (in which case the item is
            awaiting a referee's approval before being integrated into the
            repository, and the mail should state this fact);

          + mail_submitters: (string) - a flag containing "Y" or "N" (defaulting
            to "Y"). Determines whether or not the notification mail will be
            sent to the submitters;

          + item_managers:    (string) - a comma-separated list of email
            addresses, each of which corresponds to a "manager" for the class
            of item that has been submitted. These managers will receive the
            notification message sent by this function;

          + author_file: (string) - the name of a file that contains the names
            of the item's authors (one author per line);

          + title_file:  (string) - the name of a file that contains the title
            of the new item;

          + owners_file: (string) - the name of a file that contains the email
            addresses of the "owners" of the submitted item. I.e. those who
            will be classed as "submitters" of the item and will therefore
            have modification rights over it. The mail will be sent to these
            people. There should be one email-address per line in this file;

          + rn_file1: (string) - the name of the the file containing the item's
            principal reference number;

          + rn_file2: (string) - the name of the file containing the item's
            additional reference number(s) (e.g. sometimes two reference numbers
            are allocated during the submission process;

       @param curdir: (string) - the current submission's working directory. All
        files containing data related to the submission are stored here and
        therefore all of the files referred to in the "parameters" dictionary
        are considered to be within "curdir";

       @param form: (string) - a dictionary-like structure containing the fields
        that were present in the WebSubmit submission form;

       @return: (string) - an empty string;
    """
    global sysno ## (I'm really sorry for that! :-O )
    sequence_id = bibtask_allocate_sequenceid(curdir)
    ## Read items from the parameters array into local vars:
    item_status     = parameters["item_status"]
    mail_submitters = parameters["mail_submitters"]
    item_managers   = parameters["item_managers"]
    author_file     = parameters["author_file"]
    title_file      = parameters["title_file"]
    owners_file     = parameters["owners_file"]
    rn_file1        = parameters["rn_file1"]
    rn_file2        = parameters["rn_file2"]

    ## Now wash the parameters' values:
    ##
    ## item_status:
    try:
        ## If item_status isn't "added" or "approval", make it "added" by
        ## default. Else, keep its value:
        item_status = (item_status.upper() in ("ADDED", "APPROVAL") \
                       and item_status.upper()) or "ADDED"
    except AttributeError:
        ## Oops - item_status wasn't a string (NoneType?) Anyway, default
        ## it to "ADDED".
        item_status = "ADDED"

    ## mail_submitters:
    try:
        ## If mail_submitters isn't "Y" or "N", make it "Y" by
        ## default. Else, keep its value:
        mail_submitters = (mail_submitters.upper() in ("Y", "N") \
                       and mail_submitters.upper()) or "Y"
    except AttributeError:
        ## Oops - mail_submitters wasn't a string (NoneType?) Anyway, default
        ## it to "Y".
        mail_submitters = "Y"

    ## item_managers:
    ## A string in which the item_managers' email addresses will be stored:
    managers_email = ""
    try:
        ## We assume that the email addresses of item managers are
        ## separated by commas.
        item_managers_list = item_managers.split(",")
        for manager in item_managers_list:
            manager_address = manager.strip()
            ## Test that this manager's email address is OK, adding it if so:
            if email_valid_p(manager_address):
                ## This address is OK - add it to the string of manager
                ## addresses:
                managers_email += "%s," % manager_address
        ## Strip the trailing comma from managers_email (if there is one):
        managers_email = managers_email.strip().rstrip(",")
    except AttributeError:
        ## Oops - item_managers doesn't seem to be a string? Treat it as
        ## though it were empty:
        managers_email = ""

    ## author_file:
    authors = ""
    try:
        ## Read in the authors from author_file, putting them into the "authors"
        ## variable, one per line:
        fp_author_file = open("%s/%s" % (curdir, author_file), "r")
        for author in fp_author_file:
            authors += "%s\n" % author.strip()
        fp_author_file.close()
    except IOError:
        ## Unable to correctly read from "author_file", Skip it as though
        ## there were no authors:
        authors = "-"

    ## title_file:
    title = ""
    try:
        ## Read in the lines from title_file, putting them into the "title"
        ## variable on one line:
        fp_title_file = open("%s/%s" % (curdir, title_file), "r")
        for line in fp_title_file:
            title += "%s " % line.strip()
        fp_title_file.close()
        title = title.strip()
    except IOError:
        ## Unable to correctly read from "title_file", Skip it as though
        ## there were no title:
        title = "-"

    ## owners_file:
    ## A string in which the item_owners' email addresses will be stored:
    owners_email = ""
    try:
        fp_owners_file = open("%s/%s" % (curdir, owners_file), "r")
        for line in fp_owners_file:
            owner_address = line.strip()
            ## Test that this owner's email address is OK, adding it if so:
            if email_valid_p(owner_address):
                ## This address is OK - add it to the string of item owner
                ## addresses:
                owners_email += "%s," % owner_address
        ## Strip the trailing comma from owners_email (if there is one):
        owners_email = owners_email.strip().rstrip(",")
    except IOError:
        ## Unable to correctly read from "owners_file", Skip it as though
        ## there were no title:
        owners_email = ""

    ## Add "SuE" (the submitter) into the list of document "owners":
    try:
        fp_sue = open("%s/SuE" % curdir, "r")
        sue = fp_sue.readline()
        fp_sue.close()
    except IOError:
        sue = ""
    else:
        if sue.lower() not in owners_email.lower().split(","):
            ## The submitter is not listed in the "owners" mails,
            ## add her:
            owners_email = "%s,%s" % (sue, owners_email)
            owners_email = owners_email.strip().rstrip(",")

    ## rn_file1 & rn_file2:
    reference_numbers = ""
    try:
        fp_rnfile1 = open("%s/%s" % (curdir, rn_file1), "r")
        for line in fp_rnfile1:
            reference_number = line.strip()
            reference_number = \
               reference_number.replace("\n", "").replace("\r", "").\
               replace(" ", "")
            if reference_number != "":
                ## Add this reference number into the "reference numbers"
                ## variable:
                reference_numbers += "%s " % reference_number
        fp_rnfile1.close()
    except IOError:
        reference_numbers = ""
    try:
        fp_rnfile2 = open("%s/%s" % (curdir, rn_file2), "r")
        for line in fp_rnfile2:
            reference_number = line.strip()
            reference_number = \
               reference_number.replace("\n", "").replace("\r", "").\
               replace(" ", "")
            if reference_number != "":
                ## Add this reference number into the "reference numbers"
                ## variable:
                reference_numbers += "%s " % reference_number
        fp_rnfile2.close()
    except IOError:
        pass
    ## Strip any trailing whitespace from the reference numbers:
    reference_numbers = reference_numbers.strip()

    ## Now build the email from the information we've collected:
    email_txt = """
The following item has been submitted to %(sitename)s:
   Reference(s): %(reference)s
   Title:        %(title)s
   Author(s):      %(author)s
""" % { 'sitename'   : CFG_SITE_NAME,
        'reference' : reference_numbers,
        'title'     : title,
        'author'    : authors,
      }
    if item_status == "ADDED":
        ## The item has been added into the repository.
        email_txt += """
It will soon be made available and you will be able to check it at the
following URL:

  <%(siteurl)s/%(CFG_SITE_RECORD)s/%(record-id)s>

Please report any problems to <%(sitesupportemail)s>.
""" % { 'siteurl' : CFG_SITE_URL,
        'CFG_SITE_RECORD' : CFG_SITE_RECORD,
        'record-id' : sysno,
        'sitesupportemail' : CFG_SITE_SUPPORT_EMAIL,
      }
    else:
        ## The item has not yet been added - instead it awaits the
        ## approval of a referee. Let the email reflect this detail:
        email_txt += """
The item is now awaiting a referee's approval before being integrated
into the repository. You will be alerted by email as soon as a decision
has been taken.
"""
    ## Finish the message with a signature:
    email_txt += """

Thank you for submitting your item into %(sitename)s.
""" % { 'sitename' : CFG_SITE_NAME, }


    ## Send the email:
    if mail_submitters == "Y" and len(owners_email) != "":
        ## Mail-to is "owners_email":
        if managers_email != "":
            ## Managers should also be copied into the mail:
            owners_email += ",%s" % managers_email
        ## Post the mail:
        scheduled_send_email(CFG_EMAIL_FROM_ADDRESS, owners_email, \
                   "[%s] Submitted" % reference_numbers, \
                   email_txt, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN, \
                   other_bibtasklet_arguments=['-I', str(sequence_id)])
    elif managers_email != "":
        ## Although it's not desirable to mail the submitters, if "managers"
        ## have been given, it is reasonable to mail them:
        scheduled_send_email(CFG_EMAIL_FROM_ADDRESS, managers_email, \
                   "[%s] Submitted" % reference_numbers, \
                   email_txt, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN, \
                   other_bibtasklet_arguments=['-I', str(sequence_id)])
    elif CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN:
        ## We don't want to mail the "owners". Let's mail the admin instead:
        scheduled_send_email(CFG_EMAIL_FROM_ADDRESS, CFG_SITE_ADMIN_EMAIL, \
                   "[%s] Submitted" % reference_numbers, email_txt, \
                   other_bibtasklet_arguments=['-I', str(sequence_id)])

    ## Return an empty string
    return ""
Exemplo n.º 8
0
def Mail_Submitter(parameters, curdir, form, user_info=None):
    """
    This function send an email to the submitter to warn him the
    document he has just submitted has been correctly received.

    Parameters:

      * authorfile: Name of the file containing the authors of the
                    document

      * titleFile: Name of the file containing the title of the
                   document

      * emailFile: Name of the file containing the email of the
                   submitter of the document

      * status: Depending on the value of this parameter, the function
                adds an additional text to the email.  This parameter
                can be one of: ADDED: The file has been integrated in
                the database.  APPROVAL: The file has been sent for
                approval to a referee.  or can stay empty.

      * edsrn: Name of the file containing the reference of the
               document

      * newrnin: Name of the file containing the 2nd reference of the
                 document (if any)
    """
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
    sequence_id = bibtask_allocate_sequenceid(curdir)
    # retrieve report number
    edsrn = parameters['edsrn']
    newrnin = parameters['newrnin']
    fp = open("%s/%s" % (curdir,edsrn),"r")
    rn = fp.read()
    fp.close()
    rn = re.sub("[\n\r]+","",rn)
    if newrnin != "" and os.path.exists("%s/%s" % (curdir,newrnin)):
        fp = open("%s/%s" % (curdir,newrnin),"r")
        additional_rn = fp.read()
        fp.close()
        additional_rn = re.sub("[\n\r]+","",additional_rn)
        fullrn = "%s and %s" % (additional_rn,rn)
    else:
        fullrn = rn
    fullrn = fullrn.replace("\n"," ")
    # The title is read from the file specified by 'titlefile'
    try:
        fp = open("%s/%s" % (curdir,parameters['titleFile']),"r")
        m_title = fp.read().replace("\n"," ")
        fp.close()
    except:
        m_title = "-"
    # The name of the author is read from the file specified by 'authorfile'
    try:
        fp = open("%s/%s" % (curdir,parameters['authorfile']),"r")
        m_author = fp.read().replace("\n"," ")
        fp.close()
    except:
        m_author = "-"
    # The submitters email address is read from the file specified by 'emailFile'
    try:
        fp = open("%s/%s" % (curdir,parameters['emailFile']),"r")
        m_recipient = fp.read().replace ("\n"," ")
        fp.close()
    except:
        m_recipient = ""
    # create email body
    email_txt = "The document %s\nTitle: %s\nAuthor(s): %s\n\nhas been correctly received\n\n" % (fullrn,m_title,m_author)
    # The user is either informed that the document has been added to the database, or sent for approval
    if parameters['status'] == "APPROVAL":
        email_txt =  email_txt + "An email has been sent to the referee. You will be warned by email as soon as the referee takes his/her decision regarding your document.\n\n"
    elif parameters['status'] == "ADDED":
        email_txt = email_txt + "It will be soon added to our Document Server.\n\nOnce inserted, you will be able to check the  bibliographic information and the quality of the electronic documents at this URL:\n<%s/%s/%s>\nIf you detect an error please let us know by sending an email to %s. \n\n" % (CFG_SITE_URL,CFG_SITE_RECORD,sysno,CFG_SITE_SUPPORT_EMAIL)
    email_txt += get_nice_bibsched_related_message(curdir)
    email_txt = email_txt + "Thank you for using %s Submission Interface.\n" % CFG_SITE_NAME

    ## send the mail, if there are any recipients or copy to admin
    if m_recipient or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN:
        scheduled_send_email(FROMADDR, m_recipient.strip(), "%s: Document Received" % fullrn, email_txt,
                             copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,
                             other_bibtasklet_arguments=['-I', str(sequence_id)])

    return ""
Exemplo n.º 9
0
def Mail_Submitter(parameters, curdir, form, user_info=None):
    """
    This function send an email to the submitter to warn him the
    document he has just submitted has been correctly received.

    Parameters:

      * authorfile: Name of the file containing the authors of the
                    document

      * titleFile: Name of the file containing the title of the
                   document

      * emailFile: Name of the file containing the email of the
                   submitter of the document

      * status: Depending on the value of this parameter, the function
                adds an additional text to the email.  This parameter
                can be one of: ADDED: The file has been integrated in
                the database.  APPROVAL: The file has been sent for
                approval to a referee.  or can stay empty.

      * edsrn: Name of the file containing the reference of the
               document

      * newrnin: Name of the file containing the 2nd reference of the
                 document (if any)
    """
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)
    sequence_id = bibtask_allocate_sequenceid(curdir)
    # retrieve report number
    edsrn = parameters['edsrn']
    newrnin = parameters['newrnin']
    fp = open("%s/%s" % (curdir, edsrn), "r")
    rn = fp.read()
    fp.close()
    rn = re.sub("[\n\r]+", "", rn)
    if newrnin != "" and os.path.exists("%s/%s" % (curdir, newrnin)):
        fp = open("%s/%s" % (curdir, newrnin), "r")
        additional_rn = fp.read()
        fp.close()
        additional_rn = re.sub("[\n\r]+", "", additional_rn)
        fullrn = "%s and %s" % (additional_rn, rn)
    else:
        fullrn = rn
    fullrn = fullrn.replace("\n", " ")
    # The title is read from the file specified by 'titlefile'
    try:
        fp = open("%s/%s" % (curdir, parameters['titleFile']), "r")
        m_title = fp.read().replace("\n", " ")
        fp.close()
    except:
        m_title = "-"
    # The name of the author is read from the file specified by 'authorfile'
    try:
        fp = open("%s/%s" % (curdir, parameters['authorfile']), "r")
        m_author = fp.read().replace("\n", " ")
        fp.close()
    except:
        m_author = "-"
    # The submitters email address is read from the file specified by 'emailFile'
    try:
        fp = open("%s/%s" % (curdir, parameters['emailFile']), "r")
        m_recipient = fp.read().replace("\n", " ")
        fp.close()
    except:
        m_recipient = ""
    # create email body
    email_txt = "The document %s\nTitle: %s\nAuthor(s): %s\n\nhas been correctly received\n\n" % (
        fullrn, m_title, m_author)
    # The user is either informed that the document has been added to the database, or sent for approval
    if parameters['status'] == "APPROVAL":
        email_txt = email_txt + "An email has been sent to the referee. You will be warned by email as soon as the referee takes his/her decision regarding your document.\n\n"
    elif parameters['status'] == "ADDED":
        email_txt = email_txt + "It will be soon added to our Document Server.\n\nOnce inserted, you will be able to check the  bibliographic information and the quality of the electronic documents at this URL:\n<%s/%s/%s>\nIf you detect an error please let us know by sending an email to %s. \n\n" % (
            CFG_SITE_URL, CFG_SITE_RECORD, sysno, CFG_SITE_SUPPORT_EMAIL)
    email_txt += get_nice_bibsched_related_message(curdir)
    email_txt = email_txt + "Thank you for using %s Submission Interface.\n" % CFG_SITE_NAME

    ## send the mail, if there are any recipients or copy to admin
    if m_recipient or CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN:
        scheduled_send_email(
            FROMADDR,
            m_recipient.strip(),
            "%s: Document Received" % fullrn,
            email_txt,
            copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,
            other_bibtasklet_arguments=['-I', str(sequence_id)])

    return ""