def format_element(bfo, style):
    """
    Offers action to delete a blog or a post
    @param style: the CSS style to be applied to the link.
    """

    _ = gettext_set_language(bfo.lang)

    out = ""
    if bfo.user_info['email'] not in ["guest"]:
        coll = bfo.fields("980__a")[0]
        if coll in ['BLOG', 'BLOGPOST']:
            linkattrd = {}
            if style != '':
                linkattrd['style'] = style
    
            try:
                recid = bfo.control_field('001')[0]
            except:
                raise Exception("Record not found")
    
            if coll == 'BLOG':
                act = 'DBI'
                if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)):
                    doctype = 'BSI'
                    sub =  'DBIBSI'
                else:
                    doctype = 'BSIREF'
                    sub =  'DBIBSIREF'
    
            elif coll == 'BLOGPOST':
                act = 'DPI'
                if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)):
                    doctype = 'BSI'
                    sub =  'DPIBSI'
                else:
                    doctype = 'BSIREF'
                    sub =  'DPIBSIREF'
    
            out += create_html_link(CFG_SITE_URL + "/submit",
                                    {'ln': bfo.lang,
                                    'doctype': doctype,
                                    'indir': 'delete',
                                    'act': act,
                                    'sub': sub,
                                    'BSI_RN': recid},
                                    link_label = _("Ask for Deletion"),
                                    linkattrd = linkattrd)

    return out
Exemple #2
0
def index(req):
    user_info = collect_user_info(req)
    if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
        return page_not_authorized(req=req)

    req.content_type = "text/html"
    req.write(pageheaderonly("Repository tools", req=req))
    req.write("<h1>Repository tools</h1>")

    req.write("<h2>Compliance</h2>")
    req.write("<a href='/compliance.py'>Content compliance</a> - articles compliance with agreements<br />")
    req.write("<a href='/compliance.py/csv'>Content compliance to CSV</a> - articles compliance with agreements<br />")
    req.write("<a href='/nations.py/late'>24h deadline</a> - checks the 24h delivery deadline<br />")

    req.write("<h2>National statistics</h2>")
    req.write("<a href='/nations.py'>Countries impact</a> - number of pulications per country<br />")
    req.write("<a href='/nations.py/us_affiliations'>US affiliations</a> - all US affiliations<br />")
    req.write("<a href='/nations.py/us_affiliations_csv'>Selected US aff count CSV</a> - affiliation count for selected US universities<br />")
    req.write("<a href='/nations.py/usa_papers'>Selected US articles list</a><br />")
    req.write("<a href='/nations.py/usa_papers_csv'>Selected US articles list CSV</a><br />")

    req.write("<h2>Export to INSPIRE</h2>")
    req.write("<a href='/ffts_for_inspire.py'>Data export</a><br />")
    req.write("<a href='/ffts_for_inspire.py/csv'>Data export to CSV</a><br />")
    req.flush()

    req.write(pagefooteronly(req=req))
    return ""
def mail_cookie_create_role(role_name,
                            role_timeout=timedelta(hours=3),
                            cookie_timeout=timedelta(days=1),
                            onetime=True):
    """Create a unique url to be sent via email to belong temporaly to a role."""
    assert (acc_get_role_id(role_name) != 0)
    kind = 'role'
    params = (role_name, role_timeout)
    return mail_cookie_create_common(kind, params, cookie_timeout, onetime)
Exemple #4
0
def isUserSuperAdmin(user_info):
    """Return True if the user is superadmin; False otherwise."""
    if run_sql("""SELECT r.id
        FROM accROLE r LEFT JOIN user_accROLE ur
        ON r.id = ur.id_accROLE
        WHERE r.name = %s AND
        ur.id_user = %s AND ur.expiration>=NOW() LIMIT 1""", (SUPERADMINROLE, user_info['uid']), 1):
        return True
    return acc_firerole_check_user(user_info, load_role_definition(acc_get_role_id(SUPERADMINROLE)))
Exemple #5
0
def Mail_Approval_Request_to_Committee_Chair(parameters,
                                             curdir,
                                             form,
                                             user_info=None):
    """
    This function sends a confirmation email to the Committee Chair
    when approval for a document is requested.
    """
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)

    # retrieve useful information from webSubmit configuration
    res = run_sql("select * from sbmCPLXAPPROVAL where rn=%s", (rn, ))
    categ = res[0][1]

    pubcomchair_address = ""
    # Try to retrieve the committee chair's email from the referee's database
    for user in acc_get_role_users(
            acc_get_role_id("pubcomchair_%s_%s" % (res[0][0], categ))):
        pubcomchair_address += user[1]

    #Get the document details from the repository - use the function in publiline.py
    item_details = get_brief_doc_details_from_repository(rn)

    #Generate the author list
    authors = ""
    for element in item_details['authors']:
        authors += element + ", "

    message = """
    The document %s has been published as a Communication.
    Please select an appropriate referee for this document.

    Title: %s

    Author(s): %s

    To access the document(s), select the file(s) from the location:
    <%s/%s/%s>

    To select a referee, please go to:
    <%s/publiline.py?flow=cplx&doctype=%s&categ=%s&apptype=%s&RN=%s&ln=en>

    ---------------------------------------------
    Best regards.
    The submission team.""" % (
        rn, item_details['title'], authors, CFG_SITE_URL, CFG_SITE_RECORD,
        sysno, CFG_SITE_URL, res[0][0], res[0][1], res[0][3], rn)
    # send the mail

    send_email(FROMADDR,
               pubcomchair_address,
               "Request for Referee Selection : Document %s" % rn,
               message,
               footer="")
    return ""
def _resolve_maximum_acces_rights(uid):
    '''
    returns [max_role, lcul] to use in execute_action and check_transaction_permissions.
    Defaults to ['guest',0] if user has no roles assigned.
    Always returns the maximum privilege.
    '''

    roles = {bconfig.CLAIMPAPER_ADMIN_ROLE: acc_get_role_id(bconfig.CLAIMPAPER_ADMIN_ROLE),
            bconfig.CLAIMPAPER_USER_ROLE: acc_get_role_id(bconfig.CLAIMPAPER_USER_ROLE)}
    uroles = acc_get_user_roles(uid)

    max_role = ['guest', 0]

    for r in roles:
        if roles[r] in uroles:
            rright = bconfig.CMPROLESLCUL[r]
            if rright >= max_role[1]:
                max_role = [r, rright]

    return max_role
Exemple #7
0
def isUserSuperAdmin(user_info):
    """Return True if the user is superadmin; False otherwise."""
    if run_sql(
            """SELECT r.id
        FROM accROLE r LEFT JOIN user_accROLE ur
        ON r.id = ur.id_accROLE
        WHERE r.name = %s AND
        ur.id_user = %s AND ur.expiration>=NOW() LIMIT 1""",
        (SUPERADMINROLE, user_info['uid']), 1):
        return True
    return acc_firerole_check_user(
        user_info, load_role_definition(acc_get_role_id(SUPERADMINROLE)))
def mail_cookie_check_role(cookie, uid):
    """Check a given cookie for a valid authorization to a particular role and
    temporaly add the given uid to the role specified."""
    try:
        (kind, params) = mail_cookie_check_common(cookie)
        assert (kind == 'role')
        (role_name, role_timeout) = params
        role_id = acc_get_role_id(role_name)
        assert (role_id != 0)
        assert (type(role_timeout) is timedelta)
    except (TypeError, AssertionError, StandardError), e:
        raise InvenioWebAccessMailCookieError, e
def mail_cookie_check_role(cookie, uid):
    """Check a given cookie for a valid authorization to a particular role and
    temporaly add the given uid to the role specified."""
    try:
        (kind, params) = mail_cookie_check_common(cookie)
        assert(kind == 'role')
        (role_name, role_timeout) = params
        role_id = acc_get_role_id(role_name)
        assert(role_id != 0)
        assert(type(role_timeout) is timedelta)
    except (TypeError, AssertionError, StandardError), e:
        raise InvenioWebAccessMailCookieError, e
Exemple #10
0
def is_no_quota_user(uid):
    """
    Return True if the user belongs to any of the no_quota roles.
    """
    no_quota_role_ids = [
        acc_get_role_id(role) for role in CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA
    ]
    res = {}
    user_info = collect_user_info(uid)
    for role_id in no_quota_role_ids:
        if acc_is_user_in_role(user_info, role_id):
            return True
    return False
Exemple #11
0
def show_restricted_records(req):
    user_info = collect_user_info(req)
    if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
        return page_not_authorized(req=req)

    all_ids = [id[0] for id in run_sql("Select id from bibrec")]
    visible_ids = perform_request_search()

    deleted_and_older_and_restricted = set(all_ids) - set(visible_ids)
    restricted_ids = []
    # restricted_ids_older = []
    for id in deleted_and_older_and_restricted:
        rec = get_record(id)
        collections = record_get_field_values(rec, "980","%","%","%")
        if "DELETED" not in collections:
            year = record_get_field_values(rec, "773","%","%","y")
            title = record_get_field_values(rec, "245","%","%","a")
            if title:
                title = title[0]
            else:
                title = "No title"
            if year:
                if int(year[0]) >= 2015:
                    restricted_ids.append((id, title))
                # else:
                #    restricted_ids_older.append(id)
            else:
                restricted_ids.append((id,title))

    print "Restricted ids"
    print restricted_ids

    req.content_type = "text/html"
    req.write(pageheaderonly("Repository tools", req=req))
    req.write("<h1>Restricted records</h1>")
    req.write("<strong>Total number of possibli restricted records: {0}</strong>".format(len(restricted_ids)))
    req.write("<ol>")
    for id, title in restricted_ids:
        req.write("<li><a href='http://repo.scoap3.org/record/{1}'>{0}</a> <a href='http://repo.scoap3.org/record/edit/?ln=en#state=edit&recid={1}'>edit</a></li>".format(title, id))
    req.write("</ol>")
    # for id, title in restricted_ids:
    #    req.write("{0},".format(id))

    req.write(pagefooteronly(req=req))
    return ""
def Mail_Approval_Request_to_Committee_Chair(parameters, curdir, form, user_info=None):
    """
    This function sends a confirmation email to the Committee Chair
    when approval for a document is requested.
    """
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)

    # retrieve useful information from webSubmit configuration
    res = run_sql("select * from sbmCPLXAPPROVAL where rn=%s", (rn, ))
    categ = res[0][1]

    pubcomchair_address = ""
    # Try to retrieve the committee chair's email from the referee's database
    for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_%s" % (res[0][0],categ))):
        pubcomchair_address += user[1]

    #Get the document details from the repository - use the function in publiline.py
    item_details = get_brief_doc_details_from_repository(rn)

    #Generate the author list
    authors = ""
    for element in item_details['authors']:
        authors += element + ", "

    message = """
    The document %s has been published as a Communication.
    Please select an appropriate referee for this document.

    Title: %s

    Author(s): %s

    To access the document(s), select the file(s) from the location:
    <%s/%s/%s>

    To select a referee, please go to:
    <%s/publiline.py?flow=cplx&doctype=%s&categ=%s&apptype=%s&RN=%s&ln=en>

    ---------------------------------------------
    Best regards.
    The submission team.""" % (rn,item_details['title'],authors,CFG_SITE_URL,CFG_SITE_RECORD,sysno,CFG_SITE_URL,res[0][0],res[0][1],res[0][3],rn)
    # send the mail

    send_email(FROMADDR,pubcomchair_address,"Request for Referee Selection : Document %s" % rn, message,footer="")
    return ""
