Example #1
0
def regenerate(req, journal_name="", issue="", ln=CFG_SITE_LANG,
               confirmed_p="", publish_draft_articles_p=""):
    """
    Clears the cache for the given issue.
    """
    navtrail_previous_links = wjn.getnavtrail(' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a> &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">%s</a>' % (CFG_SITE_URL, CFG_SITE_URL, journal_name, journal_name))

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
        issue_number = wash_issue_number(ln, journal_name,
                                         issue)
        confirmed_p = wash_url_argument(confirmed_p, 'str') == "confirmed"
        publish_draft_articles_p = wash_url_argument(publish_draft_articles_p, 'str') == "move"

    except InvenioWebJournalNoJournalOnServerError, e:
        register_exception(req=req)
        return e.user_box()
Example #2
0
def issue_control(req, journal_name="", issue=[],
                  ln=CFG_SITE_LANG, action="cfg"):
    """
    Page that allows full control over creating, backtracing, adding to,
    removing from issues.
    """
    navtrail_previous_links = wjn.getnavtrail(' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a> &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">%s</a>' % (CFG_SITE_URL, CFG_SITE_URL, journal_name, journal_name))

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)
    try:
        journal_name = wash_journal_name(ln, journal_name)
        action = wash_url_argument(action, 'str')
        issue = wash_url_argument(issue, 'list')
        issues = [wash_issue_number(ln,journal_name, _issue) \
                  for _issue in issue \
                  if _issue != "ww/YYYY"]
    except InvenioWebJournalNoJournalOnServerError, e:
        register_exception(req=req)
        return e.user_box()
