Exemple #1
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(success), argd['ln'])
        redirect_to_url(req, display_url)
Exemple #2
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)}
            )
            target = (
                CFG_SITE_SECURE_URL
                + "/youraccount/login"
                + make_canonical_urlargd(
                    {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_SECURE_URL + user_info["uri"]}, {}
                )
            )
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", text=auth_msg)

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_SECURE_URL,
            CFG_SITE_RECORD,
            self.recid,
            str(success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
Exemple #3
0
    def sub(self, req, form):
        """DEPRECATED: /submit/sub is deprecated now, so raise email to the admin (but allow submission to continue anyway)"""
        args = wash_urlargd(form, {'password': (str, '')})
        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "../sub/",
                                       navmenuid='submit')
        try:
            raise DeprecationWarning, 'submit/sub handler has been used. Please use submit/direct. e.g. "submit/sub?RN=123@SBIFOO" -> "submit/direct?RN=123&sub=SBIFOO"'
        except DeprecationWarning:
            register_exception(req=req, alert_admin=True)

        ln = args['ln']
        _ = gettext_set_language(ln)
        #DEMOBOO_RN=DEMO-BOOK-2008-001&ln=en&password=1223993532.26572%40APPDEMOBOO
        params = dict(form)
        password = args['password']
        if password:
            del params['password']
            if "@" in password:
                params['access'], params['sub'] = password.split('@', 1)
            else:
                params['sub'] = password
        else:
            args = str(req.args).split('@')
            if len(args) > 1:
                params = {'sub' : args[-1]}
                args = '@'.join(args[:-1])
                params.update(cgi.parse_qs(args))
            else:
                return warning_page(_("Sorry, invalid URL..."), req, ln=ln)
        url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL, urlencode(params, doseq=True))
        redirect_to_url(req, url)
Exemple #4
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

        user_info = collect_user_info(req)
        uid = getUid(req)

        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)}
            )
            target = (
                CFG_SITE_SECURE_URL
                + "/youraccount/login"
                + make_canonical_urlargd(
                    {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_SECURE_URL + user_info["uri"]}, {}
                )
            )
            return redirect_to_url(req, target, norobot=True)

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_SECURE_URL,
            CFG_SITE_RECORD,
            self.recid,
            str(-success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
Exemple #5
0
 def new_ticket(self, req, form):
     """handle a edit/new_ticket request"""
     argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG), 'recid': (int, 0)})
     ln = argd['ln']
     _ = gettext_set_language(ln)
     auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
     if auth_code != 0:
         return page_not_authorized(req=req, referer="/edit",
                                    text=auth_message, navtrail=navtrail)
     uid = current_user.get_id()
     if argd['recid']:
         (errmsg, url) = perform_request_newticket(argd['recid'], uid)
         if errmsg:
             return page(title       = _("Failed to create a ticket"),
                         body        = _("Error")+": "+errmsg,
                         errors      = [],
                         warnings    = [],
                         uid         = uid,
                         language    = ln,
                         navtrail    = navtrail,
                         lastupdated = __lastupdated__,
                         req         = req,
                         body_css_classes = ['bibedit'])
         else:
             #redirect..
             redirect_to_url(req, url)
Exemple #6
0
            def goto_handler(req, form):
                ## Let's put what is in the GET query
                for key, value in dict(form).items():
                    if key in params_to_pass:
                        params_to_pass[key] = str(value)

                ## Let's override the params_to_pass to the call with the
                ## arguments in the configuration
                configuration_parameters = redirection_data['parameters'] or {}
                params_to_pass.update(configuration_parameters)

                ## Let's add default parameters if the plugin expects them
                if 'component' in params_to_pass:
                    params_to_pass['component'] = component
                if 'path' in params_to_pass:
                    params_to_pass['path'] = path
                if 'user_info' in params_to_pass:
                    params_to_pass['user_info'] = collect_user_info(req)
                if 'req' in params_to_pass:
                    params_to_pass['req'] = req
                try:
                    new_url = goto_plugin(**params_to_pass)
                except Exception as err:
                    register_exception(req=req, alert_admin=True)
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
                if new_url:
                    if new_url.startswith('/'):
                        new_url = CFG_SITE_URL + new_url
                    redirect_to_url(req, new_url)
                else:
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
Exemple #7
0
 def issue_control(self, req, form):
     """
     page that allows full control over creating, backtracing, adding to,
     removing from issues.
     """
     argd = wash_urlargd(
         form,
         {
             "name": (str, ""),
             "add": (str, ""),
             "action_publish": (str, "cfg"),
             "issue_number": (list, []),
             "ln": (str, ""),
         },
     )
     redirect_to_url(
         req,
         CFG_SITE_SECURE_URL
         + "/admin/webjournal/webjournaladmin.py/issue_control?journal_name="
         + argd["name"]
         + "&ln="
         + argd["ln"]
         + "&issue="
         + argd["issue_number"]
         + "&action="
         + argd["action_publish"],
     )