Exemple #13
0
def index(req):
    user_info = collect_user_info(req)
    if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
        return page_not_authorized(req=req)

    req.content_type = "text/html"
    req.write(pageheaderonly("Repository tools & extra resources", req=req))
    req.write("<h1>Repository tools</h1>")

    req.write("<h2>Compliance</h2>")
    req.write("<a href='/compliance.py'>Content compliance</a> - articles compliance with agreements<br />")
    req.write("<a href='/compliance.py/csv'>Content compliance to CSV</a> - articles compliance with agreements<br />")
    req.write("<a href='/nations.py/late'>24h deadline</a> - checks the 24h delivery deadline (OBSOLETE)<br />")

    req.write("<h2>National statistics</h2>")
    req.write("<a href='/nations.py'>Countries impact</a> - number of pulications per country<br />")
    req.write("<a href='/nations.py/us_affiliations'>US affiliations</a> - all US affiliations<br />")
    req.write("<a href='/nations.py/us_affiliations_csv'>Selected US aff count CSV</a> - affiliation count for selected US universities<br />")
    req.write("<a href='/nations.py/usa_papers'>Selected US articles list</a><br />")
    req.write("<a href='/nations.py/usa_papers_csv'>Selected US articles list CSV</a><br />")
    req.write("<a href='/nations.py/papers_by_country_csv?country=xxx'>CSV list of articles by country</a> - you need to change argument 'country=xxx' to a country from the list bellow<br />")
    req.write("<textarea>Algeria, Argentina, Armenia, Australia, Austria, Azerbaijan, Belarus, Belgium, Bangladesh, Brazil, Bulgaria, Canada, CERN, Chile, China, Colombia, Costa Rica, Cuba, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Georgia, Germany, Greece, Hong Kong, Hungary, Iceland, India, Indonesia, Iran, Ireland, Israel, Italy, Japan, South Korea, Lebanon, Lithuania, Luxembourg, Mexico, Montenegro, Morocco, Niger, Netherlands, New Zealand, Norway, Pakistan, Poland, Portugal, Romania, Republic of San Marino, Russia, Saudi Arabia, Serbia, Singapore, Slovakia, South Africa, Spain, Sweden, Switzerland, Taiwan, Thailand, Tunisia, Turkey, Ukraine, UK, USA, Uruguay, Uzbekistan, Venezuela, Vietnam, Yemen, Peru, Kuwait, Sri Lanka, Kazakhstan, Mongolia, United Arab Emirates, United Arab Emirates, Malaysia, Qatar, Kyrgyz Republic, Jordan</textarea>")
    req.write("<a href='https://repo.scoap3.org/nations.py/countries_by_publishers'>Countries per journals</a>")

    req.write("<h2>Articles for impact calculations</h2>")
    req.write("<a href='/nations.py/impact_articles?year=2014'>Countries impact for 2014</a><br />")
    req.write("<a href='https://gist.github.com/Dziolas/7924d2feb2b3e5b0618a'>Code to run on Inspire server to get articles for impact calculation</a><br />")

    req.write("<h2>Export to INSPIRE</h2>")
    req.write("<a href='/ffts_for_inspire.py'>Data export</a><br />")
    req.write("<a href='/ffts_for_inspire.py/csv'>Data export to CSV</a><br />")

    req.write("<h1>Hidden collections</h1>")
    req.write("<a href='/collection/Erratum'>Erratas</a><br />")
    req.write("<a href='/collection/Addendum'>Addendums</a><br />")
    req.write("<a href='/collection/Corrigendum'>Corrigendums</a><br />")
    req.write("<a href='/collection/Editorial'>Editorials</a><br />")
    req.write("<a href='/collection/older_than_2014'>Articles older than 2014</a><br />")
    req.flush()

    req.write(pagefooteronly(req=req))
    return ""
Exemple #14
0
def check_quota(nb_messages):
    """
    @param nb_messages: max number of messages a user can have
    @return: a dictionary of users over-quota
    """
    from invenio.webuser import collect_user_info
    from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id
    no_quota_role_ids = [
        acc_get_role_id(role) for role in CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA
    ]
    res = {}
    for uid, n in run_sql(
            "SELECT id_user_to, COUNT(id_user_to) FROM user_msgMESSAGE GROUP BY id_user_to HAVING COUNT(id_user_to) > %s",
        (nb_messages, )):
        user_info = collect_user_info(uid)
        for role_id in no_quota_role_ids:
            if acc_is_user_in_role(user_info, role_id):
                break
        else:
            res[uid] = n
    return res
Exemple #15
0
def json(req):
    """
    Returns all BAI information in a JSON friendly way.
    """
    import json
    from invenio.dbquery import run_sql
    from invenio.webuser import collect_user_info
    from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id
    if not acc_is_user_in_role(collect_user_info(req),
                               acc_get_role_id('cernintranet')):
        from invenio.webinterface_handler_config import HTTP_FORBIDDEN
        req.status = HTTP_FORBIDDEN
        return ""
    bais = run_sql(
        "SELECT personid, tag, data FROM aidPERSONIDDATA WHERE tag in ('canonical_name', 'extid:INSPIREID', 'extid:ORCID', 'uid') ORDER BY personid"
    )
    emails = dict(run_sql("SELECT id, email FROM user"))
    req.content_type = 'application/json'
    old_personid = None
    authors = {}
    person = {}
    canonical_name = ""
    for personid, tag, data in bais:
        if personid != old_personid:
            if not person and canonical_name in authors:
                # We can delete this person
                del authors[canonical_name]
            person = {}
            old_personid = personid
        if tag == 'canonical_name':
            authors[data] = person
            canonical_name = data
        elif tag == 'uid' and int(data) in emails:
            person['email'] = emails[int(data)]
        elif tag == 'extid:INSPIREID':
            person['INSPIREID'] = data
        elif tag == 'extid:ORCID':
            person['ORCID'] = data
    json.dump(authors, req)
    return ""
Exemple #16
0
def json(req):
    """
    Returns all BAI information in a JSON friendly way.
    """
    import json
    from invenio.dbquery import run_sql
    from invenio.webuser import collect_user_info
    from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id
    if not acc_is_user_in_role(collect_user_info(req), acc_get_role_id('cernintranet')):
        from invenio.webinterface_handler_config import HTTP_FORBIDDEN
        req.status = HTTP_FORBIDDEN
        return ""
    bais = run_sql("SELECT personid, tag, data FROM aidPERSONIDDATA WHERE tag in ('canonical_name', 'extid:INSPIREID', 'extid:ORCID', 'uid') ORDER BY personid")
    emails = dict(run_sql("SELECT id, email FROM user"))
    req.content_type = 'application/json'
    old_personid = None
    authors = {}
    person = {}
    canonical_name = ""
    for personid, tag, data in bais:
        if personid != old_personid:
            if not person and canonical_name in authors:
                # We can delete this person
                del authors[canonical_name]
            person = {}
            old_personid = personid
        if tag == 'canonical_name':
            authors[data] = person
            canonical_name = data
        elif tag == 'uid' and int(data) in emails:
            person['email'] = emails[int(data)]
        elif tag == 'extid:INSPIREID':
            person['INSPIREID'] = data
        elif tag == 'extid:ORCID':
            person['ORCID'] = data
    json.dump(authors, req)
    return ""