Example #3
0
def configure(req, journal_name=None, ln=CFG_SITE_LANG, xml_config=u'', action='edit'):
    """
    Let admins configure the journal settings
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    if journal_name is None:
        navtrail_previous_links = wjn.getnavtrail(' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a>' % CFG_SITE_URL)
    else:
        navtrail_previous_links = wjn.getnavtrail(' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a> &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">%s</a>' % (CFG_SITE_URL, CFG_SITE_URL, journal_name, journal_name))

    if action in ['add', 'addDone']:
        page_title = _('Add Journal')
    else:
        page_title = _("Edit Settings")

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name, guess=False)
        xml_config = wash_url_argument(xml_config, 'str')
        action = wash_url_argument(action, 'str')
    except InvenioWebJournalNoJournalOnServerError, e:
        # Ok, no journal. Let the admin add one...
        pass
def perform_request_comments(req=None, ln=CFG_SITE_LANG, uid="", comID="", recID="", reviews=0, abuse=False, collection=""):
    """
    Display the list of comments/reviews along with information about the comment.

    Display the comment given by its ID, or the list of comments for
    the given record ID.
    If abuse == True, only list records reported as abuse.
    If comID and recID are not provided, list all comments, or all
    abused comments (check parameter 'abuse')
    """
    ln = wash_language(ln)
    uid = wash_url_argument(uid, 'int')
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    reviews = wash_url_argument(reviews, 'int')
    collection = wash_url_argument(collection, 'str')

    user_info = collect_user_info(req)
    user_collections = ['Show all']
    user_collections.extend(get_user_collections(req))
    if collection and collection != 'Show all':
        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatecomments', collection=collection)
        if auth_code:
            return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                            comID=comID,
                                                            recID=recID,
                                                            comment_data=None,
                                                            reviews=reviews,
                                                            error=1,
                                                            user_collections=user_collections,
                                                            collection=collection)
    if collection:
        if recID or uid:
            comments = query_get_comments(uid, comID, recID, reviews, ln, abuse=abuse, user_collections=user_collections, collection=collection)
        else:
            comments = query_get_comments('', comID, '', reviews, ln, abuse=abuse, user_collections=user_collections, collection=collection)
    else:
        if recID or uid:
            comments = query_get_comments(uid, comID, recID, reviews, ln, abuse=abuse, user_collections=user_collections, collection=user_collections[0])
        else:
            comments = query_get_comments('', comID, '', reviews, ln, abuse=abuse, user_collections=user_collections, collection=user_collections[0])
    if comments:
        return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                        comID=comID,
                                                        recID=recID,
                                                        comment_data=comments,
                                                        reviews=reviews,
                                                        error=0,
                                                        user_collections=user_collections,
                                                        collection=collection)
    else:
        return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                        comID=comID,
                                                        recID=recID,
                                                        comment_data=comments,
                                                        reviews=reviews,
                                                        error=2,
                                                        user_collections=user_collections,
                                                        collection=collection)
Example #5
0
def kb_edit_mapping(req, kb, key, mapFrom, mapTo,
                    update="", delete="", sortby="to", ln=CFG_SITE_LANG):
    """
    Edit a mapping to in kb. Edit can be "update old value" or "delete existing value"

    @param kb the knowledge base id to edit
    @param key the key of the mapping that will be modified
    @param mapFrom the new key of the mapping
    @param mapTo the new value of the mapping
    @param update contains a value if the mapping is to be updated
    @param delete contains a value if the mapping is to be deleted
    @param sortby the sorting criteria ('from' or 'to')
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

    try:
        dummy = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        kb_id = wash_url_argument(kb, 'int')
        kb_name = bibknowledge.get_kb_name(kb_id)

        if kb_name is None:
            return page(title=_("Unknown Knowledge Base"),
                        body = "",
                        language=ln,
                        navtrail = navtrail_previous_links,
                        errors = [("ERR_KB_ID_UNKNOWN", kb)],
                        lastupdated=__lastupdated__,
                        req=req)


        key = wash_url_argument(key, 'str')
        if delete != "":
            #Delete
            bibknowledge.remove_kb_mapping(kb_name, key)
        if update != "":
            #Update
            new_key = wash_url_argument(mapFrom, 'str')
            new_value = wash_url_argument(mapTo, 'str')
            bibknowledge.update_kb_mapping(kb_name, key, new_key, new_value)

        redirect_to_url(req, "kb?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #6
0
def new_dataset(req, title=None, paper=None, authors=None, description=None,
                dataset_file=None, doi="", submitter_name=None,
                submitter_email=None, comments=None):
    """Form handler for dataset submissions."""
    import uuid

    title = wash_url_argument(title, "str")
    paper = wash_url_argument(paper, "str")
    authors = wash_url_argument(authors, "str")
    description = wash_url_argument(description, "str")
    submitter_name = wash_url_argument(submitter_name, "str")
    submitter_email = wash_url_argument(submitter_email, "str")
    comments = wash_url_argument(comments, "str")

    dataset_file = wash_url_argument(dataset_file, "str")
    tmp_id = str(uuid.uuid1())
    if dataset_file:
        f = open(CFG_TMPSHAREDDIR + 'dataset-submission-' + tmp_id, 'wb')
        f.write(req.form["dataset_file"].file.read())
        f.close()

    res = submit_email_ticket(title, paper, authors, description,
                              tmp_id, req.form["dataset_file"].filename,
                              doi, submitter_name, submitter_email, comments)

    if res:
        return redirect_to_url(
            req,
            "%s/data_submission.py/data_submission_success?title=%s" % (CFG_SITE_URL, title)
        )
    else:
        return redirect_to_url(
            req,
            "%s/data_submission.py/data_submission_fail?title=%s" % (CFG_SITE_URL, title)
        )
Example #7
0
def format_template_show_attributes(req, bft, ln=CFG_SITE_LANG, new=0):
    """
    Page for template name and descrition attributes edition.

    This is also the first page shown when a format template
    has just been added. In that case new is different from
    False and we can offer specific option to user (for ex
    let him make a duplicate of existing template).

    @param req: the request object
    @param ln: language
    @param bft: the name of the template to show
    @param new: if "False", the template has not just been added
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Format Templates")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        format_template = wash_url_argument(bft, 'str')
        format_name = bibformat_engine.get_format_template_attrs(bft)['name']
        is_new = wash_url_argument(new, 'int')

        if not bibformatadminlib.can_read_format_template(bft): #No read permission
            try:
                raise InvenioBibFormatError(_('Format template %s cannot not be read. %s') % (format_template, ""))
            except InvenioBibFormatError, exc:
                register_exception(req=req)
                return page(title=_("Restricted Format Template"),
                            body = """You don't have permission
                            to view this format template.""",
                            language=ln,
                            navtrail = navtrail_previous_links,
                            lastupdated=__lastupdated__,
                            req=req)

        return page(title=_("Format Template %s Attributes"%format_name),
                    body=bibformatadminlib.perform_request_format_template_show_attributes(bft, ln=ln, new=is_new),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links ,
                    lastupdated=__lastupdated__,
                    req=req)
Example #8
0
def kb_delete(req, kb, ln=CFG_SITE_LANG, chosen_option=""):
    """
    Deletes an existing kb

    @param kb the kb id to delete
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a> &gt; %s''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"), _("Delete Knowledge Base"))

    try:
        dummy = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        kb_id = wash_url_argument(kb, 'int')
        kb_name = bibknowledge.get_kb_name(kb_id)
        if kb_name is None:
            return page(title=_("Unknown Knowledge Base"),
                        body = "",
                        language=ln,
                        navtrail = navtrail_previous_links,
                        errors = [("ERR_KB_ID_UNKNOWN", kb)],
                        lastupdated=__lastupdated__,
                        req=req)

        #Ask confirmation to user if not already done
        chosen_option = wash_url_argument(chosen_option, 'str')
        if chosen_option == "":
            return dialog_box(req=req,
                              ln=ln,
                              title="Delete %s" % kb_name,
                              message="""Are you sure you want to
                              delete knowledge base <i>%s</i>?""" % kb_name,
                              navtrail=navtrail_previous_links,
                              options=[_("Cancel"), _("Delete")])

        elif chosen_option==_("Delete"):
            bibknowledge.delete_kb(kb_name)

        redirect_to_url(req, "kb?ln=%(ln)s" % {'ln':ln})
    else:
        navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb">%s</a>''' % (CFG_SITE_SECURE_URL, _("Manage Knowledge Bases"))

        return page_not_authorized(req=req, text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #9
0
def output_format_update_attributes(req, bfo, ln=CFG_SITE_LANG,
                                    name = "", description="",
                                    code="", content_type="",
                                    names_trans=[], visibility="0"):
    """
    Update the name, description and code of given output format

    @param req: the request object
    @param ln: language
    @param description: the new description
    @param name: the new name
    @param code: the new short code (== new bfo) of the output format
    @param content_type: the new content_type of the output format
    @param bfo: the filename of the output format to update
    @param names_trans: the translations in the same order as the languages from get_languages()
    @param visibility: the visibility of the output format in the output formats list (public pages)
    @return: a web page (or redirection to a web page)
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:

        name = wash_url_argument(name, 'str')
        description = wash_url_argument(description, 'str')
        bfo = wash_url_argument(bfo, 'str')
        code = wash_url_argument(code, 'str')
        visibility = wash_url_argument(visibility, 'int')
        bfo = bibformatadminlib.update_output_format_attributes(bfo,
                                                                name,
                                                                description,
                                                                code,
                                                                content_type,
                                                                names_trans,
                                                                visibility)

        redirect_to_url(req, "output_format_show?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln,
                                                                           'bfo':bfo,
                                                                           'names_trans':names_trans})
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg)
Example #10
0
def output_formats_manage(req, ln=CFG_SITE_LANG, sortby="code"):
    """
    Main page for output formats management. Check for authentication and print output formats list.

    @param req: the request object
    @param ln: language
    @param sortby: the sorting crieteria (can be 'code' or 'name')
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail()

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        sortby = wash_url_argument(sortby, 'str')
        return page(title=_("Manage Output Formats"),
                body=bibformatadminlib.perform_request_output_formats_management(ln=ln, sortby=sortby),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #11
0
def format_element_test(req, bfe, ln=CFG_SITE_LANG, param_values=None):
    """
    Allows user to test element with different parameters and check output

    'param_values' is the list of values to pass to 'format'
    function of the element as parameters, in the order ...
    If params is None, this means that they have not be defined by user yet.

    @param bfe: the name of the element to test
    @param ln: language
    @param param_values: the list of parameters to pass to element format function
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>''' %( CFG_SITE_URL, ln , _("Format Elements Documentation")))

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfe = wash_url_argument(bfe, 'str')
        user_info = collect_user_info(req)
        uid = user_info['uid']
        return page(title=_("Test Format Element %s" % bfe),
                body=bibformatadminlib.perform_request_format_element_test(bfe=bfe,
                                                                           ln=ln,
                                                                           param_values=param_values,
                                                                           user_info=user_info),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #12
0
def format_template_show_dependencies(req, bft, ln=CFG_SITE_LANG):
    """
    Show the dependencies (on elements) of the given format.

    @param req: the request object
    @param ln: language
    @param bft: the filename of the template to show
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Format Templates")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        format_template = wash_url_argument(bft, 'str')
        format_name = bibformat_engine.get_format_template_attrs(bft)['name']

        return page(title=_("Format Template %s Dependencies" % format_name),
                    body=bibformatadminlib.perform_request_format_template_show_dependencies(bft, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)

    else:
        return page_not_authorized(req=req, text=auth_msg)
Example #13
0
def hot(req, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    View most active comments/reviews
    @param req: request object to obtain user information
    @param ln: language
    @param comments: boolean enabled for comments, disabled for reviews
    @param top: number of results to be shown
    @param collection: filter results by collection
    """
    ln = wash_language(ln)
    collection = wash_url_argument(collection, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgwebcomment')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    return page(title=(comments=='0' and _("View most reviewed records") or
                           _("View most commented records")),
                    body=perform_request_hot(req, ln=ln, comments=comments, top=top, collection=collection),
                    uid=user_info['uid'],
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
Example #14
0
def reference_add(req, record_id, references, url, email, comments):
    """
    Form handler for requests coming from HRA format

    Used when the record has no references

    """
    record_id = wash_url_argument(record_id, "int")
    references = wash_url_argument(references, "str")
    url = wash_url_argument(url, "str")
    email = wash_url_argument(email, "str")
    comments = wash_url_argument(comments, "str")

    submit_reference_add_ticket(record_id, references, url, email, comments)

    return redirect_to_url(req, "%s/reference_update.py/reference_add_success?record_id=%s" % (CFG_SITE_URL, record_id))
Example #15
0
def format_templates_manage(req, ln=CFG_SITE_LANG, checking='0'):
    """
    Main page for formats templates management. Check for authentication and print formats list.

    @param req: the request object
    @param ln: language
    @param checking: if 0, basic checking. Else perform extensive checking (time-consuming)
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail()

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        checking_level = wash_url_argument(checking, 'int')
        return page(title=_("Manage Format Templates"),
                body=bibformatadminlib.perform_request_format_templates_management(ln=ln, checking=checking_level),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
def output_format_show(
    req, bfo, ln=CFG_SITE_LANG, r_fld=[], r_val=[], r_tpl=[], default="", r_upd="", chosen_option="", **args
):
    """
    Show a single output format. Check for authentication and print output format settings.

    The page either shows the output format from file, or from user's
    POST session, as we want to let him edit the rules without
    saving. Policy is: r_fld, r_val, rules_tpl are list of attributes
    of the rules.  If they are empty, load from file. Else use
    POST. The i th value of each list is one of the attributes of rule
    i. Rule i is the i th rule in order of evaluation.  All list have
    the same number of item.

    r_upd contains an action that has to be performed on rules. It
    can composed of a number (i, the rule we want to modify) and an
    operator : "save" to save the rules, "add" or "del".
    syntax: operator [number]
    For eg: r_upd = _("Save Changes") saves all rules (no int should be specified).
    For eg: r_upd = _("Add New Rule") adds a rule (no int should be specified).
    For eg: r_upd = _("Remove Rule") + " 5"  deletes rule at position 5.
    The number is used only for operation delete.

    An action can also be in **args. We must look there for string starting
    with '(+|-) [number]' to increase (+) or decrease (-) a rule given by its
    index (number).
    For example "+ 5" increase priority of rule 5 (put it at fourth position).
    The string in **args can be followed by some garbage that looks like .x
    or .y, as this is returned as the coordinate of the click on the
    <input type="image">. We HAVE to use args and reason on its keys, because for <input> of
    type image, iexplorer does not return the value of the tag, but only the name.

    Action is executed only if we are working from user's POST session
    (means we must have loaded the output format first, which is
    totally normal and expected behaviour)


    @param req: the request object
    @param bfo: the filename of the output format to show
    @param ln: language
    @param r_fld: the list of 'field' attribute for each rule
    @param r_val: the list of 'value' attribute for each rule
    @param r_tpl: the list of 'template' attribute for each rule
    @param default: the default format template used by this output format
    @param r_upd: the rule that we want to increase/decrease in order of evaluation
    @param chosen_option: emptry string when user has not yet confirmed to go on
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        """ &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>"""
        % (CFG_SITE_URL, ln, _("Manage Output Formats"))
    )
    code = wash_url_argument(bfo, "str")

    try:
        uid = getUid(req)
    except MySQLdb.Error, e:
        return error_page(req)
Example #17
0
def format_element_show_dependencies(req, bfe, ln=CFG_SITE_LANG):
    """
    Shows format element dependencies

    @param req: the request object
    @param req: the request object
    @param bfe: the name of the bfe to show
    @param ln: language
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln , _("Format Elements Documentation")))
    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfe = wash_url_argument(bfe, 'str')
        return page(title=_("Format Element %s Dependencies" % bfe),
                body=bibformatadminlib.perform_request_format_element_show_dependencies(bfe=bfe, ln=ln),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
def perform_request_delete(comID=-1, recID=-1, uid=-1, reviews="", ln=CFG_SITE_LANG):
    """
    """
    from search_engine import record_exists

    warnings = []

    ln = wash_language(ln)
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    uid = wash_url_argument(uid, 'int')
    # parameter reviews is deduced from comID when needed

    if comID is not None and recID is not None and uid is not None:
        if comID <= 0 and recID <= 0 and uid <= 0:
            if comID != -1:
                warnings.append(("WRN_WEBCOMMENT_ADMIN_INVALID_COMID",))
            return (webcomment_templates.tmpl_admin_delete_form(ln, warnings), None, warnings)

        if comID > 0 and not recID > 0:
            comment = query_get_comment(comID)

            if comment:
                # Figure out if this is a review or a comment
                c_star_score = 5
                if comment[c_star_score] > 0:
                    reviews = 1
                else:
                    reviews = 0
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                warnings.append(('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return (webcomment_templates.tmpl_admin_delete_form(ln, warnings), None, warnings)

        elif recID > 0:
            if record_exists(recID):
                comID = ''
                reviews = wash_url_argument(reviews, 'int')
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                warnings.append(('WRN_WEBCOMMENT_ADMIN_RECID_INEXISTANT', comID))
                return (webcomment_templates.tmpl_admin_delete_form(ln, warnings), None, warnings)
        else:
            return (webcomment_templates.tmpl_admin_delete_form(ln, warnings), None, warnings)

    else:
        return (webcomment_templates.tmpl_admin_delete_form(ln, warnings), None, warnings)
def perform_request_undel_single_com(ln=CFG_SITE_LANG, id=id):
    """
    Mark comment referenced by id as active
    """
    ln = wash_language(ln)
    id = wash_url_argument(id, 'int')

    return query_undel_single_comment(id)
def getnavtrail(previous = '', ln=CFG_SITE_LANG):
    """Get the navtrail"""
    previous = wash_url_argument(previous, 'str')
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail = """<a class="navtrail" href="%s/help/admin">%s</a> """ % (CFG_SITE_URL, _("Admin Area"))
    navtrail = navtrail + previous
    return navtrail
Example #21
0
def data_submission_success(req, title, ticketres=None):
    """Submission confirmation message."""
    body = """
    <br/><b>Thanks for your submission!</b><br/>
    <p>We will get back to you as soon as the submission of the dataset <i>%s</i> is processed!</p>
    """ % (wash_url_argument(title, "str"))

    return page(req=req, title="Dataset submitted", body=body)
Example #22
0
def data_submission_fail(req, title, ticketres=None):
    """Submission error message."""
    body = """
    <br/><b>Your submission of "%s" failed!</b><br/>
    <p>We are sorry for this inconvenience, please try again.</p>
    """ % (wash_url_argument(title, "str"))

    return page(req=req, title="Dataset submitted", body=body)
Example #23
0
def index(req, ln=CFG_SITE_LANG, action='', bsrID='', sm_name='', sm_def_type='', sm_def_value='', sm_washer='', sm_locale=''):
    """
    Display the initial(main) page
    """
    navtrail_previous_links = bsc.getnavtrail()

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    auth = bsc.check_user(req,'cfgbibsort')
    if not auth[0]:
        action = wash_url_argument(action, 'str')
        bsrID = wash_url_argument(bsrID, 'int')
        sm_name = wash_url_argument(sm_name, 'str')
        sm_def_type = wash_url_argument(sm_def_type, 'str')
        sm_def_value = wash_url_argument(sm_def_value, 'str')
        sm_washer = wash_url_argument(sm_washer, 'str')
        sm_locale = wash_url_argument(sm_locale, 'str')
        return page(title="BibSort Admin Interface",
                body=bsc.perform_index(ln, action, bsrID, sm_name, sm_def_type, sm_def_value, sm_washer, sm_locale),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req, text=auth[1], navtrail=navtrail_previous_links)
def perform_request_delete(comID=-1, recID=-1, uid=-1, reviews="", ln=CFG_SITE_LANG):
    """
    """
    _ = gettext_set_language(ln)

    from search_engine import record_exists

    warnings = []

    ln = wash_language(ln)
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    uid = wash_url_argument(uid, 'int')
    # parameter reviews is deduced from comID when needed

    if comID is not None and recID is not None and uid is not None:
        if comID <= 0 and recID <= 0 and uid <= 0:
            if comID != -1:
                try:
                    raise InvenioWebCommentWarning(_('Invalid comment ID.'))
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(("WRN_WEBCOMMENT_ADMIN_INVALID_COMID",))
            return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

        if comID > 0 and not recID > 0:
            comment = query_get_comment(comID)

            if comment:
                # Figure out if this is a review or a comment
                c_star_score = 5
                if comment[c_star_score] > 0:
                    reviews = 1
                else:
                    reviews = 0
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                try:
                    raise InvenioWebCommentWarning(_('Comment ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)
def update_detailed_record_options(req, colID, ln=CFG_SITE_LANG, tabs=[], recurse=0):
    """Update the preferences for the tab to show/hide in the detailed record page. """

    _tabs = wash_url_argument(tabs, 'list')
    navtrail_previous_links = wsc.getnavtrail() + """&gt; <a class="navtrail" href="%s/admin/websearch/websearchadmin.py/">WebSearch Admin</a> """ % (CFG_SITE_URL)

    try:
        uid = getUid(req)
    except Error, e:
        return error_page(req)
def perform_request_unreport_single_com(ln=CFG_SITE_LANG, id=""):
    """
    private function
    Unreport a single comment
    @param ln: language
    @param id: comment id to be deleted
    """
    ln = wash_language(ln)
    id = wash_url_argument(id, 'int')
    return query_suppress_abuse_report(id)
def perform_request_del_single_com_auth(ln=CFG_SITE_LANG, id=id):
    """
    private function
    Delete a single comment requested by the author
    @param ln: language
    @param id: comment id to be deleted
    """
    ln = wash_language(ln)
    id = wash_url_argument(id, 'int')
    return query_delete_comment_auth(id)
Example #28
0
def kb_show(req, kb, sortby="to", ln=CFG_SITE_LANG, startat=0, search=""):
    """
    Shows the content of the given knowledge base id. Check for authentication and kb existence.
    Before displaying the content of the knowledge base, check if a form was submitted asking for
    adding, editing or removing a value.

    @param ln language
    @param kb the kb id to show
    @param sortby the sorting criteria ('from' or 'to')
    @param startat the number from which start showing mapping rules in kb
    @param search search for this string in the kb
    """

    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = '''
         &gt; <a class="navtrail"
         href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln,
                                         _("Manage Knowledge Bases"))

    try:
        uid = getUid(req)
    except MySQLdb.Error:
        return error_page(req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        kb_id = wash_url_argument(kb, 'int')
        kb_name = bibknowledge.get_kb_name(kb_id)

        if kb_name is None:
            return page(title=_("Unknown Knowledge Base"),
                        body="",
                        language=ln,
                        navtrail=navtrail_previous_links,
                        errors=[("ERR_KB_ID_UNKNOWN", kb)],
                        lastupdated=__lastupdated__,
                        req=req)
        return page(
            title=_("Knowledge Base %s" % kb_name),
            body=bibknowledgeadminlib.perform_request_knowledge_base_show(
                ln=ln,
                kb_id=kb_id,
                sortby=sortby,
                startat=startat,
                search_term=search),
            uid=uid,
            language=ln,
            navtrail=navtrail_previous_links,
            lastupdated=__lastupdated__,
            req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #29
0
def format_template_update_attributes(req,
                                      bft,
                                      ln=CFG_SITE_LANG,
                                      name="",
                                      description="",
                                      duplicate=None):
    """
    Update the name and description of given format template

    @param req: the request object
    @param ln: language
    @param description: the new description
    @param name: the new name
    @param bft: the filename of the template to update
    @param duplicate: the filename of template that we want to copy (the code)
    @return: a web page (or redirection to a web page)
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:

        if duplicate is not None:
            duplicate = wash_url_argument(duplicate, 'str')
        name = wash_url_argument(name, 'str')
        description = wash_url_argument(description, 'str')
        bft = bibformatadminlib.update_format_template_attributes(
            bft, name, description, duplicate)

        redirect_to_url(
            req, "format_template_show?ln=%(ln)s&bft=%(bft)s" % {
                'ln': ln,
                'bft': bft
            })
    else:
        return page_not_authorized(req=req, text=auth_msg)
Example #30
0
def get_msg_associated_to_code(err_code, stream='error'):
    """
    Returns string of code
    @param err_code: error or warning code
    @type err_code: string
    @param stream: 'error' or 'warning'
    @type stream: string
    @return: (err_code, formatted_message)
    @rtype: tuple
    """
    err_code = wash_url_argument(err_code, 'str')
    stream = wash_url_argument(stream, 'str')
    try:
        module_directory_name = err_code.split('_')[1].lower()
        module_config = module_directory_name + '_config'
        module_dict_name = "CFG_" + module_directory_name.upper() + \
                           "_%s_MESSAGES" % stream.upper()
        module = __import__(
            module_config, globals(), locals(), [module_dict_name])
        module_dict = getattr(module, module_dict_name)
        err_msg = module_dict[err_code]
    except ImportError:
        error = 'ERR_MISCUTIL_IMPORT_ERROR'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (err_code,
                                                        module_config)
        err_code = error
    except AttributeError:
        error = 'ERR_MISCUTIL_NO_DICT'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (err_code,
                                                        module_config,
                                                        module_dict_name)
        err_code = error
    except KeyError:
        error = 'ERR_MISCUTIL_NO_MESSAGE_IN_DICT'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (err_code,
                  module_config + '.' + module_dict_name)
        err_code = error
    except:
        error = 'ERR_MISCUTIL_UNDEFINED_ERROR'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % err_code
        err_code = error
    return (err_code, err_msg)
Example #31
0
def del_com(req, ln=CFG_SITE_LANG, action="delete", **hidden):
    """
    private function
    Delete a comment
    @param req: request object to obtain user information
    @param ln: language
    @param **hidden: ids of comments to delete sent as individual variables comidX=on, where X is id
    """
    ln = wash_language(ln)
    action = wash_url_argument(action, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    try:
        uid = getUid(req)
    except Error:
        return page(title=_("Internal Error"),
                    body = create_error_box(req, verbose=0, ln=ln),
                    description="%s - Internal Error" % CFG_SITE_NAME,
                    keywords="%s, Internal Error" % CFG_SITE_NAME,
                    language=ln,
                    req=req)

    (auth_code, auth_msg) = check_user(req,'cfgwebcomment')
    if (auth_code != 'false'):
        comIDs = []
        args = hidden.keys()
        for var in args:
            try:
                comIDs.append(int(var.split('comid')[1]))
            except:
                pass
        if action == 'delete':
            body = perform_request_del_com(ln=ln, comIDs=comIDs)
            title = _("Delete comments")
        elif action == 'unreport':
            body = suppress_abuse_report(ln=ln, comIDs=comIDs)
            title = _("Suppress abuse reports")
        elif action == 'undelete':
            body = perform_request_undel_com(ln=ln, comIDs=comIDs)
            title = _("Undelete comments")
        else:
            redirect_to_url(req, CFG_SITE_URL + '/admin/webcomment/webcommentadmin.py')
        return page(title=title,
                    body=body,
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
Example #32
0
def del_com(req, ln=CFG_SITE_LANG, action="delete", **hidden):
    """
    private function
    Delete a comment
    @param req: request object to obtain user information
    @param ln: language
    @param **hidden: ids of comments to delete sent as individual variables comidX=on, where X is id
    """
    ln = wash_language(ln)
    action = wash_url_argument(action, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    try:
        uid = getUid(req)
    except Error:
        return page(title=_("Internal Error"),
                    body = create_error_box(req, verbose=0, ln=ln),
                    description="%s - Internal Error" % CFG_SITE_NAME,
                    keywords="%s, Internal Error" % CFG_SITE_NAME,
                    language=ln,
                    req=req)

    (auth_code, auth_msg) = check_user(req,'cfgwebcomment')
    if (auth_code != 'false'):
        comIDs = []
        args = hidden.keys()
        for var in args:
            try:
                comIDs.append(int(var.split('comid')[1]))
            except:
                pass
        if action == 'delete':
            body = perform_request_del_com(ln=ln, comIDs=comIDs)
            title = _("Delete comments")
        elif action == 'unreport':
            body = suppress_abuse_report(ln=ln, comIDs=comIDs)
            title = _("Suppress abuse reports")
        elif action == 'undelete':
            body = perform_request_undel_com(ln=ln, comIDs=comIDs)
            title = _("Undelete comments")
        else:
            redirect_to_url(req, CFG_SITE_URL + '/admin/webcomment/webcommentadmin.py')
        return page(title=title,
                    body=body,
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
Example #33
0
def format_template_delete(req, bft, ln=CFG_SITE_LANG, chosen_option=""):
    """
    Delete a format template

    @param req: the request object
    @param bft: the filename of the template to delete
    @param ln: language
    @param chosen_option: empty string when user has not yet confirm. Else "Delete" to confirm
    @return: a web page (or redirection to a web page)
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail('''
    &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a> &gt; %s''' % (CFG_SITE_SECURE_URL, ln ,_("Manage Format Templates"),_("Delete Format Template")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        #Ask confirmation to user if not already done
        chosen_option = wash_url_argument(chosen_option, 'str')
        if chosen_option == "":
            format_template = wash_url_argument(bft, 'str')
            format_name = bibformat_engine.get_format_template_attrs(bft)['name']
            return dialog_box(req=req,
                              ln=ln,
                              title="Delete %s" % format_name,
                              message="Are you sure you want to delete" \
                              "format template <i>%s</i>?" % format_name,
                              navtrail=navtrail_previous_links,
                              options=[_("Cancel"), _("Delete")])

        elif chosen_option==_("Delete"):
            bibformatadminlib.delete_format_template(bft)

        redirect_to_url(req, "format_templates_manage?ln=%(ln)s" % {'ln':ln})
    else:
        return page_not_authorized(req=req, text=auth_msg)
Example #34
0
def get_msg_associated_to_code(err_code, stream='error'):
    """
    Returns string of code
    @param err_code: error or warning code
    @type err_code: string
    @param stream: 'error' or 'warning'
    @type stream: string
    @return: (err_code, formatted_message)
    @rtype: tuple
    """
    err_code = wash_url_argument(err_code, 'str')
    stream = wash_url_argument(stream, 'str')
    try:
        module_directory_name = err_code.split('_')[1].lower()
        module_config = module_directory_name + '_config'
        module_dict_name = "CFG_" + module_directory_name.upper() + \
                           "_%s_MESSAGES" % stream.upper()
        module = __import__(module_config, globals(), locals(),
                            [module_dict_name])
        module_dict = getattr(module, module_dict_name)
        err_msg = module_dict[err_code]
    except ImportError:
        error = 'ERR_MISCUTIL_IMPORT_ERROR'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (err_code,
                                                        module_config)
        err_code = error
    except AttributeError:
        error = 'ERR_MISCUTIL_NO_DICT'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (
            err_code, module_config, module_dict_name)
        err_code = error
    except KeyError:
        error = 'ERR_MISCUTIL_NO_MESSAGE_IN_DICT'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % (
            err_code, module_config + '.' + module_dict_name)
        err_code = error
    except:
        error = 'ERR_MISCUTIL_UNDEFINED_ERROR'
        err_msg = CFG_MISCUTIL_ERROR_MESSAGES[error] % err_code
        err_code = error
    return (err_code, err_msg)
Example #35
0
def alert(req, journal_name="", ln=CFG_SITE_LANG, sent="False", plainText=u"",
          htmlMail="", recipients="", subject="", issue="", force="False"):
    """
    Sends an email alert, in HTML/PlainText or only PlainText to a mailing
    list to alert for new journal releases.
    """
    navtrail_previous_links = wjn.getnavtrail(' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a> &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">%s</a>' % (CFG_SITE_URL, CFG_SITE_URL, journal_name, journal_name))

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
        issue = wash_issue_number(ln,
                                         journal_name,
                                         issue)
        plain_text = wash_url_argument(plainText, 'str')
        html_mail = wash_url_argument(htmlMail, 'str')
        recipients = wash_url_argument(recipients, 'str')
        subject = wash_url_argument(subject, 'str')
        sent = wash_url_argument(sent, 'str')
        force = wash_url_argument(force, 'str')
    except InvenioWebJournalNoJournalOnServerError, e:
        register_exception(req=req)
        return e.user_box()
Example #36
0
def output_format_show_dependencies(req, bfo, ln=CFG_SITE_LANG):
    """
    Show the dependencies of the given output format.

    @param req: the request object
    @param ln: language
    @param bfo: the filename of the output format to show
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s </a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Manage Output Formats")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfo = wash_url_argument(bfo, 'str')

        if not bibformatadminlib.can_read_output_format(
                bfo):  #No read permission
            try:
                raise InvenioBibFormatError(
                    _('Output format %s cannot not be read. %s') % (bfo, ""))
            except InvenioBibFormatError, exc:
                register_exception(req=req)
                return page(title=_("Restricted Output Format"),
                            body="""You don't have permission
                            to view this output format.""",
                            language=ln,
                            navtrail=navtrail_previous_links,
                            lastupdated=__lastupdated__,
                            req=req)

        format_name = bibformat_engine.get_output_format_attrs(
            bfo)['names']['generic']

        return page(title=_("Output Format %s Dependencies" % format_name),
                    body=bibformatadminlib.
                    perform_request_output_format_show_dependencies(bfo,
                                                                    ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
def loan_on_desk_step4(req, list_of_books=None, user_info=None, due_date=None,
                       note=None, ln=CFG_SITE_LANG):
    """
    http://cds.cern.ch/admin/bibcirculation/bibcirculationadmin.py/loan_on_desk_step5
    """

    user_info = eval(user_info)

    list_of_books = eval(list_of_books)
    due_date = wash_url_argument(due_date, 'list')


    return bal.loan_on_desk_step4(req, list_of_books, user_info,
                                  due_date, note, ln)
Example #38
0
 def test_wash_url_argument(self):
     """urlutils - washing of URL arguments"""
     self.assertEqual(1,
                      wash_url_argument(['1'], 'int'))
     self.assertEqual("1",
                      wash_url_argument(['1'], 'str'))
     self.assertEqual(['1'],
                      wash_url_argument(['1'], 'list'))
     self.assertEqual(0,
                      wash_url_argument('ellis', 'int'))
     self.assertEqual("ellis",
                      wash_url_argument('ellis', 'str'))
     self.assertEqual(["ellis"],
                      wash_url_argument('ellis', 'list'))
     self.assertEqual(0,
                      wash_url_argument(['ellis'], 'int'))
     self.assertEqual("ellis",
                      wash_url_argument(['ellis'], 'str'))
     self.assertEqual(["ellis"],
                      wash_url_argument(['ellis'], 'list'))
def perform_request_latest(req=None, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    Display the list of latest comments/reviews along with information about the comment.

    @param req: request object for obtaining user information
    @param ln: language
    @param comments: boolean activated if using comments, deactivated for reviews
    @param top: Specify number of results to be shown
    @param collection: filter by collection
    """
    ln = wash_language(ln)
    comments = wash_url_argument(comments, 'int')
    top = wash_url_argument(top, 'int')
    collection = wash_url_argument(collection, 'str')

    user_info = collect_user_info(req)
    user_collections = ['Show all']
    user_collections.extend(get_user_collections(req))
    if collection and collection != 'Show all':
        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatecomments', collection=collection)
        if auth_code:
            return webcomment_templates.tmpl_admin_latest(ln=ln,
                                                          comment_data=None,
                                                          comments=comments, error=1, user_collections=user_collections, collection=collection)
    if collection:
        comments_retrieved = query_get_latest(comments, ln, top, user_collections, collection)
    else:
        comments_retrieved = query_get_latest(comments, ln, top, user_collections, user_collections[0])
    if comments_retrieved:
        return webcomment_templates.tmpl_admin_latest(ln=ln,
                                                      comment_data=comments_retrieved,
                                                      comments=comments, error=0, user_collections=user_collections, collection=collection)
    else:
        return webcomment_templates.tmpl_admin_latest(ln=ln,
                                                      comment_data=comments_retrieved,
                                                      comments=comments, error=2, user_collections=user_collections, collection=collection)
Example #40
0
def kb_show_attributes(req, kb, ln=CFG_SITE_LANG, sortby="to"):
    """
    Shows the attributes (name, description) of a given kb

    @param ln language
    @param kb the kb id to show
    @param sortby the sorting criteria ('from' or 'to')
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (
        CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

    try:
        uid = getUid(req)
    except MySQLdb.Error:
        return error_page(req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:

        kb_id = wash_url_argument(kb, 'int')
        kb_name = bibknowledge.get_kb_name(kb_id)

        if kb_name is None:
            return page(title=_("Unknown Knowledge Base"),
                        body="",
                        language=ln,
                        navtrail=navtrail_previous_links,
                        errors=[("ERR_KB_ID_UNKNOWN", kb)],
                        lastupdated=__lastupdated__,
                        req=req)

        return page(title=_("Knowledge Base %s Attributes" % kb_name),
                    body=bibknowledgeadminlib.
                    perform_request_knowledge_base_show_attributes(
                        ln=ln, kb_id=kb_id, sortby=sortby),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #41
0
def new_dataset(req,
                title=None,
                paper=None,
                authors=None,
                description=None,
                dataset_file=None,
                doi="",
                submitter_name=None,
                submitter_email=None,
                comments=None):
    """Form handler for dataset submissions."""
    import uuid

    title = wash_url_argument(title, "str")
    paper = wash_url_argument(paper, "str")
    authors = wash_url_argument(authors, "str")
    description = wash_url_argument(description, "str")
    submitter_name = wash_url_argument(submitter_name, "str")
    submitter_email = wash_url_argument(submitter_email, "str")
    comments = wash_url_argument(comments, "str")

    dataset_file = wash_url_argument(dataset_file, "str")
    tmp_id = str(uuid.uuid1())
    if dataset_file:
        f = open(CFG_TMPSHAREDDIR + 'dataset-submission-' + tmp_id, 'wb')
        f.write(req.form["dataset_file"].file.read())
        f.close()

    res = submit_email_ticket(title, paper, authors, description, tmp_id,
                              req.form["dataset_file"].filename, doi,
                              submitter_name, submitter_email, comments)

    if res:
        return redirect_to_url(
            req, "%s/data_submission.py/data_submission_success?title=%s" %
            (CFG_SITE_URL, title))
    else:
        return redirect_to_url(
            req, "%s/data_submission.py/data_submission_fail?title=%s" %
            (CFG_SITE_URL, title))
def perform_request_undel_com(ln=CFG_SITE_LANG, comIDs=[]):
    """
    private function
    Undelete the comments and say whether successful or not
    @param ln: language
    @param comIDs: list of comment ids
    """
    ln = wash_language(ln)
    comIDs = wash_url_argument(comIDs, 'list')
    # map ( fct, list, arguments of function)
    comIDs = map(wash_url_argument, comIDs, ('int '*len(comIDs)).split(' ')[:-1])

    if not comIDs:
        comIDs = map(coerce, comIDs, ('0 '*len(comIDs)).split(' ')[:-1])
        return webcomment_templates.tmpl_admin_undel_com(del_res=comIDs, ln=ln)

    del_res = []
    for comID in comIDs:
        del_res.append((comID, query_undel_single_comment(comID)))
    return webcomment_templates.tmpl_admin_undel_com(del_res=del_res, ln=ln)
def suppress_abuse_report(ln=CFG_SITE_LANG, comIDs=[]):
    """
    private function
    suppress the abuse reports for the given comIDs.
    @param ln: language
    @param comIDs: list of ids to suppress attached reports.
    """
    ln = wash_language(ln)
    comIDs = wash_url_argument(comIDs, 'list')
    # map ( fct, list, arguments of function)
    comIDs = map(wash_url_argument, comIDs, ('int '*len(comIDs)).split(' ')[:-1])

    if not comIDs:
        comIDs = map(coerce, comIDs, ('0 '*len(comIDs)).split(' ')[:-1])
        return webcomment_templates.tmpl_admin_del_com(del_res=comIDs, ln=ln)

    del_res = []
    for comID in comIDs:
        del_res.append((comID, query_suppress_abuse_report(comID)))
    return webcomment_templates.tmpl_admin_suppress_abuse_report(del_res=del_res, ln=ln)
Example #44
0
def format_element_test(req, bfe, ln=CFG_SITE_LANG, param_values=None):
    """
    Allows user to test element with different parameters and check output

    'param_values' is the list of values to pass to 'format'
    function of the element as parameters, in the order ...
    If params is None, this means that they have not be defined by user yet.

    @param req: the request object
    @param bfe: the name of the element to test
    @param ln: language
    @param param_values: the list of parameters to pass to element format function
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Format Elements Documentation")))

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfe = wash_url_argument(bfe, 'str')
        user_info = collect_user_info(req)
        uid = user_info['uid']
        return page(title=_("Test Format Element %s" % bfe),
                    body=bibformatadminlib.perform_request_format_element_test(
                        bfe=bfe,
                        ln=ln,
                        param_values=param_values,
                        user_info=user_info),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #45
0
def index(req,
          ln=CFG_SITE_LANG,
          action='',
          bsrID='',
          sm_name='',
          sm_def_type='',
          sm_def_value='',
          sm_washer='',
          sm_locale=''):
    """
    Display the initial(main) page
    """
    navtrail_previous_links = bsc.getnavtrail()

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    auth = bsc.check_user(req, 'cfgbibsort')
    if not auth[0]:
        action = wash_url_argument(action, 'str')
        bsrID = wash_url_argument(bsrID, 'int')
        sm_name = wash_url_argument(sm_name, 'str')
        sm_def_type = wash_url_argument(sm_def_type, 'str')
        sm_def_value = wash_url_argument(sm_def_value, 'str')
        sm_washer = wash_url_argument(sm_washer, 'str')
        sm_locale = wash_url_argument(sm_locale, 'str')
        return page(title="BibSort Admin Interface",
                    body=bsc.perform_index(ln, action, bsrID, sm_name,
                                           sm_def_type, sm_def_value,
                                           sm_washer, sm_locale),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth[1],
                                   navtrail=navtrail_previous_links)
Example #46
0
def index(req, ln=CFG_SITE_LANG, journal_name=None, action=""):
    """
    Main administration page.

    Lists the journals, and offers options to edit them, delete them
    or add new journals
    """
    navtrail_previous_links = wjn.getnavtrail()

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
        action = wash_url_argument(action, 'str')
    except InvenioWebJournalNoJournalOnServerError, e:
        # Ok, no journal. Let the admin add one...
        pass
Example #47
0
def format_template_show_dependencies(req, bft, ln=CFG_SITE_LANG):
    """
    Show the dependencies (on elements) of the given format.

    @param req: the request object
    @param ln: language
    @param bft: the filename of the template to show
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Manage Format Templates")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        format_template = wash_url_argument(bft, 'str')
        format_name = bibformat_engine.get_format_template_attrs(bft)['name']

        return page(title=_("Format Template %s Dependencies" % format_name),
                    body=bibformatadminlib.
                    perform_request_format_template_show_dependencies(bft,
                                                                      ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)

    else:
        return page_not_authorized(req=req, text=auth_msg)
Example #48
0
def format_element_show_dependencies(req, bfe, ln=CFG_SITE_LANG):
    """
    Shows format element dependencies

    @param req: the request object
    @param req: the request object
    @param bfe: the name of the bfe to show
    @param ln: language
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s">%s</a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Format Elements Documentation")))
    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfe = wash_url_argument(bfe, 'str')
        return page(title=_("Format Element %s Dependencies" % bfe),
                    body=bibformatadminlib.
                    perform_request_format_element_show_dependencies(bfe=bfe,
                                                                     ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Example #49
0
def register_errors(errors_or_warnings_list, stream, req=None):
    """
    log errors to invenio.err and warnings to invenio.log
    errors will be logged with client information (if req is given) and a
    tracestack warnings will be logged with just the warning message

    @param errors_or_warnings_list: list of tuples (err_name, err_msg)

    err_name = ERR_ + %(module_directory_name)s + _ + %(error_name)s #ALL CAPS
    err_name must be stored in file:  module_directory_name + _config.py
    as the key for dict with name:  CFG_ + %(module_directory_name)s +
        _ERROR_MESSAGES

    @param stream: 'error' or 'warning'

    @param req: mod_python request
    @return: tuple integer 1 if successfully wrote to stream, integer 0 if not
            will append another error to errors_list if unsuccessful
    """
    client_info_dict = ""
    if stream == "error":
        # call the stack trace now
        tracestack_pretty = get_tracestack()
        # if req is given, get client info
        if req:
            client_info_dict = get_client_info(req)
            if client_info_dict:
                client_info = \
'''URL: http://%(host)s%(url)s
    Browser: %(browser)s
    Client: %(client_ip)s''' % client_info_dict
            else:
                client_info = "No client information available"
        else:
            client_info = "No client information available"
    # check arguments
    errors_or_warnings_list = wash_url_argument(errors_or_warnings_list,
                                                'list')
    stream = wash_url_argument(stream, 'str')
    for etuple in errors_or_warnings_list:
        etuple = wash_url_argument(etuple, 'tuple')
    # check stream arg for presence of [error,warning]; when none, add error
    # and default to warning
    if stream == 'error':
        stream = 'err'
    elif stream == 'warning':
        stream = 'log'
    else:
        stream = 'log'
        error = 'ERR_MISCUTIL_BAD_FILE_ARGUMENT_PASSED'
        errors_or_warnings_list.append(
            (error, eval(CFG_MISCUTIL_ERROR_MESSAGES[error]) % stream))
    # update log_errors
    stream_location = os.path.join(CFG_LOGDIR, 'invenio.' + stream)
    errors = ''
    for etuple in errors_or_warnings_list:
        try:
            errors += "%s%s : %s \n " % (' ' * 4 * 7 + ' ', etuple[0],
                                         etuple[1])
        except:
            errors += "%s%s \n " % (' ' * 4 * 7 + ' ', etuple)
    if errors:
        errors = errors[(4 * 7 +
                         1):-3]  # get rid of begining spaces and last '\n'
    msg = """
%(time)s --> %(errors)s%(error_file)s""" % {
        'time': client_info_dict and client_info_dict['time'] or \
                time.strftime("%Y-%m-%d %H:%M:%S"),
        'errors': errors,
        'error_file': stream=='err' and "\n%s%s\n%s\n" % (
            ' '*4, client_info, tracestack_pretty) or ""}
    try:
        stream_to_write = open(stream_location, 'a+')
        stream_to_write.writelines(msg)
        stream_to_write.close()
        return_value = 1
    except:
        error = 'ERR_MISCUTIL_WRITE_FAILED'
        errors_or_warnings_list.append(
            (error, CFG_MISCUTIL_ERROR_MESSAGES[error] % stream_location))
        return_value = 0
    return return_value
def perform_request_comments(req=None,
                             ln=CFG_SITE_LANG,
                             uid="",
                             comID="",
                             recID="",
                             reviews=0,
                             abuse=False,
                             collection=""):
    """
    Display the list of comments/reviews along with information about the comment.

    Display the comment given by its ID, or the list of comments for
    the given record ID.
    If abuse == True, only list records reported as abuse.
    If comID and recID are not provided, list all comments, or all
    abused comments (check parameter 'abuse')
    """
    ln = wash_language(ln)
    uid = wash_url_argument(uid, 'int')
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    reviews = wash_url_argument(reviews, 'int')
    collection = wash_url_argument(collection, 'str')

    user_info = collect_user_info(req)
    user_collections = ['Show all']
    user_collections.extend(get_user_collections(req))
    if collection and collection != 'Show all':
        (auth_code, auth_msg) = acc_authorize_action(req,
                                                     'moderatecomments',
                                                     collection=collection)
        if auth_code:
            return webcomment_templates.tmpl_admin_comments(
                ln=ln,
                uid=uid,
                comID=comID,
                recID=recID,
                comment_data=None,
                reviews=reviews,
                error=1,
                user_collections=user_collections,
                collection=collection)
    if collection:
        if recID or uid:
            comments = query_get_comments(uid,
                                          comID,
                                          recID,
                                          reviews,
                                          ln,
                                          abuse=abuse,
                                          user_collections=user_collections,
                                          collection=collection)
        else:
            comments = query_get_comments('',
                                          comID,
                                          '',
                                          reviews,
                                          ln,
                                          abuse=abuse,
                                          user_collections=user_collections,
                                          collection=collection)
    else:
        if recID or uid:
            comments = query_get_comments(uid,
                                          comID,
                                          recID,
                                          reviews,
                                          ln,
                                          abuse=abuse,
                                          user_collections=user_collections,
                                          collection=user_collections[0])
        else:
            comments = query_get_comments('',
                                          comID,
                                          '',
                                          reviews,
                                          ln,
                                          abuse=abuse,
                                          user_collections=user_collections,
                                          collection=user_collections[0])
    if comments:
        return webcomment_templates.tmpl_admin_comments(
            ln=ln,
            uid=uid,
            comID=comID,
            recID=recID,
            comment_data=comments,
            reviews=reviews,
            error=0,
            user_collections=user_collections,
            collection=collection)
    else:
        return webcomment_templates.tmpl_admin_comments(
            ln=ln,
            uid=uid,
            comID=comID,
            recID=recID,
            comment_data=comments,
            reviews=reviews,
            error=2,
            user_collections=user_collections,
            collection=collection)
Example #51
0
def kb_upload(req, kb, ln=CFG_SITE_LANG):
    """
    Uploads file rdffile.
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail = '''<a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % \
               (CFG_SITE_SECURE_URL, ln, _("Knowledge Bases"))

    try:
        dummy = getUid(req)
    except MySQLdb.Error:
        return error_page(req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        kb_id = wash_url_argument(kb, 'int')
        #get the form
        form = req.form
        #get the contents from the form
        if not form.has_key('file') or not form['file'].filename:
            return page(title=_("Cannot upload file"),
                        body=_("You have not selected a file to upload"),
                        language=ln,
                        navtrail=navtrail,
                        lastupdated=__lastupdated__,
                        req=req)
        fileitem = form['file']
        uploaddir = CFG_WEBDIR + "/kbfiles"

        #create a upload directory unless already exists
        if os.path.isfile(uploaddir):
            return page(title=_("Cannot upload file"),
                        body = "Cannot create directory " + \
                                uploaddir+" since it already" + \
                                " exists and it is a file",
                        language=ln,
                        navtrail = navtrail,
                        lastupdated=__lastupdated__,
                        req=req)
        if not os.path.isdir(uploaddir):
            try:
                os.mkdir(uploaddir)
            except:
                return page(title=_("Cannot upload file"),
                        body = "Cannot create directory "+uploaddir+ \
                               " maybe no access rights",
                        language=ln,
                        navtrail = navtrail,
                        lastupdated=__lastupdated__,
                        req=req)

        #if we are here we can try to write
        #get the name and the file..
        fn = str(kb_id) + ".rdf"
        open(uploaddir + "/" + fn, 'w').write(fileitem.file.read())
        body = (_("File %s uploaded.") % ('kbfiles/' + cgi.escape(fn)))
        body += " <a href='" + CFG_SITE_SECURE_URL + "/kb'>%s</a>" % _("Back")
        return (page(title=_("File uploaded"),
                     body=body,
                     language=ln,
                     navtrail=navtrail,
                     lastupdated=__lastupdated__,
                     req=req))
    else:
        return (page_not_authorized(req=req, text=auth_msg, navtrail=navtrail))
Example #52
0
                        _('Format template %s cannot not be read. %s') %
                        (bft, ""))
                except InvenioBibFormatError, exc:
                    register_exception(req=req)
                    return page(title=_("Restricted Format Template"),
                                body="""You don't have permission to
                            view this format template.""",
                                language=ln,
                                navtrail=navtrail_previous_links,
                                lastupdated=__lastupdated__,
                                req=req)
            name = bibformat_engine.get_format_template_attrs(bft)['name']
            title = _("Validation of Format Template %s" % name)

        elif bfe is not None:  #Format element validation
            bfe = wash_url_argument(bfe, 'str')
            navtrail_previous_links = bibformatadminlib.getnavtrail(
                ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_elements_doc?ln=%s#%s">%s</a>'''
                % (CFG_SITE_SECURE_URL, ln, bfe.upper(),
                   _("Format Elements Documentation")))

            if not bibformatadminlib.can_read_format_element(bfe) and \
                   not bibformat_dblayer.tag_exists_for_name(bfe): #No read permission
                try:
                    raise InvenioBibFormatError(
                        _('Format element %s cannot not be read. %s') %
                        (bfe, ""))
                except InvenioBibFormatError, exc:
                    register_exception(req=req)
                    return page(title=_("Restricted Format Element"),
                                body="""You don't have permission
def perform_request_delete(comID=-1,
                           recID=-1,
                           uid=-1,
                           reviews="",
                           ln=CFG_SITE_LANG):
    """
    """
    from search_engine import record_exists

    warnings = []

    ln = wash_language(ln)
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    uid = wash_url_argument(uid, 'int')
    # parameter reviews is deduced from comID when needed

    if comID is not None and recID is not None and uid is not None:
        if comID <= 0 and recID <= 0 and uid <= 0:
            if comID != -1:
                warnings.append(("WRN_WEBCOMMENT_ADMIN_INVALID_COMID", ))
            return (webcomment_templates.tmpl_admin_delete_form(ln, warnings),
                    None, warnings)

        if comID > 0 and not recID > 0:
            comment = query_get_comment(comID)

            if comment:
                # Figure out if this is a review or a comment
                c_star_score = 5
                if comment[c_star_score] > 0:
                    reviews = 1
                else:
                    reviews = 0
                return (perform_request_comments(ln=ln,
                                                 comID=comID,
                                                 recID=recID,
                                                 reviews=reviews), None,
                        warnings)
            else:
                warnings.append(
                    ('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return (webcomment_templates.tmpl_admin_delete_form(
                    ln, warnings), None, warnings)

        elif recID > 0:
            if record_exists(recID):
                comID = ''
                reviews = wash_url_argument(reviews, 'int')
                return (perform_request_comments(ln=ln,
                                                 comID=comID,
                                                 recID=recID,
                                                 reviews=reviews), None,
                        warnings)
            else:
                warnings.append(
                    ('WRN_WEBCOMMENT_ADMIN_RECID_INEXISTANT', comID))
                return (webcomment_templates.tmpl_admin_delete_form(
                    ln, warnings), None, warnings)
        else:
            return (webcomment_templates.tmpl_admin_delete_form(ln, warnings),
                    None, warnings)

    else:
        return (webcomment_templates.tmpl_admin_delete_form(ln, warnings),
                None, warnings)
Example #54
0
def output_format_show(req,
                       bfo,
                       ln=CFG_SITE_LANG,
                       r_fld=[],
                       r_val=[],
                       r_tpl=[],
                       default="",
                       r_upd="",
                       chosen_option="",
                       **args):
    """
    Show a single output format. Check for authentication and print output format settings.

    The page either shows the output format from file, or from user's
    POST session, as we want to let him edit the rules without
    saving. Policy is: r_fld, r_val, rules_tpl are list of attributes
    of the rules.  If they are empty, load from file. Else use
    POST. The i th value of each list is one of the attributes of rule
    i. Rule i is the i th rule in order of evaluation.  All list have
    the same number of item.

    r_upd contains an action that has to be performed on rules. It
    can composed of a number (i, the rule we want to modify) and an
    operator : "save" to save the rules, "add" or "del".
    syntax: operator [number]
    For eg: r_upd = _("Save Changes") saves all rules (no int should be specified).
    For eg: r_upd = _("Add New Rule") adds a rule (no int should be specified).
    For eg: r_upd = _("Remove Rule") + " 5"  deletes rule at position 5.
    The number is used only for operation delete.

    An action can also be in **args. We must look there for string starting
    with '(+|-) [number]' to increase (+) or decrease (-) a rule given by its
    index (number).
    For example "+ 5" increase priority of rule 5 (put it at fourth position).
    The string in **args can be followed by some garbage that looks like .x
    or .y, as this is returned as the coordinate of the click on the
    <input type="image">. We HAVE to use args and reason on its keys, because for <input> of
    type image, iexplorer does not return the value of the tag, but only the name.

    Action is executed only if we are working from user's POST session
    (means we must have loaded the output format first, which is
    totally normal and expected behaviour)


    @param req: the request object
    @param bfo: the filename of the output format to show
    @param ln: language
    @param r_fld: the list of 'field' attribute for each rule
    @param r_val: the list of 'value' attribute for each rule
    @param r_tpl: the list of 'template' attribute for each rule
    @param default: the default format template used by this output format
    @param r_upd: the rule that we want to increase/decrease in order of evaluation
    @param chosen_option: emptry string when user has not yet confirmed to go on
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = bibformatadminlib.getnavtrail(
        ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Manage Output Formats")))
    code = wash_url_argument(bfo, 'str')

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        bfo = wash_url_argument(bfo, 'str')
        default = wash_url_argument(default, 'str')
        r_upd = wash_url_argument(r_upd, 'str')

        if not bibformatadminlib.can_read_output_format(
                bfo):  #No read permission
            try:
                raise InvenioBibFormatError(
                    _('Output format %s cannot not be read. %s') % (bfo, ""))
            except InvenioBibFormatError, exc:
                register_exception(req=req)
                return page(title=_("Restricted Output Format"),
                            body="""You don't have permission to
                            view this output format.""",
                            language=ln,
                            navtrail=navtrail_previous_links,
                            lastupdated=__lastupdated__,
                            req=req)

        output_format = bibformat_engine.get_output_format(
            code=bfo, with_attributes=True)
        name = output_format['attrs']['names']['generic']
        if name == "":
            name = bfo

        if not bibformatadminlib.can_write_output_format(bfo) and \
               chosen_option == "":#No write permission
            return dialog_box(req=req,
                              ln=ln,
                              title="File Permission on %s" % name,
                              message="You don't have write permission " \
                              "on <i>%s</i>.<br/> You can view the output " \
                              "format, but not edit it." % name,
                              navtrail=navtrail_previous_links,
                              options=[ _("Ok")])

        return page(title=_('Output Format %s Rules' % name),
                    body=bibformatadminlib.perform_request_output_format_show(
                        bfo=bfo,
                        ln=ln,
                        r_fld=r_fld,
                        r_val=r_val,
                        r_tpl=r_tpl,
                        default=default,
                        r_upd=r_upd,
                        args=args),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
Example #55
0
def validate_format(req, ln=CFG_SITE_LANG, bfo=None, bft=None, bfe=None):
    """
    Returns a page showing the status of an output format or format
    template or format element. This page is called from output
    formats management page or format template management page or
    format elements documentation.

    The page only shows the status of one of the format, depending on
    the specified one. If multiple are specified, shows the first one.

    @param req: the request object
    @param ln: language
    @param bfo: an output format 6 chars code
    @param bft: a format element filename
    @param bfe: a format element name
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        if bfo is not None:  #Output format validation
            bfo = wash_url_argument(bfo, 'str')
            navtrail_previous_links = bibformatadminlib.getnavtrail(
                ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>'''
                % (CFG_SITE_SECURE_URL, ln, _("Manage Output Formats")))

            if not bibformatadminlib.can_read_output_format(
                    bfo):  #No read permission
                try:
                    raise InvenioBibFormatError(
                        _('Output format %s cannot not be read. %s') %
                        (bfo, ""))
                except InvenioBibFormatError, exc:
                    register_exception(req=req)
                    return page(title=_("Restricted Output Format"),
                                body="""You don't have permission
                            to view this output format.""",
                                language=ln,
                                navtrail=navtrail_previous_links,
                                lastupdated=__lastupdated__,
                                req=req)

            output_format = bibformat_engine.get_output_format(
                code=bfo, with_attributes=True)
            name = output_format['attrs']['names']['generic']
            title = _("Validation of Output Format %s" % name)

        elif bft is not None:  #Format template validation
            bft = wash_url_argument(bft, 'str')
            navtrail_previous_links = bibformatadminlib.getnavtrail(
                ''' &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>'''
                % (CFG_SITE_SECURE_URL, ln, _("Manage Format Templates")))

            if not bibformatadminlib.can_read_format_template(
                    bft):  #No read permission
                try:
                    raise InvenioBibFormatError(
                        _('Format template %s cannot not be read. %s') %
                        (bft, ""))
                except InvenioBibFormatError, exc:
                    register_exception(req=req)
                    return page(title=_("Restricted Format Template"),
                                body="""You don't have permission to
                            view this format template.""",
                                language=ln,
                                navtrail=navtrail_previous_links,
                                lastupdated=__lastupdated__,
                                req=req)
            name = bibformat_engine.get_format_template_attrs(bft)['name']
            title = _("Validation of Format Template %s" % name)
Example #56
0
def format_template_show(req,
                         bft,
                         code=None,
                         ln=CFG_SITE_LANG,
                         ln_for_preview=CFG_SITE_LANG,
                         pattern_for_preview="",
                         content_type_for_preview="text/html",
                         chosen_option=""):
    """
    Main page for template edition. Check for authentication and print formats editor.

    @param req: the request object
    @param ln: language
    @param code: the code being edited
    @param bft: the name of the template to show
    @param ln_for_preview: the language for the preview (for bfo)
    @param pattern_for_preview: the search pattern to be used for the preview (for bfo)
    @param content_type_for_preview: the (MIME) content type of the preview
    @param chosen_option: returned value for dialog_box warning
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    navtrail_previous_links = bibformatadminlib.getnavtrail(
        '''
    &gt; <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>'''
        % (CFG_SITE_SECURE_URL, ln, _("Manage Format Templates")))

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        format_template = wash_url_argument(bft, 'str')
        ln_preview = wash_language(ln_for_preview)
        pattern_preview = wash_url_argument(pattern_for_preview, 'str')
        if not bibformatadminlib.can_read_format_template(
                bft):  #No read permission
            try:
                raise InvenioBibFormatError(
                    _('Format template %s cannot not be read. %s') %
                    (format_template, ""))
            except InvenioBibFormatError, exc:
                register_exception(req=req)
                return page(title=_("Restricted Format Template"),
                            body="""You don't have permission
                            to view this format template.""",
                            language=ln,
                            navtrail=navtrail_previous_links,
                            lastupdated=__lastupdated__,
                            req=req)

        format_name = bibformat_engine.get_format_template_attrs(bft)['name']
        if not bibformatadminlib.can_write_format_template(bft) and \
               chosen_option == "": #No write permission
            return dialog_box(req=req,
                              ln=ln,
                              title="File Permission on %s" % format_name,
                              message="You don't have write permission " \
                              "on <i>%s</i>.<br/> You can view the template" \
                              ", but not edit it." % format_name,
                              navtrail=navtrail_previous_links,
                              options=[ _("Ok")])

        if bft.endswith('.xsl'):
            format_name += ' (XSL)'
        return page(
            title=_("Format Template %s" % format_name),
            body=bibformatadminlib.perform_request_format_template_show(
                format_template,
                code=code,
                ln=ln,
                ln_for_preview=ln_preview,
                pattern_for_preview=pattern_preview,
                content_type_for_preview=content_type_for_preview),
            uid=uid,
            language=ln,
            navtrail=navtrail_previous_links,
            lastupdated=__lastupdated__,
            req=req)
Example #57
0
def get_msgs_for_code_list(code_list, stream='error', ln=CFG_SITE_LANG):
    """
    @param code_list: list of tuples  [(err_name, arg1, ..., argN), ...]

    err_name = ERR_ + %(module_directory_name)s + _ + %(error_name)s #ALL CAPS
    err_name must be stored in file:  module_directory_name + _config.py
    as the key for dict with name:  CFG_ + %(module_directory_name)s +
    _ERROR_MESSAGES
    For warnings, same thing except:
        err_name can begin with either 'ERR' or 'WRN'
        dict name ends with _warning_messages

    @param stream: 'error' or 'warning'

    @return: list of tuples of length 2 [('ERR_...', err_msg), ...]
        if code_list empty, will return None.
        if errors retrieving error messages, will append an error to the list
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    out = []
    if type(code_list) is None:
        return None
    code_list = wash_url_argument(code_list, 'list')
    stream = wash_url_argument(stream, 'str')
    for code_tuple in code_list:
        if not (type(code_tuple) is tuple):
            code_tuple = (code_tuple, )
        nb_tuple_args = len(code_tuple) - 1
        err_code = code_tuple[0]
        if stream == 'error' and not err_code.startswith('ERR'):
            error = 'ERR_MISCUTIL_NO_ERROR_MESSAGE'
            out.append((error, eval(CFG_MISCUTIL_ERROR_MESSAGES[error])))
            continue
        elif stream == 'warning' and not (err_code.startswith('ERR') or \
                err_code.startswith('WRN')):
            error = 'ERR_MISCUTIL_NO_WARNING_MESSAGE'
            out.append((error, eval(CFG_MISCUTIL_ERROR_MESSAGES[error])))
            continue
        (new_err_code, err_msg) = get_msg_associated_to_code(err_code, stream)
        if err_msg[:2] == '_(' and err_msg[-1] == ')':
            # err_msg is internationalized
            err_msg = eval(err_msg)
        nb_msg_args = err_msg.count('%') - err_msg.count('%%')
        parsing_error = ""
        if new_err_code != err_code or nb_msg_args == 0:
            # undefined_error or immediately displayable error
            out.append((new_err_code, err_msg))
            continue
        try:
            if nb_msg_args == nb_tuple_args:
                err_msg = err_msg % code_tuple[1:]
            elif nb_msg_args < nb_tuple_args:
                err_msg = err_msg % code_tuple[1:nb_msg_args + 1]
                parsing_error = 'ERR_MISCUTIL_TOO_MANY_ARGUMENT'
                parsing_error_message = eval(
                    CFG_MISCUTIL_ERROR_MESSAGES[parsing_error])
                parsing_error_message %= code_tuple[0]
            elif nb_msg_args > nb_tuple_args:
                code_tuple = list(code_tuple)
                for dummy in range(nb_msg_args - nb_tuple_args):
                    code_tuple.append('???')
                    code_tuple = tuple(code_tuple)
                err_msg = err_msg % code_tuple[1:]
                parsing_error = 'ERR_MISCUTIL_TOO_FEW_ARGUMENT'
                parsing_error_message = eval(
                    CFG_MISCUTIL_ERROR_MESSAGES[parsing_error])
                parsing_error_message %= code_tuple[0]
        except:
            parsing_error = 'ERR_MISCUTIL_BAD_ARGUMENT_TYPE'
            parsing_error_message = eval(
                CFG_MISCUTIL_ERROR_MESSAGES[parsing_error])
            parsing_error_message %= code_tuple[0]
        out.append((err_code, err_msg))
        if parsing_error:
            out.append((parsing_error, parsing_error_message))
    if not (out):
        out = None
    return out
Example #58
0
def format_template_show_preview_or_save(req,
                                         bft,
                                         ln=CFG_SITE_LANG,
                                         code=None,
                                         ln_for_preview=CFG_SITE_LANG,
                                         pattern_for_preview="",
                                         content_type_for_preview='text/html',
                                         save_action=None,
                                         navtrail=""):
    """
    Print the preview of a record with a format template. To be included inside Format template
    editor. If the save_action has a value, then the code should also be saved at the same time

    @param req: the request object
    @param code: the code of a template to use for formatting
    @param ln: language
    @param ln_for_preview: the language for the preview (for bfo)
    @param pattern_for_preview: the search pattern to be used for the preview (for bfo)
    @param content_type_for_preview: the content-type to use to serve the preview page
    @param save_action: has a value if the code has to be saved
    @param bft: the filename of the template to save
    @param navtrail: navigation trail
    @return: a web page
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    (auth_code, auth_msg) = check_user(req, 'cfgbibformat')
    if not auth_code:
        user_info = collect_user_info(req)
        uid = user_info['uid']
        bft = wash_url_argument(bft, 'str')
        if save_action is not None and code is not None:
            #save
            bibformatadminlib.update_format_template_code(bft, code=code)
        bibformat_engine.clear_caches()
        if code is None:
            code = bibformat_engine.get_format_template(bft)['code']

        ln_for_preview = wash_language(ln_for_preview)
        pattern_for_preview = wash_url_argument(pattern_for_preview, 'str')
        if pattern_for_preview == "":
            try:
                recID = search_pattern(p='-collection:DELETED').pop()
            except KeyError:
                return page(title="No Document Found",
                            body="",
                            uid=uid,
                            language=ln_for_preview,
                            navtrail="",
                            lastupdated=__lastupdated__,
                            req=req,
                            navmenuid='search')

            pattern_for_preview = "recid:%s" % recID
        else:
            try:
                recID = search_pattern(p=pattern_for_preview + \
                                        ' -collection:DELETED').pop()
            except KeyError:
                return page(title="No Record Found for %s" %
                            pattern_for_preview,
                            body="",
                            uid=uid,
                            language=ln_for_preview,
                            navtrail="",
                            lastupdated=__lastupdated__,
                            req=req)

        units = create_basic_search_units(None, pattern_for_preview, None)
        keywords = [unit[1] for unit in units if unit[0] != '-']
        bfo = bibformat_engine.BibFormatObject(recID=recID,
                                               ln=ln_for_preview,
                                               search_pattern=keywords,
                                               xml_record=None,
                                               user_info=user_info)
        body = format_with_format_template(bft,
                                           bfo,
                                           verbose=7,
                                           format_template_code=code)

        if content_type_for_preview == 'text/html':
            #Standard page display with CDS headers, etc.
            return page(title="",
                        body=body,
                        uid=uid,
                        language=ln_for_preview,
                        navtrail=navtrail,
                        lastupdated=__lastupdated__,
                        req=req,
                        navmenuid='search')
        else:
            #Output with chosen content-type.
            req.content_type = content_type_for_preview
            req.send_http_header()
            req.write(body)
    else:
        return page_not_authorized(req=req, text=auth_msg)
                else:
                    reviews = 0
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                try:
                    raise InvenioWebCommentWarning(_('Comment ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

        elif recID > 0:
            if record_exists(recID):
                comID = ''
                reviews = wash_url_argument(reviews, 'int')
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                try:
                    raise InvenioWebCommentWarning(_('Record ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_RECID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)
        else:
            return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

    else:
        return webcomment_templates.tmpl_admin_delete_form(ln, warnings)
Example #60
0
def kb_update_attributes(req,
                         kb="",
                         name="",
                         description="",
                         sortby="to",
                         ln=CFG_SITE_LANG,
                         chosen_option=None,
                         kb_type=None):
    """
    Update the attributes of the kb

    @param ln language
    @param kb the kb id to update
    @param sortby the sorting criteria ('from' or 'to')
    @param name the new name of the kn
    @param description the new description of the kb
    @param chosen_option set to dialog box value
    """

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (
        CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

    try:
        dummy = getUid(req)
    except MySQLdb.Error:
        return error_page(req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        kb_id = wash_url_argument(kb, 'int')
        if chosen_option is not None:
            # Update could not be performed.
            # Redirect to kb attributes page
            redirect_to_url(
                req,
                "kb?ln=%(ln)s&amp;action=attributes&amp;kb=%(kb)s&sortby=%(sortby)s&kb_type=%(kb_type)s"
                % {
                    'ln': ln,
                    'kb': kb_id,
                    'sortby': sortby,
                    'kb_type': kb_type
                })

        kb_name = bibknowledge.get_kb_name(kb_id)

        if kb_name is None:
            return page(title=_("Unknown Knowledge Base"),
                        body="",
                        language=ln,
                        navtrail=navtrail_previous_links,
                        errors=[("ERR_KB_ID_UNKNOWN", kb)],
                        lastupdated=__lastupdated__,
                        req=req)

        new_name = wash_url_argument(name, 'str')
        if kb_name != new_name and bibknowledge.kb_exists(new_name):
            #A knowledge base with that name already exist
            #Do not update
            return dialog_box(req=req,
                              ln=ln,
                              title="Name already in use",
                              message="""<i>%s</i> cannot be renamed to %s:
                                        Another knowledge base already has that name.
                                        <br/>Please choose another name.""" %
                              (kb_name, new_name),
                              navtrail=navtrail_previous_links,
                              options=[_("Ok")])

        new_desc = wash_url_argument(description, 'str')
        bibknowledge.update_kb_attributes(kb_name, new_name, new_desc)
        redirect_to_url(
            req, "kb?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s" % {
                'ln': ln,
                'kb': kb_id,
                'sortby': sortby
            })
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)