Exemple #8
0
def kb_add(req, ln=CFG_SITE_LANG, sortby="to", kbtype=""):
    """
    Adds a new kb
    @param req the request
    @param ln language
    @param sortby to or from
    @param kbtype type of knowledge base. one of: "", taxonomy, dynamic
    """
    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:
        name = "Untitled"
        if kbtype == "taxonomy":
            name = "Untitled Taxonomy"
        if kbtype == "dynamic":
            name = "Untitled dynamic"
        kb_id = bibknowledge.add_kb(kb_name=name, kb_type=kbtype)
        redirect_to_url(req, "kb?ln=%(ln)s&amp;action=attributes&amp;kb=%(kb)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
    else:
        navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Exemple #9
0
    def __call__(self, req, form):
        argd = wash_urlargd(form, {
            'id' : (int, 0),
            'format' : (str, '')})

        formats_dict = get_output_formats(True)
        formats = {}
        for f in formats_dict.values():
            if f['attrs']['visibility']:
                formats[f['attrs']['code'].lower()] = f['attrs']['content_type']
        del formats_dict

        if argd['id'] and argd['format']:
            ## Translate back common format names
            f = {
                'nlm' : 'xn',
                'marcxml' : 'xm',
                'dc' : 'xd',
                'endnote' : 'xe',
                'mods' : 'xo'
            }.get(argd['format'], argd['format'])
            if f in formats:
                redirect_to_url(req, '%s/%s/%s/export/%s' % (CFG_SITE_URL, CFG_SITE_RECORD, argd['id'], f))
            else:
                raise apache.SERVER_RETURN, apache.HTTP_NOT_ACCEPTABLE
        elif argd['id']:
            return websearch_templates.tmpl_unapi(formats, identifier=argd['id'])
        else:
            return websearch_templates.tmpl_unapi(formats)
Exemple #10
0
    def sub(self, req, form):
        """DEPRECATED: /submit/sub is deprecated now, so raise email to the admin (but allow submission to continue anyway)"""
        args = wash_urlargd(form, {'password': (str, '')})
        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "../sub/", navmenuid='submit')
        try:
            raise DeprecationWarning, 'submit/sub handler has been used. Please use submit/direct. e.g. "submit/sub?RN=123@SBIFOO" -> "submit/direct?RN=123&sub=SBIFOO"'
        except DeprecationWarning:
            register_exception(req=req, alert_admin=True)

        ln = args['ln']
        _ = gettext_set_language(ln)
        #DEMOBOO_RN=DEMO-BOOK-2008-001&ln=en&password=1223993532.26572%40APPDEMOBOO
        params = dict(form)
        password = args['password']
        if password:
            del params['password']
            if "@" in password:
                params['access'], params['sub'] = password.split('@', 1)
            else:
                params['sub'] = password
        else:
            args = str(req.args).split('@')
            if len(args) > 1:
                params = {'sub': args[-1]}
                args = '@'.join(args[:-1])
                params.update(cgi.parse_qs(args))
            else:
                return warning_page(_("Sorry, invalid URL..."), req, ln=ln)
        url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL,
                                       urlencode(params, doseq=True))
        redirect_to_url(req, url)