def Send_Request_For_Refereeing_Process(parameters, curdir, form, user_info=None):
    global rn,sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$",curdir).group(2)
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # retrieve category
    categformat = categformat.replace("<CATEG>","([^-]*)")
    categs = re.match(categformat,rn)
    if categs is not None:
        category = categs.group(1)
    else:
        category = "unknown"
    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""
    if os.path.exists("%s/%s" % (curdir,parameters['titleFile'])):
        fp = open("%s/%s" % (curdir,parameters['titleFile']),"r")
        title = fp.read()
        fp.close()
        title = title.replace("\n","")
    else:
        title = ""
    title += " - %s" % date
    # create AU
    if os.path.exists("%s/%s" % (curdir,parameters['authorfile'])):
        fp = open("%s/%s" % (curdir,parameters['authorfile']), "r")
        author = fp.read()
        fp.close()
    else:
        author = ""
    # we get the referee password
    #sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    #if len(sth) >0:
        #access = sth[0][0]
    # Build referee's email address
    refereeaddress = ""
    # Try to retrieve the publication committee chair's email from the role database
    for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_%s" % (doctype,category))):
        refereeaddress += user[1] + ","
    # And if there are general referees
    for user in acc_get_role_users(acc_get_role_id("pubcomchair_%s_*" % doctype)):
        refereeaddress += user[1] + ","
    refereeaddress = re.sub(",$","",refereeaddress)
    # Creation of the mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)
    title_referee = "Request for refereeing process of %s" % rn
    mail_referee = "The document %s has been asked for refereing process to the %s Server..\nYour have to select an editorial board for it.\n\n" % (rn,CFG_SITE_NAME)
    mail_referee +="Title: %s\n\nAuthor(s): %s\n\n" % (title,author)
    mail_referee +="To access the document(s), select the file(s) from the location:<%s/record/%s/files/>\n\n" % (CFG_SITE_URL,sysno)
    mail_referee +="To select an editorial board, you should go to this URL:\n<%s/publiline.py?doctype=%s&categ=%s&RN=%s>\n" % (CFG_SITE_URL,doctype,category,rn)
    mail_referee +="---------------------------------------------\nBest regards.\nThe submission team.\n"
    #Send mail to referee
    send_email(FROMADDR, addresses, title_referee, mail_referee, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
def APO_Mail_Final_Decision_to_User (parameters, curdir, form, user_info=None):
    """
    This function sends an email to the user informing him/her about
    the decision taken by the referee on his/her proposition.
    This email is also sent to the referee for checking.

    Parameters:

       * 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"

    """

    global sysno, rn
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
    doctype = form['doctype']
    # variables declaration
    categformat = parameters['categformatAPP']
    sequence_id = bibtask_allocate_sequenceid(curdir)

    ## 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 " \
                                   "APO_Mail_Final_Decision_to_User. 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 " \
                                "APO_Mail_Final_Decision_to_User. 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 " \
                                   "APO_Mail_Final_Decision_to_User. 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 " \
                               "APO_Mail_Final_Decision_to_User. Tried to open decision " \
                               "file [%s/%s] but was unable to." \
                               % (curdir, decision_filename)
            register_exception(prefix=exception_prefix)
        else:
            decision = decision.strip()

    # 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"

    # 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
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    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:
        record_owners_list = []
    record_owners = ",".join([owner for owner in record_owners_list])
    if record_owners != "":
        addresses += ",%s" % record_owners

    # Add "SuE" (user who throught the action) into the list of addresses:
    try:
        fp_sue = open("%s/SuE" % curdir, "r")
        sue = fp_sue.readline()
        fp_sue.close()
        addresses += ",%s" % sue
    except IOError:
        sue = ""

    post_title = "".join(["%s" % title.strip() for title in \
                    get_fieldvalues(int(sysno), "245__a")])

    post_url = "".join(["%s" % url.strip() for url in \
                         get_fieldvalues(int(sysno), "520__u")])

    if decision != "":
        if decision == "approve":
            mailtitle = "Post record deletion approved: [%(id)s]"
            if post_title:
                mailtitle = mailtitle % {'id': post_title}
            else:
                mailtitle = mailtitle % {'id': post_url}
            mailbody = "\nThe deletion of the post record with URL [%s] and title '%s' has been approved.\n" % (post_url, post_title)
            mailbody += "\nThis post record will be no longer available in the repository.\n"
        else:
            mailtitle = "Post record deletion has been rejected: [%(id)s]"
            if post_title:
                mailtitle = mailtitle % {'id': post_title}
            else:
                mailtitle = mailtitle % {'id': post_url}
            mailbody = "\nThe deletion of the post record with URL [%s] and title '%s' has been rejected.\n" % (post_url, post_title)

    # 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 ""
def CONFSUBMIT_Send_Approval_Request (parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    simple approval process.  This function is very CERN-specific and
    should be changed in case of external use.  Must be called after
    the Get_Report_Number function.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * titleFile: name of the file in which the title is stored.

       * submitteremailfile: name of the file in which the title is stored.

       * submitternamefile: name of the file in which the title is stored.

       * contactnamefile: name of the file in which the title is stored.

       * contactemailfile: name of the file in which the title is stored.

       * referencefile: name of the file in which the title is stored.

       * affiliationfile: name of the file in which the title is stored.

       * regionfile: name of the file in which the title is stored.

       * rankfile: name of the file in which the title is stored.

       * fieldfile: name of the file in which the title is stored.

       * experimentsfile: name of the file in which the title is stored.

       * urlfile: name of the file in which the title is stored.

       * datefile: name of the file in which the title is stored.

       * abstractfile: name of the file in which the title is stored.

       * seriesnamefile: name of the file where the series name is stored.

       * seriesnumberfile: name of the file where the series number is stored.

       * directory: parameter used to create the URL to access the
                    files.
    """
    global rn,sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$",curdir).group(2)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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 record data
    date = get_file_contents(curdir, "date")
    title = get_file_contents(curdir, parameters['titleFile']).replace("\n","")
    title += " - %s" % date
    submitteremail = get_file_contents(curdir, parameters['submitteremailfile']).replace("\n",", ")
    submittername = get_file_contents(curdir, parameters['submitternamefile']).replace("\n",", ")
    contactname = get_file_contents(curdir, parameters['contactnamefile']).replace("\n",", ")
    contactemail = get_file_contents(curdir, parameters['contactemailfile']).replace("\n",", ")
    subtitle = get_file_contents(curdir, parameters['subtitle']).replace("\n",", ")
    city = get_file_contents(curdir, parameters['cityfile']).replace("\n",", ")
    country = get_file_contents(curdir, parameters['countryfile']).replace("\n",", ")
    state = get_file_contents(curdir, parameters['statefile']).replace("\n",", ")
    stdate = get_file_contents(curdir, parameters['stdatefile']).replace("\n",", ")
    fndate = get_file_contents(curdir, parameters['fndatefile']).replace("\n",", ")
    field = get_file_contents(curdir, parameters['fieldfile']).replace("\n",", ")
    url = get_file_contents(curdir, parameters['urlfile']).replace("\n"," ")
    shorttitle = get_file_contents(curdir, parameters['shorttitle']).replace("\n"," ")
    keywords = get_file_contents(curdir, parameters['keywords']).replace("\n"," ")
    proceedings = get_file_contents(curdir, parameters['proceedings']).replace("\n"," ")
    seriesname = get_file_contents(curdir, parameters['seriesnamefile']).replace("\n"," ")
    seriesnumber = get_file_contents(curdir, parameters['seriesnumberfile']).replace("\n"," ")
    abstract = get_file_contents(curdir, parameters['abstractfile'])

    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(sth) >0:
        access = sth[0][0]
    # 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 are general referees
    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
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)
    record_url = "%s/%s/%s" % (CFG_SITE_URL, CFG_SITE_RECORD, sysno)
    title_referee = "Request for approval of %s" % rn
    mail_referee = """
The document %(rn)s has been submitted to the Conferences database and it will appear here:\n%(recordlink)s.
To approve/reject the document, you should go to this URL:\n%(access)s\n

Title: %(title)s
Date: from %(stdate)s to %(fndate)s
Place: %(city)s, %(state)s, %(country)s
Series name: %(seriesname)s
Series number: %(seriesnumber)s

URL: %(url)s

Field(s): %(field)s

Description:
%(abstract)s

Contact name(s): %(contactname)s
Contact email(s): %(contactemail)s
Submitter name(s): %(submittername)s
Submitter email(s): %(submitteremail)s
    """ % {'rn' : rn,
           'title' : title,
           'submitteremail' : submitteremail,
           'submittername' : submittername,
           'contactname' : contactname,
           'contactemail' : contactemail,
           'field' : field,
           'city' : city,
           'state' : state,
           'country' : country,
           'stdate' : stdate,
           'fndate' : fndate,
           'url' : url,
           'subtitle' : subtitle,
           'shorttitle' : shorttitle,
           'proceedings' : proceedings,
           'keywords' : keywords,
           'access' : "%s/approve.py?access=%s" % (CFG_SITE_URL,access),
           'recordlink' : record_url,
           'abstract' : abstract,
           'seriesname' : seriesname,
           'seriesnumber' : seriesnumber
           }
    #Send mail to referee
    send_email(fromaddr=CFG_WEBSUBMIT_CONF_FROMADDR, toaddr=CFG_WEBSUBMIT_CONF_SUPPORT_EMAIL, subject=title_referee, \
               content=mail_referee, footer=email_footer(support_email=CFG_WEBSUBMIT_CONF_SUPPORT_EMAIL),
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN, bccaddr=addresses, replytoaddr=contactemail)
    return ""
Exemple #20
0
def http_check_credentials(req, role):
    """Retrieve Apache password and check user credential with the
    check_auth function. If this function returns True check if the user
    is enabled to the given role. If this is True, return, otherwise
    popup a new apache login box.
    """

    authorized = False
    while True:
        if req.headers_in.has_key("Authorization"):
            try:
                s = req.headers_in["Authorization"][6:]
                s = base64.decodestring(s)
                user, passwd = s.split(":", 1)
            except (ValueError, base64.binascii.Error, base64.binascii.Incomplete):
                raise apache.SERVER_RETURN, apache.HTTP_BAD_REQUEST

            authorized = auth_apache_user_p(user, passwd)

        if authorized:
            setApacheUser(req, user)
            authorized = acc_firerole_check_user(collect_user_info(req), load_role_definition(acc_get_role_id(role)))
            setApacheUser(req, '')

        if not authorized:
            # note that Opera supposedly doesn't like spaces around "=" below
            s = 'Basic realm="%s"' % role
            req.headers_out["WWW-Authenticate"] = s
            raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED
        else:
            setApacheUser(req, user)
            return
def Send_Approval_Request(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    simple approval process.  This function is very CERN-specific and
    should be changed in case of external use.  Must be called after
    the Get_Report_Number function.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * authorfile: name of the file in which the authors are stored

       * titlefile: name of the file in which the title is stored.

       * directory: parameter used to create the URL to access the
                    files.
    """
    global rn, sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$", curdir).group(2)
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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"
    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""
    if os.path.exists("%s/%s" % (curdir, parameters['titleFile'])):
        fp = open("%s/%s" % (curdir, parameters['titleFile']), "r")
        title = fp.read()
        fp.close()
        title = title.replace("\n", "")
    else:
        title = ""
    title += " - %s" % date
    # create AU
    if os.path.exists("%s/%s" % (curdir, parameters['authorfile'])):
        fp = open("%s/%s" % (curdir, parameters['authorfile']), "r")
        author = fp.read()
        fp.close()
    else:
        author = ""
    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn, ))
    if len(sth) > 0:
        access = sth[0][0]
    # 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 are general referees
    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
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$", "", addresses)
    title_referee = "Request for approval of %s" % rn
    mail_referee = "The document %s has been submitted to the %s Server..\nYour approval is requested on it.\n\n" % (
        rn, CFG_SITE_NAME)
    mail_referee += "Title: %s\n\nAuthor(s): %s\n\n" % (title, author)
    mail_referee += "To access the document(s), select the file(s) from the location:<%s/record/%s/files/>\n\n" % (
        CFG_SITE_URL, sysno)
    mail_referee += "To approve/reject the document, you should go to this URL:\n<%s/approve.py?%s>\n" % (
        CFG_SITE_URL, access)
    mail_referee += "---------------------------------------------\nBest regards.\nThe submission team.\n"
    #Send mail to referee
    send_email(FROMADDR,
               addresses,
               title_referee,
               mail_referee,
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
def MBI_Mail_Approval_Request_to_Referee(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    approval process related to the metadata modification of a blog record.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * directory: parameter used to create the URL to access the
                    files.
    """

    global rn, sysno
    doctype = 'BSIREF'
    approval_action = 'APM'
    sequence_id = bibtask_allocate_sequenceid(curdir)
    action = ParamFromFile("%s/%s" % (curdir,'act')).strip()
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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"

    blog_title = "".join(["%s" % title.strip() for title in \
                         get_fieldvalues(int(sysno), "245__a")])

    blog_url = "".join(["%s" % url.strip() for url in \
                        get_fieldvalues(int(sysno), "520__u")])

    blog_topic = "".join(["%s" % topic.strip() for topic in \
                    get_fieldvalues(int(sysno), "654__a")])

    blog_license = "".join(["%s" % license.strip() for license in \
                    get_fieldvalues(int(sysno), "542__f")])

    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(sth) >0:
        access = sth[0][0]

    # 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 are general referees
    for user in acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
        refereeaddress += user[1] + ","

    refereeaddress = re.sub(",$","",refereeaddress)
    # Creation of the e-mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)
        
    if os.path.exists("%s/recmysql" % curdir):
        fp = open("%s/recmysql" % curdir,"r")
        modifiedrec_xml = fp.read()
        fp.close()
    else:
        raise InvenioWebSubmitFunctionError("Cannot create database record")

    modifiedrec = create_record(modifiedrec_xml)[0]
    new_title = record_get_field_values(modifiedrec, "245", code = "a")
    new_topic = record_get_field_values(modifiedrec, "654", code = "a")
    new_license = record_get_field_values(modifiedrec, "542", code = "f")

    modified_fields = ""
    if new_title:
        modified_fields += "New title: '%s'\n" % new_title[0]
    if new_topic:
        modified_fields += "   New topic: '%s'\n" % new_topic[0]
    if new_license:
        modified_fields += "   New license: '%s'" % new_license[0]

    # Send the email:
    mail_subject = "Request for approval of blog metadata modification: [%(id)s]"
    if blog_title:
        mail_subject =  mail_subject % {'id': blog_title}
    else:
        mail_subject =  mail_subject % {'id': blog_url}

    mail_body = CFG_MAIL_BODY % \
                {'title': blog_title,
                 'blog_url': blog_url,
                 'topic': blog_topic,
                 'license': blog_license,
                 'modified_fields': modified_fields,
                 'site_name' : CFG_SITE_NAME,
                 'site_url': CFG_SITE_URL,
                 'doctype': doctype,
                 'access': access,
                 'approval_action': approval_action,
                 'rn': rn
                 }
    scheduled_send_email(CFG_SITE_SUPPORT_EMAIL, addresses,
                         mail_subject, mail_body, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN,
                         other_bibtasklet_arguments=['-I', str(sequence_id)])
    return ""
    def _precache(self, info, force=False):
        """
        Calculate prermitions for user actions.

        FIXME: compatibility layer only !!!
        """
        # get autorization key
        acc_key = self.get_acc_key()
        acc = cache.get(acc_key)
        if not force and acc_key is not None and acc is not None:
            return acc

        #FIXME: acc_authorize_action should use flask request directly
        user_info = info
        user_info.update(self.req)

        from invenio.webuser import isUserSubmitter, isUserReferee, \
            isUserAdmin, isUserSuperAdmin
        from invenio.access_control_engine import acc_authorize_action
        from invenio.access_control_admin import acc_get_role_id, \
            acc_is_user_in_role
        from invenio.search_engine import get_permitted_restricted_collections

        data = {}
        data['precached_permitted_restricted_collections'] = \
            get_permitted_restricted_collections(user_info)
        data['precached_usebaskets'] = acc_authorize_action(
            user_info, 'usebaskets')[0] == 0
        data['precached_useloans'] = acc_authorize_action(
            user_info, 'useloans')[0] == 0
        data['precached_usegroups'] = acc_authorize_action(
            user_info, 'usegroups')[0] == 0
        data['precached_usealerts'] = acc_authorize_action(
            user_info, 'usealerts')[0] == 0
        data['precached_usemessages'] = acc_authorize_action(
            user_info, 'usemessages')[0] == 0
        data['precached_usestats'] = acc_authorize_action(
            user_info, 'runwebstatadmin')[0] == 0
        data['precached_viewsubmissions'] = isUserSubmitter(user_info)
        data['precached_useapprove'] = isUserReferee(user_info)
        data['precached_useadmin'] = isUserAdmin(user_info)
        data['precached_usesuperadmin'] = isUserSuperAdmin(user_info)
        data['precached_canseehiddenmarctags'] = acc_authorize_action(
            user_info, 'runbibedit')[0] == 0
        usepaperclaim = False
        usepaperattribution = False
        viewclaimlink = False

        if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(
                user_info, acc_get_role_id("paperclaimviewers"))):
            usepaperclaim = True

        if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(
                user_info, acc_get_role_id("paperattributionviewers"))):
            usepaperattribution = True

        viewlink = False
        try:
            viewlink = session['personinfo']['claim_in_process']
        except (KeyError, TypeError):
            pass

        if (CFG_BIBAUTHORID_ENABLED and usepaperattribution and viewlink):
            viewclaimlink = True


#                if (CFG_BIBAUTHORID_ENABLED
#                    and ((usepaperclaim or usepaperattribution)
#                         and acc_is_user_in_role(data, acc_get_role_id("paperattributionlinkviewers")))):
#                    viewclaimlink = True

        data['precached_viewclaimlink'] = viewclaimlink
        data['precached_usepaperclaim'] = usepaperclaim
        data['precached_usepaperattribution'] = usepaperattribution

        cache.set(acc_key,
                  data,
                  timeout=CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT * 3600)
        return data
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 ""
Exemple #25
0
            user_info['remote_host'] = req.remote_host or ''
            user_info['referer'] = req.headers_in.get('Referer', '')
            user_info['uri'] = req.unparsed_uri or ()
            user_info['agent'] = req.headers_in.get('User-Agent', 'N/A')
        user_info['uid'] = uid
        user_info['nickname'] = get_nickname(uid) or ''
        user_info['email'] = get_email(uid) or ''
        user_info['group'] = []
        user_info['guest'] = str(isGuestUser(uid))

        if user_info['guest'] == '1' and CFG_INSPIRE_SITE:
            usepaperattribution = False
            viewclaimlink = False

            if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(
                    user_info, acc_get_role_id("paperattributionviewers"))):
                usepaperattribution = True

#            if (CFG_BIBAUTHORID_ENABLED
#                and usepaperattribution
#                and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers"))):
#                viewclaimlink = True
            if is_req:
                session = get_session(req)
                viewlink = False
                try:
                    viewlink = session['personinfo']['claim_in_process']
                except (KeyError, TypeError):
                    viewlink = False
            else:
                viewlink = False
def JOBSUBMIT_Send_Approval_Request(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    simple approval process.  This function is very CERN-specific and
    should be changed in case of external use.  Must be called after
    the Get_Report_Number function.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * titleFile: name of the file in which the title is stored.

       * contactnamefile: name of the file in which the title is stored.

       * contactemailfile: name of the file in which the title is stored.

       * referencefile: name of the file in which the title is stored.

       * affiliationfile: name of the file in which the title is stored.

       * regionfile: name of the file in which the title is stored.

       * rankfile: name of the file in which the title is stored.

       * fieldfile: name of the file in which the title is stored.

       * experimentsfile: name of the file in which the title is stored.

       * urlfile: name of the file in which the title is stored.

       * datefile: name of the file in which the title is stored.

       * abstractfile: name of the file in which the title is stored.

       * directory: parameter used to create the URL to access the
                    files.
    """
    global rn, sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$", curdir).group(2)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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 record data
    date = get_file_contents(curdir, "date")
    title = get_file_contents(curdir,
                              parameters['titleFile']).replace("\n", "")
    title += " - %s" % date
    contactname = get_file_contents(curdir,
                                    parameters['contactnamefile']).replace(
                                        "\n", ", ")
    contactemail = get_file_contents(curdir,
                                     parameters['contactemailfile']).replace(
                                         "\n", ", ")
    reference = get_file_contents(curdir, parameters['referencefile']).replace(
        "\n", ", ")
    affiliation = get_file_contents(curdir,
                                    parameters['affiliationfile']).replace(
                                        "\n", ", ")
    region = get_file_contents(curdir,
                               parameters['regionfile']).replace("\n", ", ")
    rank = get_file_contents(curdir,
                             parameters['rankfile']).replace("\n", ", ")
    field = get_file_contents(curdir,
                              parameters['fieldfile']).replace("\n", ", ")
    experiments = get_file_contents(curdir,
                                    parameters['experimentsfile']).replace(
                                        "\n", ", ")
    url = get_file_contents(curdir, parameters['urlfile']).replace("\n", " ")
    date = get_file_contents(curdir, parameters['datefile']).replace("\n", "")
    abstract = get_file_contents(curdir, parameters['abstractfile'])

    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn, ))
    if len(sth) > 0:
        access = sth[0][0]
    # 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 are general referees
    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
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "" and otheraddresses != CFG_WEBSUBMIT_JOBS_SUPPORT_EMAIL:
        addresses += otheraddresses
    else:
        addresses = re.sub(",$", "", addresses)
    record_url = "%s/%s/%s" % (CFG_SITE_URL, CFG_SITE_RECORD, sysno)
    title_referee = "Request for approval of %s" % rn
    mail_referee = """
The document %(rn)s has been submitted to the Jobs database.\nYour approval is requested on it.

Title: %(title)s
Contact name(s): %(contactname)s
Contact email(s): %(contactemail)s
Reference(s): %(reference)s
Affliliation(s): %(affiliation)s

Region(s): %(region)s
Rank(s): %(rank)s
Field(s): %(field)s
Experiments(s): %(experiments)s

URL: %(url)s

Deadline date: %(date)s

Description:
%(abstract)s

The record will appear here:
%(recordlink)s

To approve/reject the document, you should go to this URL:\n%(access)s\n
    """ % {
        'rn': rn,
        'title': title,
        'contactname': contactname,
        'contactemail': contactemail,
        'reference': reference,
        'affiliation': affiliation,
        'region': region,
        'rank': rank,
        'region': region,
        'field': field,
        'experiments': experiments,
        'url': url,
        'date': date,
        'abstract': abstract,
        'access': "%s/approve.py?access=%s" % (CFG_SITE_URL, access),
        'recordlink': record_url
    }
    #Send mail to referee
    send_email(fromaddr=CFG_WEBSUBMIT_JOBS_FROMADDR, toaddr=CFG_WEBSUBMIT_JOBS_SUPPORT_EMAIL, subject=title_referee, \
               content=mail_referee, footer=email_footer(support_email=CFG_WEBSUBMIT_JOBS_SUPPORT_EMAIL),
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN, bccaddr=addresses, replytoaddr=contactemail)
    return ""