Exemple #11
0
            def goto_handler(req, form):
                ## Let's put what is in the GET query
                for key, value in dict(form).items():
                    if key in params_to_pass:
                        params_to_pass[key] = str(value)

                ## Let's override the params_to_pass to the call with the
                ## arguments in the configuration
                configuration_parameters = redirection_data['parameters'] or {}
                params_to_pass.update(configuration_parameters)

                ## Let's add default parameters if the plugin expects them
                if 'component' in params_to_pass:
                    params_to_pass['component'] = component
                if 'path' in params_to_pass:
                    params_to_pass['path'] = path
                if 'user_info' in params_to_pass:
                    params_to_pass['user_info'] = collect_user_info(req)
                if 'req' in params_to_pass:
                    params_to_pass['req'] = req
                try:
                    new_url = goto_plugin(**params_to_pass)
                except Exception as err:
                    register_exception(req=req, alert_admin=True)
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
                if new_url:
                    if new_url.startswith('/'):
                        new_url = CFG_SITE_URL + new_url
                    redirect_to_url(req, new_url)
                else:
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
Exemple #12
0
def output_format_add(req, ln=CFG_SITE_LANG):
    """
    Adds a new output format

    @param req: the request object
    @param ln: language
    @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:

        bfo = bibformatadminlib.add_output_format()
        if bfo == None:
            return page(title=_("Cannot create output format"),
                        body = """BibFormat cannot add an output format.
                        Check output formats directory permissions.""",
                        language=ln,
                        lastupdated=__lastupdated__,
                        req=req)
        redirect_to_url(req, "output_format_show_attributes?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln, 'bfo':bfo})
    else:
        return page_not_authorized(req=req, text=auth_msg)
Exemple #13
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)
Exemple #14
0
def index(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
    """Approval web Interface.
    GET params:

    """
    uid = getUid(req)
    (auth_code, auth_message) = acc_authorize_action(uid, 'submit')
    if auth_code > 0 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
        return page_not_authorized(req,
                                   "../approve.py/index",
                                   navmenuid='yourapprovals',
                                   text=auth_message)

    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    args = wash_urlargd(req.form, {'access': (str, '')})
    if args['access'] == "":
        return warning_page(
            _("approve.py: cannot determine document reference"), req, ln)
    url_params = get_approval_url_parameters(args['access'])
    if not url_params:
        return warning_page(_("approve.py: cannot find document in database"),
                            req, ln)
    url_params['ln'] = ln
    url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL,
                                   urllib.urlencode(url_params))
    redirect_to_url(req, url)
Exemple #15
0
    def metasubmit(self, req, form):
        """ Function called after submitting the metadata upload form.
            Checks if input fields are correct before uploading.
        """
        argd = wash_urlargd(
            form, {
                'metafile': (str, None),
                'filetype': (str, None),
                'mode': (str, None),
                'submit_date': (str, None),
                'submit_time': (str, None),
                'filename': (str, None),
                'priority': (str, None),
                'email_logs_to': (str, None)
            })
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed
        if argd['metafile'] == None:
            redirect_to_url(
                req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL))

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized

        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        auth_code, auth_message = metadata_upload(req, argd['metafile'],
                                                  argd['filetype'],
                                                  argd['mode'].split()[0],
                                                  date, time, argd['filename'],
                                                  argd['ln'], argd['priority'],
                                                  argd['email_logs_to'])

        if auth_code == 1:  # not authorized
            referer = '/batchuploader/'
            return page_not_authorized(req=req,
                                       referer=referer,
                                       text=auth_message,
                                       navmenuid="batchuploader")
        else:
            uid = getUid(req)
            body = batchuploader_templates.tmpl_display_menu(argd['ln'])
            body += batchuploader_templates.tmpl_upload_successful(argd['ln'])
            title = _("Upload successful")
            navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                            (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
            return page(title=title,
                        body=body,
                        uid=uid,
                        navtrail=navtrail,
                        lastupdated=__lastupdated__,
                        req=req,
                        language=argd['ln'],
                        navmenuid="batchuploader")
Exemple #16
0
 def index(self, req, form):
     #take all the parameters..
     unparsed_uri = req.unparsed_uri
     qstr = ""
     if unparsed_uri.count('?') > 0:
         dummy, qstr = unparsed_uri.split('?')
         qstr = '?'+qstr
     redirect_to_url(req, '/yourtickets/display'+qstr)
Exemple #17
0
 def openurl(self, req, form):
     """ OpenURL Handler."""
     argd = wash_urlargd(form, websearch_templates.tmpl_openurl_accepted_args)
     ret_url = websearch_templates.tmpl_openurl2invenio(argd)
     if ret_url:
         return redirect_to_url(req, ret_url)
     else:
         return redirect_to_url(req, CFG_SITE_URL)
Exemple #18
0
        def _index(req, c, ln, doctype, act, startPg, access,
                   mainmenu, fromdir, nextPg, nbPg, curpage, step,
                   mode):
            auth_args = {}
            if doctype:
                auth_args['doctype'] = doctype
            if act:
                auth_args['act'] = act
            uid = getUid(req)

            if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
                return page_not_authorized(req, "direct",
                                            navmenuid='submit')

            if CFG_CERN_SITE:
                ## HACK BEGIN: this is a hack for CMS and ATLAS draft
                user_info = collect_user_info(req)
                if doctype == 'CMSPUB' and act == "" and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**':
                    if isGuestUser(uid):
                        return redirect_to_url(req, "%s/youraccount/login%s" % (
                            CFG_SITE_SECURE_URL,
                            make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {}))
                                               , norobot=True)
                    if 'cms-publication-committee-chair [CERN]' not in user_info['group']:
                        return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of the CMS Publication Committee Chair.",
                                        navmenuid='submit')
                elif doctype == 'ATLPUB' and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**':
                    if isGuestUser(uid):
                        return redirect_to_url(req, "%s/youraccount/login%s" % (
                            CFG_SITE_SECURE_URL,
                            make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {}))
                                               , norobot=True)
                    if 'atlas-gen [CERN]' not in user_info['group']:
                        return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of ATLAS.",
                                        navmenuid='submit')
            ## HACK END

            if doctype == "":
                catalogues_text, at_least_one_submission_authorized, submission_exists = makeCataloguesTable(req, ln=CFG_SITE_LANG)
                if not at_least_one_submission_authorized and submission_exists:

                    if isGuestUser(uid):
                        return redirect_to_url(req, "%s/youraccount/login%s" % (
                            CFG_SITE_SECURE_URL,
                            make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {}))
                                            , norobot=True)
                    else:

                        return page_not_authorized(req, "../submit",
                                                   uid=uid,
                                                   navmenuid='submit')
                return home(req, catalogues_text, c, ln)
            elif act == "":
                return action(req, c, ln, doctype)
            elif int(step)==0:
                return interface(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage)
            else:
                return endaction(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode)
Exemple #19
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_SECURE_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)
Exemple #20
0
    def article(self, req, form):
        """
        Article page.
        Washes all the parameters and stores them in journal_defaults dict
        for subsequent format_elements.
        Passes on to logic function and eventually returns HTML.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                    'issue': (str, ""),
                                    'category': (str, ""),
                                    'number': (str, ""),
                                    'ln': (str, ""),
                                   }
                            )
        try:
            ln = wash_journal_language(argd['ln'])
            journal_name = wash_journal_name(ln, argd['name'])
            issue = wash_issue_number(ln, journal_name,
                                      argd['issue'])
            issue_year = issue.split('/')[1]
            issue_number = issue.split('/')[0]
            category = wash_category(ln, argd['category'], journal_name, issue_number)
            number = wash_article_number(ln, argd['number'], journal_name)
            recid = get_recid_from_legacy_number(issue, category, int(number))
        except InvenioWebJournalNoJournalOnServerError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoNameError as e:
            return e.user_box(req)
        except InvenioWebJournalNoCurrentIssueError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalIssueNumberBadlyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoArticleNumberError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoCategoryError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalJournalIdNotFoundDBError as e:
            register_exception(req=req)
            return e.user_box(req)

        if recid != -1:
            # Found a corresponding record
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '/' + str(recid) + '?ln=' + ln)
        else:
            # Corresponding record not found. Display index
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '?ln=' + ln)
Exemple #21
0
    def __call__(self, req, form):
        """Redirect calls without final slash."""

        if self.recid:
            redirect_to_url(req, '%s/%s/%s/edit/' % (CFG_SITE_SECURE_URL,
                                                         CFG_SITE_RECORD,
                                                         self.recid))
        else:
            redirect_to_url(req, '%s/%s/edit/' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD))