Exemple #27
0
def index(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG, todo="", id="", doctype="",
          categ="", addusers="", warningText="", role=""):
    """Main entry point for the management of referees."""
    ln = wash_language(ln)
    # get user ID:
    uid = getUid(req)
    (auth_code, auth_message) = acc_authorize_action(req, "cfgwebsubmit", verbose=0)
    if auth_code != 0:
        ## user is not authorised to use WebSubmit Admin:
        return page_not_authorized(req=req, text=auth_message)

    # request for deleting a user
    if todo == "deleteuser":
        acc_delete_user_role(id, name_role=role)
    # request for adding user(s)
    if todo == "adduser":
        role = "referee_%s_%s" % (doctype, categ[1])
        roleId = acc_get_role_id(role)
        # if the role does not exists, we create it
        if roleId == 0:
            if acc_add_role(role, "referees for document type %s category %s" % (doctype, categ[1])) == 0:
                return errorMsg("Cannot create referee role", req, uid)
            else:
                roleId = acc_get_role_id(role)
            # if the action does not exist, we create it
            actionId = acc_get_action_id("referee")
            if actionId == 0:
                if acc_add_action("referee", "", "no", ("doctype","categ")) == 0:
                    return errorMsg("Cannot create action 'referee'", req, uid)
                else:
                    actionId = acc_get_action_id("referee")
            #create arguments
            arg1Id = acc_add_argument("doctype", doctype)
            arg2Id = acc_add_argument("categ", categ[1])
            # then link the role with the action
            if acc_add_role_action_arguments(roleId, actionId, -1, 0, 0, [arg1Id, arg2Id]) == 0:
                return errorMsg("Cannot link role with action", req, uid)
        roleId = acc_get_role_id(role)
        # For each id in the array
        if isinstance(addusers, types.ListType):
            for adduser in addusers:
                # First check  whether this id is not already associated with this rule
                myRoles = acc_get_user_roles(adduser)
                if not roleId in myRoles:
                    # Actually add the role to the user
                    acc_add_user_role(adduser, roleId)
                else:
                    warningText = '<span style="color:#f00">Sorry... This user is already a referee for this category.</span>'
        else:
            # First check  whether this id is not already associated with this rule
            myRoles = acc_get_user_roles(addusers)
            if not roleId in myRoles:
                # Actually add the role to the user
                acc_add_user_role(addusers, roleId)
            else:
                warningText = '<span style="color:#f00">Sorry... This user is already a referee for this category.</span>'
    return page(title="websubmit admin - referee selection",
                    body=displayRefereesPage(doctype, warningText),
                    description="",
                    keywords="",
                    uid=uid,
                    language=ln,
                    req=req)
Exemple #28
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 ""
Exemple #29
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, sysno, rn
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)
    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:
        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:
        send_email(FROMADDR,
                   addresses,
                   mailtitle,
                   mailbody,
                   copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
def mail_cookie_create_role(role_name, role_timeout=timedelta(hours=3), cookie_timeout=timedelta(days=1), onetime=True):
    """Create a unique url to be sent via email to belong temporaly to a role."""
    assert(acc_get_role_id(role_name) != 0)
    kind = 'role'
    params = (role_name, role_timeout)
    return mail_cookie_create_common(kind, params, cookie_timeout, onetime)
Exemple #31
0
def collect_user_info(req, login_time=False, refresh=False):
    """Given the mod_python request object rec or a uid it returns a dictionary
    containing at least the keys uid, nickname, email, groups, plus any external keys in
    the user preferences (collected at login time and built by the different
    external authentication plugins) and if the mod_python request object is
    provided, also the remote_ip, remote_host, referer, agent fields.
    NOTE: if req is a mod_python request object, the user_info dictionary
    is saved into req._user_info (for caching purpouses)
    setApacheUser & setUid will properly reset it.
    """
    from invenio.search_engine import get_permitted_restricted_collections
    user_info = {
        'remote_ip' : '',
        'remote_host' : '',
        'referer' : '',
        'uri' : '',
        'agent' : '',
        'uid' :-1,
        'nickname' : '',
        'email' : '',
        'group' : [],
        'guest' : '1',
        'session' : None,
        'precached_permitted_restricted_collections' : [],
        'precached_usebaskets' : False,
        'precached_useloans' : False,
        'precached_usegroups' : False,
        'precached_usealerts' : False,
        'precached_usemessages' : False,
        'precached_viewsubmissions' : False,
        'precached_useapprove' : False,
        'precached_useadmin' : False,
        'precached_usestats' : False,
        'precached_viewclaimlink' : False,
        'precached_usepaperclaim' : False,
        'precached_usepaperattribution' : False,
    }

    try:
        is_req = False
        if not req:
            uid = -1
        elif type(req) in (type(1), type(1L)):
            ## req is infact a user identification
            uid = req
        elif type(req) is dict:
            ## req is by mistake already a user_info
            try:
                assert(req.has_key('uid'))
                assert(req.has_key('email'))
                assert(req.has_key('nickname'))
            except AssertionError:
                ## mmh... misuse of collect_user_info. Better warn the admin!
                register_exception(alert_admin=True)
            user_info.update(req)
            return user_info
        else:
            is_req = True
            uid = getUid(req)
            if hasattr(req, '_user_info') and not login_time:
                user_info = req._user_info
                if not refresh:
                    return req._user_info
            req._user_info = user_info
            try:
                user_info['remote_ip'] = req.remote_ip
            except gaierror:
                #FIXME: we should support IPV6 too. (hint for FireRole)
                pass
            user_info['session'] = get_session(req).sid()
            user_info['remote_host'] = req.remote_host or ''
            user_info['referer'] = req.headers_in.get('Referer', '')
            user_info['uri'] = req.unparsed_uri or ()
            user_info['agent'] = req.headers_in.get('User-Agent', 'N/A')
        user_info['uid'] = uid
        user_info['nickname'] = get_nickname(uid) or ''
        user_info['email'] = get_email(uid) or ''
        user_info['group'] = []
        user_info['guest'] = str(isGuestUser(uid))

        if user_info['guest'] == '1' and CFG_INSPIRE_SITE:
            usepaperattribution = False
            viewclaimlink = False

            if (CFG_BIBAUTHORID_ENABLED
                and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionviewers"))):
                usepaperattribution = True

#            if (CFG_BIBAUTHORID_ENABLED
#                and usepaperattribution
#                and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers"))):
#                viewclaimlink = True
            if is_req:
                session = get_session(req)
                viewlink = False
                try:
                    viewlink = session['personinfo']['claim_in_process']
                except (KeyError, TypeError):
                    viewlink = False
            else:
                viewlink = False

            if (CFG_BIBAUTHORID_ENABLED
                and usepaperattribution
                and viewlink):
                    viewclaimlink = True

            user_info['precached_viewclaimlink'] = viewclaimlink
            user_info['precached_usepaperattribution'] = usepaperattribution

        if user_info['guest'] == '0':
            user_info['group'] = [group[1] for group in get_groups(uid)]
            prefs = get_user_preferences(uid)
            login_method = prefs['login_method']
            login_object = CFG_EXTERNAL_AUTHENTICATION[login_method]
            if login_object and ((datetime.datetime.now() - get_last_login(uid)).seconds > 3600):
                ## The user uses an external authentication method and it's a bit since
                ## she has not performed a login
                if not CFG_EXTERNAL_AUTH_USING_SSO or (
                    is_req and login_object.in_shibboleth(req)):
                    ## If we're using SSO we must be sure to be in HTTPS and Shibboleth handler
                    ## otherwise we can't really read anything, hence
                    ## it's better skip the synchronization
                    try:
                        groups = login_object.fetch_user_groups_membership(user_info['email'], req=req)
                        # groups is a dictionary {group_name : group_description,}
                        new_groups = {}
                        for key, value in groups.items():
                            new_groups[key + " [" + str(login_method) + "]"] = value
                        groups = new_groups
                    except (AttributeError, NotImplementedError, TypeError, InvenioWebAccessExternalAuthError):
                        pass
                    else: # Groups synchronization
                        from invenio.webgroup import synchronize_external_groups
                        synchronize_external_groups(uid, groups, login_method)
                        user_info['group'] = [group[1] for group in get_groups(uid)]

                    try:
                        # Importing external settings
                        new_prefs = login_object.fetch_user_preferences(user_info['email'], req=req)
                        for key, value in new_prefs.items():
                            prefs['EXTERNAL_' + key] = value
                    except (AttributeError, NotImplementedError, TypeError, InvenioWebAccessExternalAuthError):
                        pass
                    else:
                        set_user_preferences(uid, prefs)
                        prefs = get_user_preferences(uid)

                    run_sql('UPDATE user SET last_login=NOW() WHERE id=%s', (uid,))
            if prefs:
                for key, value in prefs.iteritems():
                    user_info[key.lower()] = value
            if login_time:
                ## Heavy computational information
                from invenio.access_control_engine import acc_authorize_action
                if CFG_WEBSEARCH_PERMITTED_RESTRICTED_COLLECTIONS_LEVEL > 0:
                    user_info['precached_permitted_restricted_collections'] = get_permitted_restricted_collections(user_info)
                user_info['precached_usebaskets'] = acc_authorize_action(user_info, 'usebaskets')[0] == 0
                user_info['precached_useloans'] = acc_authorize_action(user_info, 'useloans')[0] == 0
                user_info['precached_usegroups'] = acc_authorize_action(user_info, 'usegroups')[0] == 0
                user_info['precached_usealerts'] = acc_authorize_action(user_info, 'usealerts')[0] == 0
                user_info['precached_usemessages'] = acc_authorize_action(user_info, 'usemessages')[0] == 0
                user_info['precached_usestats'] = acc_authorize_action(user_info, 'runwebstatadmin')[0] == 0
                user_info['precached_viewsubmissions'] = isUserSubmitter(user_info)
                user_info['precached_useapprove'] = isUserReferee(user_info)
                user_info['precached_useadmin'] = isUserAdmin(user_info)
                usepaperclaim = False
                usepaperattribution = False
                viewclaimlink = False

                if (CFG_BIBAUTHORID_ENABLED
                    and acc_is_user_in_role(user_info, acc_get_role_id("paperclaimviewers"))):
                    usepaperclaim = True

                if (CFG_BIBAUTHORID_ENABLED
                    and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionviewers"))):
                    usepaperattribution = True

                if is_req:
                    session = get_session(req)
                    viewlink = False
                    try:
                        viewlink = session['personinfo']['claim_in_process']
                    except (KeyError, TypeError):
                        viewlink = False
                else:
                    viewlink = False

                if (CFG_BIBAUTHORID_ENABLED
                    and usepaperattribution
                    and viewlink):
                        viewclaimlink = True

#                if (CFG_BIBAUTHORID_ENABLED
#                    and ((usepaperclaim or usepaperattribution)
#                         and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers")))):
#                    viewclaimlink = True

                user_info['precached_viewclaimlink'] = viewclaimlink
                user_info['precached_usepaperclaim'] = usepaperclaim
                user_info['precached_usepaperattribution'] = usepaperattribution

    except Exception, e:
        register_exception()
def Mail_Approval_Request_to_Referee(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee of a document informing
    him/her that a request for its approval has been submitted by the
    user.

    @param categ_file_appreq: (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_appreq: (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

    @param edsrn: (string) - the name of the field in which the report
          number should be placed when the referee visits the form for making
          a decision.

    @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 report-number file:
    ########
    try:
        edsrn_file = parameters["edsrn"]
    except KeyError:
        ## No value given for the edsrn file:
        msg = "Error in Mail_Approval_Request_to_Referee function: unable " \
              "to determine the name of the file in which the document's " \
              "report number should be stored."
        raise InvenioWebSubmitFunctionError(msg)
    else:
        edsrn_file = str(edsrn_file)
        edsrn_file = os.path.basename(edsrn_file).strip()
        if edsrn_file == "":
            msg = "Error in Mail_Approval_Request_to_Referee function: " \
                  "unable to determine the name of the file in which " \
                  "the document's report number should be stored."
            raise InvenioWebSubmitFunctionError(msg)
    ########
    ## 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_appreq"]
    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_appreq"]
    except KeyError:
        ## No value given for the category regexp:
        category_rn_regexp = None
    else:
        if category_rn_regexp is not None:
            category_rn_regexp = str(category_rn_regexp).strip()
        if category_rn_regexp == "":
            category_rn_regexp = None
    #######
    ## Resolve the document type's category:
    ##
    ## This is a long process. The end result is that the category is extracted
    ## either from a file in curdir, or from the report number.
    ## If it's taken from the report number, the admin must configure the
    ## function to accept a regular expression that is used to find the
    ## category in the report number.
    ##
    if category_file is not None and category_rn_regexp is not None:
        ## It is not valid to have both a category file and a pattern
        ## describing how to extract the category from a report number.
        ## raise an InvenioWebSubmitFunctionError
        msg = "Error in Register_Approval_Request function: received " \
              "instructions to search for the document's category in " \
              "both its report number AND in a category file. Could " \
              "not determine which to use - please notify the " \
              "administrator."
        raise InvenioWebSubmitFunctionError(msg)
    elif category_file is not None:
        ## Attempt to recover the category information from a file in the
        ## current submission's working directory:
        category = ParamFromFile("%s/%s" % (curdir, category_file))
        if category is not None:
            category = category.strip()
        if category in (None, ""):
            ## The category cannot be resolved.
            msg = "Error in Register_Approval_Request function: received " \
                  "instructions to search for the document's category in " \
                  "a category file, but could not recover the category " \
                  "from that file. An approval request therefore cannot " \
                  "be registered for the document."
            raise InvenioWebSubmitFunctionError(msg)
    elif category_rn_regexp is not None:
        ## Attempt to recover the category information from the document's
        ## reference number using the regexp in category_rn_regexp:
        ##
        ## Does the category regexp contain the key-phrase "<CATEG>"?
        if category_rn_regexp.find("<CATEG>") != -1:
            ## Yes. Replace "<CATEG>" with "(?P<category>.+?)".
            ## For example, this:
            ##    ATL(-COM)?-<CATEG>-
            ## Will be transformed into this:
            ##    ATL(-COM)?-(?P<category>.+?)-
            category_rn_final_regexp = \
                category_rn_regexp.replace("<CATEG>", r"(?P<category>.+?)", 1)
        else:
            ## The regexp for category didn't contain "<CATEG>", but this is
            ## mandatory.
            msg = "Error in Register_Approval_Request function: The " \
                  "[%(doctype)s] submission has been configured to search " \
                  "for the document type's category in its reference number, " \
                  "using a poorly formed search expression (no marker for " \
                  "the category was present.) Since the document's category " \
                  "therefore cannot be retrieved, an approval request cannot " \
                  "be registered for it. Please report this problem to the " \
                  "administrator." \
                  % { 'doctype' : doctype, }
            raise InvenioWebSubmitFunctionError(msg)
        ##
        try:
            ## Attempt to compile the regexp for finding the category:
            re_categ_from_rn = re.compile(category_rn_final_regexp)
        except sre_constants.error:
            ## The expression passed to this function could not be compiled
            ## into a regexp. Register this exception and raise an
            ## InvenioWebSubmitFunctionError:
            exception_prefix = "Error in Register_Approval_Request function: " \
                               "The [%(doctype)s] submission has been " \
                               "configured to search for the document type's " \
                               "category in its reference number, using the " \
                               "following regexp: /%(regexp)s/. This regexp, " \
                               "however, could not be compiled correctly " \
                               "(created it from %(categ-search-term)s.)" \
                               % { 'doctype'       : doctype, \
                                   'regexp'        : category_rn_final_regexp, \
                                   'categ-search-term' : category_rn_regexp, }
            register_exception(prefix=exception_prefix)
            msg = "Error in Register_Approval_Request function: The " \
                  "[%(doctype)s] submission has been configured to search " \
                  "for the document type's category in its reference number, " \
                  "using a poorly formed search expression. Since the " \
                  "document's category therefore cannot be retrieved, an " \
                  "approval request cannot be registered for it. Please " \
                  "report this problem to the administrator." \
                  % { 'doctype' : doctype, }
            raise InvenioWebSubmitFunctionError(msg)
        else:
            ## Now attempt to recover the category from the RN string:
            m_categ_from_rn = re_categ_from_rn.match(rn)
            if m_categ_from_rn is not None:
                ## The pattern matched in the string.
                ## Extract the category from the match:
                try:
                    category = m_categ_from_rn.group("category")
                except IndexError:
                    ## There was no "category" group. That group is mandatory.
                    exception_prefix = \
                       "Error in Register_Approval_Request function: The " \
                       "[%(doctype)s] submission has been configured to " \
                       "search for the document type's category in its " \
                       "reference number using the following regexp: " \
                       "/%(regexp)s/. The search produced a match, but " \
                       "there was no \"category\" group in the match " \
                       "object although this group is mandatory. The " \
                       "regexp was compiled from the following string: " \
                       "[%(categ-search-term)s]." \
                       % { 'doctype'           : doctype, \
                           'regexp'            : category_rn_final_regexp, \
                           'categ-search-term' : category_rn_regexp, }
                    register_exception(prefix=exception_prefix)
                    msg = "Error in Register_Approval_Request function: The " \
                          "[%(doctype)s] submission has been configured to " \
                          "search for the document type's category in its " \
                          "reference number, using a poorly formed search " \
                          "expression (there was no category marker). Since " \
                          "the document's category therefore cannot be " \
                          "retrieved, an approval request cannot be " \
                          "registered for it. Please report this problem to " \
                          "the administrator." \
                          % { 'doctype' : doctype, }
                    raise InvenioWebSubmitFunctionError(msg)
                else:
                    category = category.strip()
                    if category == "":
                        msg = "Error in Register_Approval_Request function: " \
                              "The [%(doctype)s] submission has been " \
                              "configured to search for the document type's " \
                              "category in its reference number, but no " \
                              "category was found. The request for approval " \
                              "cannot be registered. Please report this " \
                              "problem to the administrator." \
                              % { 'doctype' : doctype, }
                        raise InvenioWebSubmitFunctionError(msg)
            else:
                ## No match. Cannot find the category and therefore cannot
                ## continue:
                msg = "Error in Register_Approval_Request function: The " \
                      "[%(doctype)s] submission has been configured to " \
                      "search for the document type's category in its " \
                      "reference number, but no match was made. The request " \
                      "for approval cannot be registered. Please report " \
                      "this problem to the administrator." \
                      % { 'doctype' : doctype, }
                raise InvenioWebSubmitFunctionError(msg)
    else:
        ## The document type has no category.
        category = ""
    ##
    ## End of category recovery
    #######
    #######
    ## Get the title and author(s) from the record:
    #######
    ## Author(s):
    rec_authors = ""
    rec_first_author    = print_record(int(sysno), 'tm', "100__a")
    rec_other_authors   = print_record(int(sysno), 'tm', "700__a")
    if rec_first_author != "":
        rec_authors += "".join(["%s\n" % author.strip() for \
                                author in rec_first_author.split("\n")])
    if rec_other_authors != "":
        rec_authors += "".join(["%s\n" % author.strip() for \
                                author in rec_other_authors.split("\n")])
    ## Title:
    rec_title = "".join(["%s\n" % title.strip() for title in \
                          print_record(int(sysno), 'tm', "245__a").split("\n")])
    ##
    #######
    ## the normal approval action
    approve_act = 'APP'
    ## Get notes about the approval request:
    approval_notes = get_approval_request_notes(doctype, rn)
    ## 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.
        if doctype == 'ATN':  ## Special case of 'RPR' action for doctype ATN
            action = ParamFromFile("%s/%s" % (curdir,'act')).strip()
            if action == 'RPR':
                notetype = ParamFromFile("%s/%s" % (curdir,'ATN_NOTETYPE')).strip()
                if notetype not in ('SLIDE','PROC'):
                    raise InvenioWebSubmitFunctionError('ERROR function Mail_Approval_Request_to_Referee:: do not recognize notetype ' + notetype)
                if notetype == 'PROC':
                    approve_act = 'APR'  # RPR PROC requires APR action to approve
                    referee_listname = "*****@*****.**"
                elif notetype == 'SLIDE':  ## SLIDES approval
                    approve_act = 'APS'  # RPR SLIDE requires APS action to approve
                    referee_listname = "*****@*****.**"
                else:
                    raise InvenioWebSubmitFunctionError('ERROR function Mail_Approval_Request_to_Referee:: do not understand notetype: ' +notetype)
            else:
                referee_listname = "service-cds-referee-%s" % doctype.lower()
                if category != "":
                    referee_listname += "-%s" % category.lower()
            mailto_addresses = referee_listname + "@cern.ch"
            if category == 'CDSTEST':
                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]" % rn
    mail_body = CFG_MAIL_BODY % \
                { 'site-name'               : CFG_SITE_NAME,
                  'report-number-fieldname' : edsrn_file,
                  'report-number'           : rn,
                  'title'                   : rec_title,
                  'authors'                 : rec_authors,
                  'site-url'                : CFG_SITE_URL,
                  'record-id'               : sysno,
                  'approval-action'         : approve_act,
                  'doctype'                 : doctype,
                  'notes'                   : approval_notes,
                  'category'                : category,
                }
    send_email(CFG_SITE_SUPPORT_EMAIL,
               mailto_addresses,
               mail_subj,
               mail_body,
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    ##
    return ""
Exemple #33
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 ""
Exemple #34
0
def User_is_Record_Owner_or_Curator(parameters, curdir, form, user_info=None):
    """
    Check that user is either the original submitter, or that it
    belongs to the role(s) given as parameter. This enables
    collaborative editing of records, so that collections can be
    curated by a group of people in addition to the original
    submitter.

    If the user has permission, the function ends silently. If not, it
    will raise an InvenioWebSubmitFunctionStop, informing the user that
    they don't have rights and sending them back to the submission web
    form.

    This function makes it unnecessary to protect the submission with
    WebAccess (i.e. 'submit' action): the function can check
    authorizations by itself.
    However if the case the action in which this function is used is
    still protected with WebAccess (eg. an authorization exists for
    the 'submit' action, in 'MBI'), ALL the possible submitters AND
    the curators groups must be linked to the authorization in order
    for WebSubmit to let users reach this function: this function then
    ensures that only curators or submitters of the record will be
    able to continue further.

    A record owner must have her email in the record metadata.

    A record curator must be in the role given as parameter to this
    function.

    WARNING: you must remember that category-based restrictions
    require you to check that the selected category matches the
    document to modify: one can select category 'foo' to modify
    a document submitted in category 'bar', given that submissions
    are indepedendant of the record they create.

    WARNING: for backward compatibility reasons, if no role is given
    as parameter, the function simply check against the WebAccess
    'submit' action, with this submission parameters. It then means
    that anybody connected to the authorization will be able to modify
    ANY of the records this submission can handle.

    @parameters:

       - curator_role: a role or mapping of roles that determine if
                       user is a curator or not. The parameter can
                       simply be the name of a WebAccess role. For eg:
                         curator_photo
                       where 'curator_photo' is a WebAccess role
                       matching curator users for this submission.

                       The parameter can also map the submission
                       categories to different roles, so that
                       different curator groups can be defined. For eg:
                         ARTICLE=curator_art|REPORT=curator_rep|*=curator_gen
                       (syntax: '|' to split mappings, and '=' to map category->role)

                       This specifies that role 'curator_art' is used
                       when category 'Article' is selected (code for
                       this category is 'ARTICLE'), 'curator_rep' when
                       'Report' ('REPORT' code) is selected, and
                       curator_gen in all other cases. * matches all
                       categories.

                       When defining a mapping category->role, and
                       category cannot be retrieved (for eg. with
                       /submit/direct URLs that do not specify
                       category), only the * rule/role is matched.
                       Eg: foo=role1|*=role2 matches role2 only

                       When no role is defined or matched, the curator
                       role is checked against the WebAccess 'submit'
                       action, for current WebSubmit doctype, action
                       and category.

        - curator_flag: the name of a file in which '1' is written if
                        current submitter is a curator. Otherwise, an
                        empty file is written.
                        If no value is given, no file is written.

    @return: Empty string.
    @Exceptions raised: InvenioWebSubmitFunctionStop when user is denied
                permission to work with the record.
    """
    global sysno

    # Get current doctype
    doctype_fd = open(os.path.join(curdir, 'doctype'))
    doctype = doctype_fd.read()
    doctype_fd.close()

    # Get current action
    act_fd = open(os.path.join(curdir, 'act'))
    act = act_fd.read()
    act_fd.close()

    # Get category. This one might not exist
    category = None
    if os.path.exists(os.path.join(curdir, 'combo%s' % doctype)):
        category_fd = open(os.path.join(curdir, 'combo%s' % doctype))
        category = category_fd.read()
        category_fd.close()

    # Get role to belong to in order to be curator. If not specifed,
    # we simply check against 'submit' WebAccess action for the current
    # WebSubmit action (for eg. 'MBI')
    curator_roles = []
    try:
        curator_role = parameters['curator_role']
    except:
        curator_role = ''
    if '=' in curator_role:
        # Admin specifed a different role for different category.
        # For eg: general=curator_gen|photo=curator_photo|*=curator_other
        curator_roles = [categ_and_role.split('=', 1)[1].strip() \
                         for categ_and_role in curator_role.split('|') if \
                         len(categ_and_role.split('=', 1)) == 2 and \
                         categ_and_role.split('=', 1)[0].strip() in (category, '*')]
    elif curator_role:
        curator_roles = [curator_role]

    ## Get the current user's e-mail address:
    user_email = user_info["email"].lower()

    ## Now get the email address(es) of the record submitter(s)/owner(s) from
    ## the record itself:
    record_owners_list = [email.lower().strip() for email in \
                          get_fieldvalues(sysno, CFG_WEBSUBMIT_RECORD_OWNER_EMAIL)]

    ## Now determine whether this user is listed in the record as an "owner"
    ## (or submitter):
    user_has_permission = False
    user_msg = ""
    if user_email not in ("", "guest") and user_email in record_owners_list:
        ## This user's email address is listed in the record. She should
        ## be allowed to work with it:
        user_has_permission = True

    # Check if user is curator
    is_curator = False
    if curator_roles:
        # Check against roles
        for role in curator_roles:
            if not acc_get_role_id(role):
                # Role is not defined
                continue
            if acc_is_user_in_role(user_info, acc_get_role_id(role)):
                # One matching role found
                user_has_permission = True
                is_curator = True
                break
    else:
        # Check against authorization for 'submit' (for backward compatibility)
        (auth_code, dummy) = acc_authorize_action(user_info, \
                                                  "submit", \
                                                  verbose=0, \
                                                  doctype=doctype, \
                                                  act=act)
        if auth_code == 0:
            ## The user is a curator for this
            ## submission/collection. Do not prevent access.
            is_curator = True
            user_has_permission = True

    try:
        curator_flag = parameters['curator_flag']
        if curator_flag:
            flag_fd = open(os.path.join(curdir, curator_flag), 'w')
            flag_fd.write(is_curator and '1' or '0')
            flag_fd.close()
    except:
        pass

    ## Finally, if the user still doesn't have permission to work with this
    ## record, raise an InvenioWebSubmitFunctionStop exception sending the
    ## user back to the form.
    if not user_has_permission:
        raise InvenioWebSubmitFunctionStop(CFG_MSG_USER_NOT_AUTHORIZED)
    return ""
    def tmpl_pagefooter(self, req=None, ln=CFG_SITE_LANG, lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

           Parameters:

          - 'ln' *string* - The language to display

          - 'lastupdated' *string* - when the page was last updated

          - 'pagefooteradd' *string* - additional page footer HTML code

           Output:

          - HTML code of the page headers
        """

        # load the right message language
        _ = gettext_set_language(ln)

        if lastupdated and lastupdated != '$Date$':
            if lastupdated.startswith("$Date: ") or \
            lastupdated.startswith("$Id: "):
                lastupdated = convert_datestruct_to_dategui(\
                                 convert_datecvs_to_datestruct(lastupdated),
                                 ln=ln)
            msg_lastupdated = _("Last updated") + ": " + lastupdated
        else:
            msg_lastupdated = ""

        user_info = collect_user_info(req)
        if acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
            tools = "<a href='/tools.py'>Repository tools</a>"
        else:
            tools = ""

        out = """
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
 <!--
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/submit?ln=%(ln)s">%(msg_submit)s</a>&nbsp;::&nbsp;<a class="footer" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(msg_personalize)s</a>&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>
  <br />-->
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
  <br />
  %(tools)s
 </div>
 <div class="pagefooterstriperight">
 <p><em>
 Articles in the SCOAP3 repository are released under a <a target="_blank" rel="license" href="http://creativecommons.org/licenses/by/3.0/"><strong>CC-BY</strong></a> license. Metadata are provided by the corresponding publishers and released under the <a target="_blank"  rel="license"
     href="http://creativecommons.org/publicdomain/zero/1.0/">
    <strong>CC0</strong>
  </a> waiver.
 </em></p>
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>

<!-- Piwik -->
<script type="text/javascript">
 var _paq = _paq || [];
 _paq.push(['trackPageView']);
 _paq.push(['enableLinkTracking']);
 (function() {
   var u="//piwik.inspirehep.net/";
   _paq.push(['setTrackerUrl', u+'piwik.php']);
   _paq.push(['setSiteId', 10]);
   var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
   g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
 })();
</script>
<noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=10" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->

</body>
</html>
        """ % {
          'siteurl': CFG_BASE_URL,
          'sitesecureurl': CFG_SITE_SECURE_URL,
          'ln': ln,
          'langlink': '?ln=' + ln,

          'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
          'sitesupportemail': CFG_SITE_SUPPORT_EMAIL,

          'msg_search': _("Search"),
          'msg_submit': _("Submit"),
          'msg_personalize': _("Personalize"),
          'msg_help': _("Help"),

          'msg_poweredby': _("Powered by"),
          'msg_maintainedby': _("Maintained by"),

          'msg_lastupdated': msg_lastupdated,
          'languagebox': self.tmpl_language_selection_box(req, ln),
          'version': CFG_VERSION,

          'pagefooteradd': pagefooteradd,
          'tools': tools,
        }
        return out
def Send_Approval_Request (parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    simple approval process.  This function is very CERN-specific and
    should be changed in case of external use.  Must be called after
    the Get_Report_Number function.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * authorfile: name of the file in which the authors are stored

       * titlefile: name of the file in which the title is stored.

       * directory: parameter used to create the URL to access the
                    files.
    """
    global rn,sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$",curdir).group(2)
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,CFG_SITE_SUPPORT_EMAIL)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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"
    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""
    if os.path.exists("%s/%s" % (curdir,parameters['titleFile'])):
        fp = open("%s/%s" % (curdir,parameters['titleFile']),"r")
        title = fp.read()
        fp.close()
        title = title.replace("\n","")
    else:
        title = ""
    title += " - %s" % date
    # create AU
    if os.path.exists("%s/%s" % (curdir,parameters['authorfile'])):
        fp = open("%s/%s" % (curdir,parameters['authorfile']), "r")
        author = fp.read()
        fp.close()
    else:
        author = ""
    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(sth) >0:
        access = sth[0][0]
    # 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 are general referees
    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
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)
    title_referee = "Request for approval of %s" % rn
    mail_referee = "The document %s has been submitted to the %s Server..\nYour approval is requested on it.\n\n" % (rn,CFG_SITE_NAME)
    mail_referee +="Title: %s\n\nAuthor(s): %s\n\n" % (title,author)
    mail_referee +="To access the document(s), select the file(s) from the location:<%s/record/%s/files/>\n\n" % (CFG_SITE_URL,sysno)
    mail_referee +="To approve/reject the document, you should go to this URL:\n<%s/approve.py?%s>\n" % (CFG_SITE_URL,access)
    mail_referee +="---------------------------------------------\nBest regards.\nThe submission team.\n"
    #Send mail to referee
    send_email(FROMADDR, addresses, title_referee, mail_referee, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
def Send_Request_For_Direct_Approval(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee asking him/her to
    approve/reject a document

    Parameters:

       * directory: parameter to the link manager program

       * addressesDAM: address of the referee(s)

       * categformatDAM: variable needed to extract the category of
                         the document and use it to derive the
                         address.

       * authorfile: name of the file containing the author list

       * titleFile: name of the file containing the title
    """
    global rn, sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$", curdir).group(2)
    FROMADDR = "%s Submission Engine <%s>" % (CFG_SITE_NAME, CFG_SITE_SUPPORT_EMAIL)
    otheraddresses = parameters["addressesDAM"]
    categformat = parameters["categformatDAM"]
    # retrieve category
    categformat = categformat.replace("<CATEG>", "([^-]*)")
    categs = re.match(categformat, rn)
    if categs is not None:
        category = categs.group(1)
    else:
        category = "unknown"
    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""
    if os.path.exists("%s/%s" % (curdir, parameters["titleFile"])):
        fp = open("%s/%s" % (curdir, parameters["titleFile"]), "r")
        title = fp.read()
        fp.close()
        title = title.replace("\n", "")
    else:
        title = ""
    title += " - %s" % date
    # create AU
    if os.path.exists("%s/%s" % (curdir, parameters["authorfile"])):
        fp = open("%s/%s" % (curdir, parameters["authorfile"]), "r")
        author = fp.read()
        fp.close()
    else:
        author = ""
    # we get the referee password
    # sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    # if len(sth) >0:
    # access = sth[0][0]
    # Build referee's email address
    refereeaddress = ""
    # Try to retrieve the publication committee chair's email from the role database
    for user in acc_get_role_users(acc_get_role_id("projectleader_%s_%s" % (doctype, category))):
        refereeaddress += user[1] + ","
    # And if there are general referees
    for user in acc_get_role_users(acc_get_role_id("projectleader_%s_*" % doctype)):
        refereeaddress += user[1] + ","
    refereeaddress = re.sub(",$", "", refereeaddress)
    # Creation of the mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$", "", addresses)
    title_referee = "Request for direct approval of %s" % rn
    mail_referee = (
        "The document %s has been asked direct approval to the %s Server..\nYour approval is requested on it.\n\n"
        % (rn, CFG_SITE_NAME)
    )
    mail_referee += "Title: %s\n\nAuthor(s): %s\n\n" % (title, author)
    mail_referee += "To access the document(s), select the file(s) from the location:<%s/%s/%s/files/>\n\n" % (
        CFG_SITE_URL,
        CFG_SITE_RECORD,
        sysno,
    )
    mail_referee += (
        "To approve/reject the document, you should go to this URL:\n<%s/publiline.py?doctype=%s&categ=%s&RN=%s>\n"
        % (CFG_SITE_URL, doctype, category, rn)
    )
    mail_referee += "---------------------------------------------\nBest regards.\nThe submission team.\n"
    # Send mail to referee
    send_email(FROMADDR, addresses, title_referee, mail_referee, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
Exemple #38
0
def Send_Request_For_Refereeing_Process(parameters,
                                        curdir,
                                        form,
                                        user_info=None):
    global rn, sysno
    # variables declaration
    doctype = re.search(".*/([^/]*)/([^/]*)/[^/]*$", curdir).group(2)
    FROMADDR = '%s Submission Engine <%s>' % (CFG_SITE_NAME,
                                              CFG_SITE_SUPPORT_EMAIL)
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # retrieve category
    categformat = categformat.replace("<CATEG>", "([^-]*)")
    categs = re.match(categformat, rn)
    if categs is not None:
        category = categs.group(1)
    else:
        category = "unknown"
    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""
    if os.path.exists("%s/%s" % (curdir, parameters['titleFile'])):
        fp = open("%s/%s" % (curdir, parameters['titleFile']), "r")
        title = fp.read()
        fp.close()
        title = title.replace("\n", "")
    else:
        title = ""
    title += " - %s" % date
    # create AU
    if os.path.exists("%s/%s" % (curdir, parameters['authorfile'])):
        fp = open("%s/%s" % (curdir, parameters['authorfile']), "r")
        author = fp.read()
        fp.close()
    else:
        author = ""
    # we get the referee password
    #sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    #if len(sth) >0:
    #access = sth[0][0]
    # Build referee's email address
    refereeaddress = ""
    # Try to retrieve the publication committee chair's email from the role database
    for user in acc_get_role_users(
            acc_get_role_id("pubcomchair_%s_%s" % (doctype, category))):
        refereeaddress += user[1] + ","
    # And if there are general referees
    for user in acc_get_role_users(
            acc_get_role_id("pubcomchair_%s_*" % doctype)):
        refereeaddress += user[1] + ","
    refereeaddress = re.sub(",$", "", refereeaddress)
    # Creation of the mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$", "", addresses)
    title_referee = "Request for refereeing process of %s" % rn
    mail_referee = "The document %s has been asked for refereing process to the %s Server..\nYour have to select an editorial board for it.\n\n" % (
        rn, CFG_SITE_NAME)
    mail_referee += "Title: %s\n\nAuthor(s): %s\n\n" % (title, author)
    mail_referee += "To access the document(s), select the file(s) from the location:<%s/%s/%s/files/>\n\n" % (
        CFG_SITE_URL, CFG_SITE_RECORD, sysno)
    mail_referee += "To select an editorial board, you should go to this URL:\n<%s/publiline.py?doctype=%s&categ=%s&RN=%s>\n" % (
        CFG_SITE_URL, doctype, category, rn)
    mail_referee += "---------------------------------------------\nBest regards.\nThe submission team.\n"
    #Send mail to referee
    send_email(FROMADDR,
               addresses,
               title_referee,
               mail_referee,
               copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
def DPI_Mail_Approval_Request_to_Referee(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    approval process related to the deletion of a post record.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * directory: parameter used to create the URL to access the
                    files.
    """

    global rn, sysno
    doctype = 'BSIREF'
    approval_action = 'APO'
    action = ParamFromFile("%s/%s" % (curdir,'act')).strip()
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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"

    # create TI
    if os.path.exists("%s/date" % curdir):
        fp = open("%s/date" % curdir, "r")
        date = fp.read()
        fp.close()
    else:
        date = ""

    post_author = "".join(["%s" % author.strip() for author in \
                          get_fieldvalues(int(sysno), "100__a")])

    post_title = "".join(["%s" % title.strip() for title in \
                          get_fieldvalues(int(sysno), "245__a")])
    
    post_url = "".join(["%s" % url.strip() for url in \
                         get_fieldvalues(int(sysno), "520__u")])

    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(sth) >0:
        access = sth[0][0]

    # 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 are general referees
    for user in acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
        refereeaddress += user[1] + ","

    refereeaddress = re.sub(",$","",refereeaddress)
    # Creation of the e-mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)

    # Send the email:
    mail_subject = "Request for post deletion approval : [%(id)s]"
    if post_title:
        mail_subject = mail_subject % {'id': post_title}
    else:
        mail_subject = mail_subject % {'id': post_url}

    mail_body = CFG_MAIL_BODY % \
                {'title': post_title,
                 'author': post_author,
                 'post_url': post_url,
                 'record_id': sysno,
                 'site_name': CFG_SITE_NAME,
                 'site_url': CFG_SITE_URL,
                 'doctype': doctype,
                 'access': access,
                 'approval_action': approval_action,
                 'rn': rn
                 }
    send_email(CFG_SITE_SUPPORT_EMAIL, addresses,
               mail_subject, mail_body, copy_to_admin=CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN)
    return ""
Exemple #40
0
    try:
        uid = getUid(req)
    except Error, e:
        return errorMsg(str(e), req, ln=ln)
    (auth_code, auth_message) = acc_authorize_action(req, "cfgwebsubmit", verbose=0)
    if auth_code != 0:
        ## user is not authorised to use WebSubmit Admin:
        return page_not_authorized(req=req, text=auth_message)

    # request for deleting a user
    if todo == "deleteuser":
        acc_delete_user_role(id, name_role=role)
    # request for adding user(s)
    if todo == "adduser":
        role = "referee_%s_%s" % (doctype, categ[1])
        roleId = acc_get_role_id(role)
        # if the role does not exists, we create it
        if roleId == 0:
            if acc_add_role(role, "referees for document type %s category %s" % (doctype, categ[1])) == 0:
                return errorMsg("Cannot create referee role", req)
            else:
                roleId = acc_get_role_id(role)
            # if the action does not exist, we create it
            actionId = acc_get_action_id("referee")
            if actionId == 0:
                if acc_add_action("referee", "", "no", ("doctype","categ")) == 0:
                    return errorMsg("Cannot create action 'referee'", req)
                else:
                    actionId = acc_get_action_id("referee")
            #create arguments
            arg1Id = acc_add_argument("doctype", doctype)
def SBI_Mail_Approval_Request_to_Referee(parameters, curdir, form, user_info=None):
    """
    This function sends an email to the referee in order to start the
    approval process related to the submission of a blog record.

    Parameters:

       * addressesDAM: 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
                       [categformatDAM] parameter replaces this
                       string.
                       eg.:"<CATEG>[email protected]"

       * categformatDAM: 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"

       * titlefile: name of the file in which the title is stored.

       * directory: parameter used to create the URL to access the
                    files.
    """

    global rn, sysno
    sequence_id = bibtask_allocate_sequenceid(curdir)
    doctype = 'BSIREF'
    approval_action = 'APS'
    action = ParamFromFile("%s/%s" % (curdir,'act')).strip()
    otheraddresses = parameters['addressesDAM']
    categformat = parameters['categformatDAM']
    # 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"

    if os.path.exists("%s/%s" % (curdir,parameters['titleFile'])):
        fp = open("%s/%s" % (curdir,parameters['titleFile']),"r")
        title = fp.read()
        fp.close()
        title = title.replace("\n","")
    else:
        title = ""

    # we get the referee password
    sth = run_sql("SELECT access FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(sth) >0:
        access = sth[0][0]

    # 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 are general referees
    for user in acc_get_role_users(acc_get_role_id("referee_%s_*" % doctype)):
        refereeaddress += user[1] + ","

    refereeaddress = re.sub(",$","",refereeaddress)
    # Creation of the e-mail for the referee
    addresses = ""
    if refereeaddress != "":
        addresses = refereeaddress + ","
    if otheraddresses != "":
        addresses += otheraddresses
    else:
        addresses = re.sub(",$","",addresses)

    try:
        fp = open("%s/BSI_URL" % curdir,"r")
        blog_url = fp.read().replace ("\n"," ")
        fp.close()
    except:
        blog_url = ""

    try:
        fp = open("%s/BSI_LICENSE" % curdir,"r")
        blog_license = fp.read().replace ("\n"," ")
        fp.close()
    except:
        blog_license = ""

    try:
        fp = open("%s/BSI_TOPIC" % curdir,"r")
        blog_topic = fp.read().replace ("\n"," ")
        fp.close()
    except:
        blog_topic = ""

    ## Send the email:
    mail_subject = "Request for approval of new blog submission: [%s]" % rn

    mail_body = CFG_MAIL_BODY % \
                {'title': title,
                 'blog_url': blog_url,
                 'topic': blog_topic,
                 'license': blog_license,
                 'record_id': sysno,
                 'site_name' : CFG_SITE_NAME,
                 'site_url': CFG_SITE_URL,
                 'doctype': doctype,
                 'access': access,
                 'approval_action': approval_action,
                 'rn': rn
                 }
    scheduled_send_email(CFG_SITE_SUPPORT_EMAIL, addresses,
                         mail_subject, mail_body,
                         other_bibtasklet_arguments=['-I', str(sequence_id)])
    return ""
    def tmpl_pagefooter(self,
                        req=None,
                        ln=CFG_SITE_LANG,
                        lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

           Parameters:

          - 'ln' *string* - The language to display

          - 'lastupdated' *string* - when the page was last updated

          - 'pagefooteradd' *string* - additional page footer HTML code

           Output:

          - HTML code of the page headers
        """

        # load the right message language
        _ = gettext_set_language(ln)

        if lastupdated and lastupdated != '$Date$':
            if lastupdated.startswith("$Date: ") or \
            lastupdated.startswith("$Id: "):
                lastupdated = convert_datestruct_to_dategui(\
                                 convert_datecvs_to_datestruct(lastupdated),
                                 ln=ln)
            msg_lastupdated = _("Last updated") + ": " + lastupdated
        else:
            msg_lastupdated = ""

        user_info = collect_user_info(req)
        if acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
            tools = "<a href='/tools.py'>Repository tools</a>"
        else:
            tools = ""

        out = """
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
 <!--
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/submit?ln=%(ln)s">%(msg_submit)s</a>&nbsp;::&nbsp;<a class="footer" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(msg_personalize)s</a>&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>
  <br />-->
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
  <br />
  %(tools)s
 </div>
 <div class="pagefooterstriperight">
 <p><em>
 Articles in the SCOAP3 repository are released under a <a target="_blank" rel="license" href="http://creativecommons.org/licenses/by/3.0/"><strong>CC-BY</strong></a> license. Metadata are provided by the corresponding publishers and released under the <a target="_blank"  rel="license"
     href="http://creativecommons.org/publicdomain/zero/1.0/">
    <strong>CC0</strong>
  </a> waiver.
 </em></p>
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>

<!-- Piwik -->
<script type="text/javascript">
 var _paq = _paq || [];
 _paq.push(['trackPageView']);
 _paq.push(['enableLinkTracking']);
 (function() {
   var u="//piwik.inspirehep.net/";
   _paq.push(['setTrackerUrl', u+'piwik.php']);
   _paq.push(['setSiteId', 10]);
   var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
   g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
 })();
</script>
<noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=10" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->

</body>
</html>
        """ % {
            'siteurl': CFG_BASE_URL,
            'sitesecureurl': CFG_SITE_SECURE_URL,
            'ln': ln,
            'langlink': '?ln=' + ln,
            'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
            'sitesupportemail': CFG_SITE_SUPPORT_EMAIL,
            'msg_search': _("Search"),
            'msg_submit': _("Submit"),
            'msg_personalize': _("Personalize"),
            'msg_help': _("Help"),
            'msg_poweredby': _("Powered by"),
            'msg_maintainedby': _("Maintained by"),
            'msg_lastupdated': msg_lastupdated,
            'languagebox': self.tmpl_language_selection_box(req, ln),
            'version': CFG_VERSION,
            'pagefooteradd': pagefooteradd,
            'tools': tools,
        }
        return out
def index(req,
          c=CFG_SITE_NAME,
          ln=CFG_SITE_LANG,
          todo="",
          id="",
          doctype="",
          categ="",
          addusers="",
          warningText="",
          role=""):
    """Main entry point for the management of referees."""
    ln = wash_language(ln)
    # get user ID:
    uid = getUid(req)
    (auth_code, auth_message) = acc_authorize_action(req,
                                                     "cfgwebsubmit",
                                                     verbose=0)
    if auth_code != 0:
        ## user is not authorised to use WebSubmit Admin:
        return page_not_authorized(req=req, text=auth_message)

    # request for deleting a user
    if todo == "deleteuser":
        acc_delete_user_role(id, name_role=role)
    # request for adding user(s)
    if todo == "adduser":
        role = "referee_%s_%s" % (doctype, categ[1])
        roleId = acc_get_role_id(role)
        # if the role does not exists, we create it
        if roleId == 0:
            if acc_add_role(
                    role, "referees for document type %s category %s" %
                (doctype, categ[1])) == 0:
                return errorMsg("Cannot create referee role", req, uid)
            else:
                roleId = acc_get_role_id(role)
            # if the action does not exist, we create it
            actionId = acc_get_action_id("referee")
            if actionId == 0:
                if acc_add_action("referee", "", "no",
                                  ("doctype", "categ")) == 0:
                    return errorMsg("Cannot create action 'referee'", req, uid)
                else:
                    actionId = acc_get_action_id("referee")
            #create arguments
            arg1Id = acc_add_argument("doctype", doctype)
            arg2Id = acc_add_argument("categ", categ[1])
            # then link the role with the action
            if acc_add_role_action_arguments(roleId, actionId, -1, 0, 0,
                                             [arg1Id, arg2Id]) == 0:
                return errorMsg("Cannot link role with action", req, uid)
        roleId = acc_get_role_id(role)
        # For each id in the array
        if isinstance(addusers, types.ListType):
            for adduser in addusers:
                # First check  whether this id is not already associated with this rule
                myRoles = acc_get_user_roles(adduser)
                if not roleId in myRoles:
                    # Actually add the role to the user
                    acc_add_user_role(adduser, roleId)
                else:
                    warningText = '<span style="color:#f00">Sorry... This user is already a referee for this category.</span>'
        else:
            # First check  whether this id is not already associated with this rule
            myRoles = acc_get_user_roles(addusers)
            if not roleId in myRoles:
                # Actually add the role to the user
                acc_add_user_role(addusers, roleId)
            else:
                warningText = '<span style="color:#f00">Sorry... This user is already a referee for this category.</span>'
    return page(title="websubmit admin - referee selection",
                body=displayRefereesPage(doctype, warningText),
                description="",
                keywords="",
                uid=uid,
                language=ln,
                req=req)