Exemple #22
0
    def confirm(self, req, form):
        """ Function called after submitting the metadata upload form.
            Shows a summary of actions to be performed and possible errors
        """
        argd = wash_urlargd(
            form, {
                'metafile': (Field, None),
                'filetype': (str, None),
                'mode': (str, None),
                'submit_date': (str, None),
                'submit_time': (str, None),
                'filename': (str, None),
                'priority': (str, None),
                'skip_simulation': (str, None),
                'email_logs_to': (str, None)
            })
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed or no file selected
        if not argd['metafile']:
            redirect_to_url(
                req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL))

        metafile = argd['metafile'].value
        if argd['filetype'] != 'marcxml':
            metafile = _transform_input_to_marcxml(file_input=metafile)


        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        errors_upload = ''

        skip_simulation = argd['skip_simulation'] == "skip"
        if not skip_simulation:
            errors_upload = perform_upload_check(metafile, argd['mode'])

        body = batchuploader_templates.tmpl_display_confirm_page(
            argd['ln'], metafile, argd['filetype'], argd['mode'], date, time,
            argd['filename'], argd['priority'], errors_upload, skip_simulation,
            argd['email_logs_to'])

        uid = getUid(req)
        navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                    (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
        title = 'Confirm your actions'
        return page(title=title,
                    body=body,
                    metaheaderadd=batchuploader_templates.tmpl_styles(),
                    uid=uid,
                    navtrail=navtrail,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="batchuploader")
Exemple #23
0
    def article(self, req, form):
        """
        Article page.
        Washes all the parameters and stores them in journal_defaults dict
        for subsequent format_elements.
        Passes on to logic function and eventually returns HTML.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                    'issue': (str, ""),
                                    'category': (str, ""),
                                    'number': (str, ""),
                                    'ln': (str, ""),
                                   }
                            )
        try:
            ln = wash_journal_language(argd['ln'])
            journal_name = wash_journal_name(ln, argd['name'])
            issue = wash_issue_number(ln, journal_name,
                                      argd['issue'])
            issue_year = issue.split('/')[1]
            issue_number = issue.split('/')[0]
            category = wash_category(ln, argd['category'], journal_name, issue_number)
            number = wash_article_number(ln, argd['number'], journal_name)
            recid = get_recid_from_legacy_number(issue, category, int(number))
        except InvenioWebJournalNoJournalOnServerError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoNameError as e:
            return e.user_box(req)
        except InvenioWebJournalNoCurrentIssueError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalIssueNumberBadlyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoArticleNumberError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoCategoryError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalJournalIdNotFoundDBError as e:
            register_exception(req=req)
            return e.user_box(req)

        if recid != -1:
            # Found a corresponding record
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '/' + str(recid) + '?ln=' + ln)
        else:
            # Corresponding record not found. Display index
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '?ln=' + ln)
Exemple #24
0
    def confirm(self, req, form):
        """ Function called after submitting the metadata upload form.
            Shows a summary of actions to be performed and possible errors
        """
        argd = wash_urlargd(form, {'metafile': (Field, None),
                                   'filetype': (str, None),
                                   'mode': (str, None),
                                   'submit_date': (str, None),
                                   'submit_time': (str, None),
                                   'filename': (str, None),
                                   'priority': (str, None),
                                   'skip_simulation': (str, None),
                                   'email_logs_to': (str, None)})
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed or no file selected
        if not argd['metafile']:
            redirect_to_url(req, "%s/batchuploader/metadata"
            % (CFG_SITE_SECURE_URL))

        metafile = argd['metafile'].value
        if argd['filetype'] != 'marcxml':
            metafile = _transform_input_to_marcxml(file_input=metafile)


        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        errors_upload = ''

        skip_simulation = argd['skip_simulation'] == "skip"
        if not skip_simulation:
            errors_upload = perform_upload_check(metafile, argd['mode'])

        body = batchuploader_templates.tmpl_display_confirm_page(argd['ln'],
                                                                 metafile, argd['filetype'], argd['mode'], date,
                                                                 time, argd['filename'], argd['priority'], errors_upload,
                                                                 skip_simulation, argd['email_logs_to'])

        uid = getUid(req)
        navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                    (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
        title = 'Confirm your actions'
        return page(title = title,
                    body = body,
                    metaheaderadd = batchuploader_templates.tmpl_styles(),
                    uid = uid,
                    navtrail = navtrail,
                    lastupdated = __lastupdated__,
                    req = req,
                    language = argd['ln'],
                    navmenuid = "batchuploader")
Exemple #25
0
    def regenerate(self, req, form):
        """
        Clears the cache for the issue given.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                   'issue': (str, ""),
                                   'ln': (str, "")})

        redirect_to_url(req, CFG_SITE_SECURE_URL + \
                        '/admin/webjournal/webjournaladmin.py/regenerate?journal_name=' + \
                        argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue'])
Exemple #26
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)
Exemple #27
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_SECURE_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)
Exemple #28
0
    def regenerate(self, req, form):
        """
        Clears the cache for the issue given.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                   'issue': (str, ""),
                                   'ln': (str, "")})

        redirect_to_url(req, CFG_SITE_SECURE_URL + \
                        '/admin/webjournal/webjournaladmin.py/regenerate?journal_name=' + \
                        argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue'])
Exemple #29
0
    def metasubmit(self, req, form):
        """ Function called after submitting the metadata upload form.
            Checks if input fields are correct before uploading.
        """
        argd = wash_urlargd(form, {'metafile': (str, None),
                                   'filetype': (str, None),
                                   'mode': (str, None),
                                   'submit_date': (str, None),
                                   'submit_time': (str, None),
                                   'filename': (str, None),
                                   'priority': (str, None),
                                   'email_logs_to': (str, None)})
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed
        if argd['metafile']  == None:
            redirect_to_url(req, "%s/batchuploader/metadata"
            % (CFG_SITE_SECURE_URL))

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized

        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        auth_code, auth_message = metadata_upload(req,
                                  argd['metafile'], argd['filetype'],
                                  argd['mode'].split()[0],
                                  date, time, argd['filename'], argd['ln'],
                                  argd['priority'], argd['email_logs_to'])

        if auth_code == 1: # not authorized
            referer = '/batchuploader/'
            return page_not_authorized(req=req, referer=referer,
                        text=auth_message, navmenuid="batchuploader")
        else:
            uid = getUid(req)
            body = batchuploader_templates.tmpl_display_menu(argd['ln'])
            body += batchuploader_templates.tmpl_upload_successful(argd['ln'])
            title = _("Upload successful")
            navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                            (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
            return page(title = title,
                        body = body,
                        uid = uid,
                        navtrail = navtrail,
                        lastupdated = __lastupdated__,
                        req = req,
                        language = argd['ln'],
                        navmenuid = "batchuploader")
Exemple #30
0
    def feature_record(self, req, form):
        """
        Interface to feature a record. Will be saved in a flat file.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                   'recid': (str, "init"),
                                   'url': (str, "init"),
                                   'ln': (str, "")})

        redirect_to_url(req, CFG_SITE_SECURE_URL + \
                        '/admin/webjournal/webjournaladmin.py/feature_record?journal_name=' + \
                        argd['name'] + '&ln=' + argd['ln'] + '&recid='+ argd['recid'] + '&url='+ argd['url'])
Exemple #31
0
    def feature_record(self, req, form):
        """
        Interface to feature a record. Will be saved in a flat file.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                   'recid': (str, "init"),
                                   'url': (str, "init"),
                                   'ln': (str, "")})

        redirect_to_url(req, CFG_SITE_SECURE_URL + \
                        '/admin/webjournal/webjournaladmin.py/feature_record?journal_name=' + \
                        argd['name'] + '&ln=' + argd['ln'] + '&recid='+ argd['recid'] + '&url='+ argd['url'])
Exemple #32
0
def perform_request_index(req, journal_name, issue_number, ln,
                          category, editor=False, verbose=0):
    """
    Central logic function for index pages.
    Brings together format templates and MARC rules from the config, with
    the requested index page, given by the url parameters.
    From config:
        - page template for index pages -> formatting
        - MARC rule list -> Category Navigation
        - MARC tag used for issue numbers -> search (later in the format
          elements)
    Uses BibFormatObject and format_with_format_template to produce the
    required HTML.
    """
    current_issue = get_current_issue(ln, journal_name)
    if not get_release_datetime(issue_number, journal_name):
        # Unreleased issue. Display latest released issue?
        unreleased_issues_mode = get_unreleased_issue_hiding_mode(journal_name)
        if not editor and \
               (unreleased_issues_mode == 'all' or \
                (unreleased_issues_mode == 'future' and \
                 issue_is_later_than(issue_number, current_issue))):
            redirect_to_url(req, "%s/journal/%s/%s/%s?ln=%s" % \
                            (CFG_SITE_URL,
                             journal_name,
                             current_issue.split('/')[1],
                             current_issue.split('/')[0],
                             ln))
    try:
        index_page_template = get_journal_template('index',
                                                   journal_name,
                                                   ln)
    except InvenioWebJournalTemplateNotFoundError as e:
        register_exception(req=req)
        return e.user_box(req)

    temp_marc = '''<record>
                        <controlfield tag="001">0</controlfield>
                    </record>'''
    # create a record and get HTML back from bibformat
    user_info = collect_user_info(req)
    bfo = BibFormatObject(0, ln=ln, xml_record=temp_marc,
                          user_info=user_info)
    bfo.req = req
    verbosity = 0
    if editor:
        # Increase verbosity only for editors/admins
        verbosity = verbose

    html = format_with_format_template(index_page_template,
                                       bfo,
                                       verbose=verbosity)
    return html
Exemple #33
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)
Exemple #34
0
    def direct(self, req, form):
        """Directly redirected to an initialized submission."""
        args = wash_urlargd(form, {'sub': (str, ''),
                                   'access' : (str, '')})

        sub = args['sub']
        access = args['access']
        ln = args['ln']

        _ = gettext_set_language(ln)

        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "direct",
                                           navmenuid='submit')

        myQuery = req.args
        if not sub:
            return warning_page(_("Sorry, 'sub' parameter missing..."), req, ln=ln)
        res = run_sql("SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s", (sub,))
        if not res:
            return warning_page(_("Sorry. Cannot analyse parameter"), req, ln=ln)
        else:
            # get document type
            doctype = res[0][0]
            # get action name
            action = res[0][1]
        # retrieve other parameter values
        params = dict(form)
        # find existing access number
        if not access:
            # create 'unique' access number
            pid = os.getpid()
            now = time.time()
            access = "%i_%s" % (now, pid)
        # retrieve 'dir' value
        res = run_sql ("SELECT dir FROM sbmACTION WHERE sactname=%s", (action,))
        dir = res[0][0]

        mainmenu = req.headers_in.get('referer')

        params['access'] = access
        params['act'] = action
        params['doctype'] = doctype
        params['startPg'] = '1'
        params['mainmenu'] = mainmenu
        params['ln'] = ln
        params['indir'] = dir

        url = "%s/submit?%s" % (CFG_SITE_SECURE_URL, urlencode(params))
        redirect_to_url(req, url)
Exemple #35
0
 def issue_control(self, req, form):
     """
     page that allows full control over creating, backtracing, adding to,
     removing from issues.
     """
     argd = wash_urlargd(form, {'name': (str, ""),
                                'add': (str, ""),
                                'action_publish': (str, "cfg"),
                                'issue_number': (list, []),
                                'ln': (str, "")})
     redirect_to_url(req, CFG_SITE_SECURE_URL + \
                     '/admin/webjournal/webjournaladmin.py/issue_control?journal_name=' + \
                     argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue_number'] + \
                     '&action=' + argd['action_publish'])
Exemple #36
0
 def issue_control(self, req, form):
     """
     page that allows full control over creating, backtracing, adding to,
     removing from issues.
     """
     argd = wash_urlargd(form, {'name': (str, ""),
                                'add': (str, ""),
                                'action_publish': (str, "cfg"),
                                'issue_number': (list, []),
                                'ln': (str, "")})
     redirect_to_url(req, CFG_SITE_SECURE_URL + \
                     '/admin/webjournal/webjournaladmin.py/issue_control?journal_name=' + \
                     argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue_number'] + \
                     '&action=' + argd['action_publish'])
Exemple #37
0
def perform_request_search(req, journal_name, ln,
                           archive_issue, archive_select,
                           archive_date, archive_search, verbose=0):
    """
    Logic for the search / archive page.
    """
    try:
        search_page_template = get_journal_template('search',
                                                    journal_name,
                                                    ln)
    except InvenioWebJournalTemplateNotFoundError as e:
        register_exception(req=req)
        return e.user_box(req)

    if archive_select == "False" and archive_search == "False":
        temp_marc = '''<record>
                            <controlfield tag="001">0</controlfield>
                        </record>'''

        user_info = collect_user_info(req)
        bfo = BibFormatObject(0,
                              ln=ln,
                              xml_record=temp_marc,
                              user_info=user_info)
        bfo.req = req
        html = format_with_format_template(search_page_template,
                                           bfo,
                                           verbose=verbose)
        return html

    elif archive_select == "Go":
        redirect_to_url(req, "%s/journal/%s/%s/%s?ln=%s" % (CFG_SITE_URL,
                                                            journal_name,
                                                            archive_issue.split('/')[1],
                                                            archive_issue.split('/')[0],
                                                            ln))
    elif archive_search == "Go":
        try:
            archive_issue_time = datetime.datetime(*time.strptime(archive_date, "%d/%m/%Y")[0:5])
            archive_issue = datetime_to_issue(archive_issue_time, journal_name)
            if not archive_issue:
                archive_issue = get_current_issue(ln, journal_name)
        except ValueError:
            archive_issue = get_current_issue(ln, journal_name)
        redirect_to_url(req, "%s/journal/%s/%s/%s?ln=%s" % (CFG_SITE_URL,
                                                            journal_name,
                                                            archive_issue.split('/')[1],
                                                            archive_issue.split('/')[0],
                                                            ln))
Exemple #38
0
def kb_dynamic_update(req,
                      kb_id,
                      field,
                      expression,
                      collection,
                      ln=CFG_SITE_LANG):
    """
    Updates the configuration of a collection based KB by checking user
    rights and calling bibknowledgeadminlib..
    @param req request
    @param kb_id knowledge base id
    @param field configured field for this dynamic kb
    @param expression search expression
    @param collection search in this collection
    @param ln language
    """
    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:
        #actual config call
        err = bibknowledgeadminlib.perform_update_kb_config(
            kb_id, field, expression, collection)
        if err:
            return page(title=_("Error"),
                        body=err,
                        language=ln,
                        navtrail=navtrail_previous_links,
                        lastupdated=__lastupdated__,
                        req=req)

        else:
            redirect_to_url(
                req, "kb?ln=%(ln)s&kb=%(kb_id)s" % {
                    'ln': ln,
                    'kb_id': kb_id
                })
    else:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Exemple #39
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)
Exemple #40
0
def del_single_com_mod(req, ln=CFG_SITE_LANG, id=""):
    """
    Allow moderator to delete a single comment
    @param req: request object to obtain user information
    @param ln: language
    @param id: comment id
    """
    ln = wash_language(ln)
    user_info = collect_user_info(req)
    referer = user_info['referer']
    (auth_code, auth_msg) = check_user(req,'cfgwebcomment')
    if (auth_code != 'false') or check_user_is_author(user_info['uid'], id):
        perform_request_del_single_com_mod(ln=ln, id=id)
        redirect_to_url(req, referer)
    else:
        return page_not_authorized(req=req, text=auth_msg)
Exemple #41
0
    def __call__(self, req, form):
        """ Maybe resolve the final / of a directory """

        # When this method is called, we either are a directory which
        # has an 'index' method, and we redirect to it, or we don't
        # have such a method, in which case it is a traversal error.

        if "" in self._exports:
            if not form:
                # Fix missing trailing slash as a convenience, unless
                # we are processing a form (in which case it is better
                # to fix the form posting).
                redirect_to_url(req, req.uri + "/", apache.HTTP_MOVED_PERMANENTLY)

        _debug(req, 'directory %r is not callable' % self)
        raise TraversalError()
Exemple #42
0
def del_single_com_mod(req, ln=CFG_SITE_LANG, id=""):
    """
    Allow moderator to delete a single comment
    @param req: request object to obtain user information
    @param ln: language
    @param id: comment id
    """
    ln = wash_language(ln)
    user_info = collect_user_info(req)
    referer = user_info['referer']
    (auth_code, auth_msg) = check_user(req, 'cfgwebcomment')
    if (auth_code != 'false') or check_user_is_author(user_info['uid'], id):
        perform_request_del_single_com_mod(ln=ln, id=id)
        redirect_to_url(req, referer)
    else:
        return page_not_authorized(req=req, text=auth_msg)
Exemple #43
0
def unreport_com(req, ln=CFG_SITE_LANG, id=""):
    """
    Unreport a comment
    @param req: request object to obtain user information
    @param ln: language
    @param id: comment id
    """
    ln = wash_language(ln)
    user_info = collect_user_info(req)
    referer = user_info['referer']
    (auth_code, auth_msg) = check_user(req, 'cfgwebcomment')
    if (auth_code != 'false'):
        perform_request_unreport_single_com(ln=ln, id=id)
        redirect_to_url(req, referer)
    else:
        return page_not_authorized(req=req, text=auth_msg)
Exemple #44
0
 def administrate(self, req, form):
     """Index page."""
     argd = wash_urlargd(form, {'name': (str, ""),
                                 'ln': (str, "")
                                 })
     try:
         ln = wash_journal_language(argd['ln'])
         journal_name = wash_journal_name(ln, argd['name'])
     except InvenioWebJournalNoJournalOnServerError as e:
         register_exception(req=req)
         return e.user_box(req)
     except InvenioWebJournalNoNameError as e:
         return e.user_box(req)
     redirect_to_url(req, CFG_SITE_SECURE_URL + \
                     '/admin/webjournal/webjournaladmin.py/administrate?journal_name=' + \
                     journal_name + '&ln=' + ln)
Exemple #45
0
    def check_authorization_moderatelinkbacks(self, req, argd):
        """
        Check if user has authorization moderate linkbacks
        @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized
        """
        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = acc_authorize_action(
            req,
            'moderatelinkbacks',
            collection=guess_primary_collection_of_a_record(self.recid))
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])
Exemple #46
0
    def regenerate(self, req, form):
        """
        Clears the cache for the issue given.
        """
        argd = wash_urlargd(form, {"name": (str, ""), "issue": (str, ""), "ln": (str, "")})

        redirect_to_url(
            req,
            CFG_SITE_SECURE_URL
            + "/admin/webjournal/webjournaladmin.py/regenerate?journal_name="
            + argd["name"]
            + "&ln="
            + argd["ln"]
            + "&issue="
            + argd["issue"],
        )
Exemple #47
0
def unreport_com(req, ln=CFG_SITE_LANG, id=""):
    """
    Unreport a comment
    @param req: request object to obtain user information
    @param ln: language
    @param id: comment id
    """
    ln = wash_language(ln)
    user_info = collect_user_info(req)
    referer = user_info['referer']
    (auth_code, auth_msg) = check_user(req,'cfgwebcomment')
    if (auth_code != 'false'):
        perform_request_unreport_single_com(ln=ln, id=id)
        redirect_to_url(req, referer)
    else:
        return page_not_authorized(req=req, text=auth_msg)
Exemple #48
0
    def display(self, req, form):
        """Display search history page.  A misnomer."""

        argd = wash_urlargd(form, {'p': (str, "n")
                                   })

        uid = getUid(req)

        # load the right language
        _ = gettext_set_language(argd['ln'])

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/youralerts/display" % \
                                             (CFG_SITE_SECURE_URL,),
                                       navmenuid="youralerts")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/youralerts/display%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_usealerts']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use alerts."))

        if argd['p'] == 'y':
            _title = _("Popular Searches")
        else:
            _title = _("Your Searches")

        # register event in webstat
        if user_info['email']:
            user_str = "%s (%d)" % (user_info['email'], user_info['uid'])
        else:
            user_str = ""
        try:
            register_customevent("alerts", ["display", "", user_str])
        except:
            register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'")

        return page(title=_title,
                    body=webalert.perform_display(argd['p'], uid, ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemple #49
0
    def __call__(self, req, form):
        """ Maybe resolve the final / of a directory """

        # When this method is called, we either are a directory which
        # has an 'index' method, and we redirect to it, or we don't
        # have such a method, in which case it is a traversal error.

        if "" in self._exports:
            if not form:
                # Fix missing trailing slash as a convenience, unless
                # we are processing a form (in which case it is better
                # to fix the form posting).
                redirect_to_url(req, req.uri + "/",
                                apache.HTTP_MOVED_PERMANENTLY)

        _debug(req, 'directory %r is not callable' % self)
        raise TraversalError()
Exemple #50
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)
        argd['recid'] = self.recid

        if self.format is not None:
            argd['of'] = self.format
        req.argd = argd
        uid = getUid(req)
        if uid == -1:
            return page_not_authorized(req, "../",
                text="You are not authorized to view this record.",
                                       navmenuid='search')
        elif uid > 0:
            pref = get_user_preferences(uid)
            try:
                if 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        # Check if the record belongs to a restricted primary
        # collection.  If yes, redirect to the authenticated URL.
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)

        if argd['rg'] > CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS and acc_authorize_action(req, 'runbibedit')[0] != 0:
            argd['rg'] = CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS

        #check if the user has rights to set a high wildcard limit
        #if not, reduce the limit set by user, with the default one
        if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0):
            if acc_authorize_action(req, 'runbibedit')[0] != 0:
                argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT

        # only superadmins can use verbose parameter for obtaining debug information
        if not isUserSuperAdmin(user_info):
            argd['verbose'] = 0

        if auth_code and user_info['email'] == 'guest':
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                    make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text=auth_msg, \
                navmenuid='search')

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if isinstance(out, intbitset):
            return out.fastdump()
        elif out == []:
            return str(out)
        else:
            return out
Exemple #51
0
    def _redirect_to_page(self, req, url, language):
        """Redirects user to a page with the given URL
        and language.

        @param req: request as received from apache
        @param language: the language of the page
        @param url: url to redirect to
        """
        # check which symbol to use for appending the parameters
        # if this is the only parameter use ?
        if -1 == url.find("?"):
            append_symbol = "?"
        # if there are other parameters already appended, use &
        else:
            append_symbol = "&"

        redirect_url = "%s%sln=%s" % (url, append_symbol, language)
        redirect_to_url(req, redirect_url)
Exemple #52
0
    def _check_user_credentials(self, req, language):
        """Check if the user is allowed to use field exporter

        @param req: request as received from apache
        @param language: the language of the page
        """
        user_info = collect_user_info(req)

        #redirect guests to login page
        if "1" == user_info["guest"]:
            referer_url = "%s?ln=%s" % (self._EXPORT_URL, language)
            redirect_url = "%s?ln=%s&referer=%s" % (self._LOGIN_URL, language,
                                                    referer_url)
            redirect_to_url(req, redirect_url)
        #redirect unauthorized user to not_authorized page
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgbibexport')
        if 0 != auth_code:
            self._redirect_to_not_authorised_page(req, language)
Exemple #53
0
    def index(self, req, form):
        """Index page."""

        argd = wash_urlargd(form, {'page': (int, 1),
                                   'format': (str, "rc"),
                                   'order_by': (str, "lcf"),
                                   'per_page': (str, "all"),
                                   })
        # TODO: support also "reviews", by adding  new option to show/hide them if needed
        uid = getUid(req)

        # load the right language
        _ = gettext_set_language(argd['ln'])

        # Is site ready to accept comments?
        if not CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourcomments" % \
                                             (CFG_SITE_SECURE_URL,),
                                       text="Comments are currently disabled on this site",
                                       navmenuid="yourcomments")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/yourcomments%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_sendcomments']:
            # Maybe we should still authorize if user submitted
            # comments in the past?
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use comments."))

        return page(title=_("Your Comments"),
                    body=perform_display_your_comments(user_info,
                                                       page_number=argd['page'],
                                                       selected_order_by_option=argd['order_by'],
                                                       selected_display_number_option=argd['per_page'],
                                                       selected_display_format_option=argd['format'],
                                                       ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemple #54
0
def resolve_doi(req, doi, ln=CFG_SITE_LANG, verbose=0):
    """
    Redirect to given DOI, or display error page when DOI cannot be
    resolved.
    """
    _ = gettext_set_language(ln)
    # Fetch user ID:
    try:
        uid = getUid(req)
    except Error:
        register_exception(req=req, alert_admin=True)
        return page(title=_("Internal Error"),
                    body=create_error_box(req, verbose=verbose, ln=ln),
                    description="%s - Internal Error" % CFG_SITE_NAME,
                    keywords="%s, Internal Error" % CFG_SITE_NAME,
                    language=ln,
                    req=req,
                    navmenuid='search')
    # Resolve DOI
    recids = perform_request_search(p='doi:"%s"' % doi, of="id", verbose=verbose)
    recids = [recid for recid in recids if doi.lower() in \
              [doi.lower() for doi in get_record(recid).get('doi', '') if doi]]

    # Answer
    if len(recids) == 1:
        # Found unique matching record
        return redirect_to_url(req, CFG_SITE_URL + '/' + CFG_SITE_RECORD + '/' + str(recids[0]))
    elif len(recids) == 0:
        # No corresponding record found
        page_body = '<p>' + (_("Sorry, DOI %(x_doi)s could not be resolved.", x_doi=('<strong>' + str(doi) + '</strong>'))) + '</p>'
        if req.header_only:
            raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
        return page(title=_('DOI "%(x_doi)s" Not Found', x_doi=cgi.escape(doi)),
                    body=page_body,
                    description=(CFG_SITE_NAME + ' - ' + _("Not found") + ': ' + cgi.escape(str(doi))),
                    keywords="%s" % CFG_SITE_NAME,
                    uid=uid,
                    language=ln,
                    req=req,
                    navmenuid='search')
    else:
        # Found multiple matching records
        try:
            raise Exception('DOI "%s" matched multiple records (%s) -- Please check' % (doi, ', '.join([str(recid) for recid in recids])))
        except Exception, e:
            register_exception(req=req, alert_admin=True)
        page_body = websearch_templates.tmpl_multiple_dois_found_page(doi, recids, ln)
        return page(title=_('Found multiple records matching DOI %(x_doi)s', x_doi=cgi.escape(doi)),
                    body=page_body,
                    description=(CFG_SITE_NAME + ' - ' + _("Found multiple records matching DOI") + ': ' + cgi.escape(str(doi))),
                    keywords="%s" % CFG_SITE_NAME,
                    uid=uid,
                    language=ln,
                    req=req,
                    navmenuid='search')
Exemple #55
0
    def __call__(self, req, form):
        """Called in case of URLs like /CFG_SITE_RECORD/123/files without
           trailing slash.
        """
        args = wash_urlargd(form, bibdocfile_templates.files_default_urlargd)
        ln = args['ln']
        link_ln = ''
        if ln != CFG_SITE_LANG:
            link_ln = '?ln=%s' % ln

        return redirect_to_url(req, '%s/%s/%s/files/%s' % (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, link_ln))
Exemple #56
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

        user_info = collect_user_info(req)
        uid = getUid(req)

        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(-success), argd['ln'])
        redirect_to_url(req, display_url)
Exemple #57
0
def kb_add(req, ln=CFG_SITE_LANG, sortby="to", kbtype=""):
    """
    Adds a new kb
    @param req the request
    @param ln language
    @param sortby to or from
    @param kbtype type of knowledge base. one of: "", taxonomy, dynamic
    """
    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:
        name = "Untitled"
        if kbtype == "taxonomy":
            name = "Untitled Taxonomy"
        if kbtype == "dynamic":
            name = "Untitled dynamic"
        kb_id = bibknowledge.add_kb(kb_name=name.decode('utf-8'),
                                    kb_type=kbtype)
        redirect_to_url(
            req, "kb?ln=%(ln)s&amp;action=attributes&amp;kb=%(kb)s" % {
                'ln': ln,
                'kb': kb_id,
                'sortby': sortby
            })
    else:
        navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (
            CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Exemple #58
0
    def __call__(self, req, form):
        """Serve webdoc page in the given language."""
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        if self.webdocname in ['admin', 'hacking', ''] and \
               self.categ == 'help' and \
               not (req.uri.endswith('.html') or \
                    req.uri.endswith('/help/search/') or \
                    req.uri.endswith('/help/submit/')):
            # Eg. /help/hacking -> /help/hacking/
            #     /help         -> /help/
            ln_link = (argd['ln'] != CFG_SITE_LANG
                       and '?ln=' + argd['ln']) or ''
            redirect_to_url(req, req.uri + "/" + ln_link)
        elif req.uri.endswith('.html') or \
                 req.uri.endswith('/help/search/') or \
                 req.uri.endswith('/help/submit/'):
            # Legacy urls
            path = req.uri.split('/')
            parts = path[-1].split('.')
            title = parts[0]
            ln = CFG_SITE_LANG
            if len(parts) > 1 and parts[1] in CFG_SITE_LANGS:
                ln = parts[1]
            category = path[-2]
            webdocname = self.legacy_urls_mappings.get(title, '')
            if category == 'submit':
                webdocname = 'submit-guide'
                category = ''
            elif category == 'help' or category == 'search':
                category = ''
            if category != '':
                category += '/'

            url = CFG_SITE_URL + '/help/' + category + webdocname
            ln_link = (ln != CFG_SITE_LANG and '?ln=' + ln) or ''
            redirect_to_url(req, url + ln_link)
        else:
            return display_webdoc_page(self.webdocname,
                                       categ=self.categ,
                                       ln=argd['ln'],
                                       req=req)