def uploadfile(self, req, form):
        """
        Similar to /submit, but only consider files. Nice for
        asynchronous Javascript uploads. Should be used to upload a
        single file.

        Also try to create an icon, and return URL to file(s) + icon(s)

        Authentication is performed based on session ID passed as
        parameter instead of cookie-based authentication, due to the
        use of this URL by the Flash plugin (to upload multiple files
        at once), which does not route cookies.

        FIXME: consider adding /deletefile and /modifyfile functions +
        parsing of additional parameters to rename files, add
        comments, restrictions, etc.
        """
        argd = wash_urlargd(form, {
            'doctype': (str, ''),
            'access': (str, ''),
            'indir': (str, ''),
            'session_id': (str, ''),
            'rename': (str, ''),
            })

        curdir = None
        if not form.has_key("indir") or \
               not form.has_key("doctype") or \
               not form.has_key("access"):
            raise apache.SERVER_RETURN(apache.HTTP_BAD_REQUEST)
        else:
            curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR,
                                  argd['indir'],
                                  argd['doctype'],
                                  argd['access'])

        user_info = collect_user_info(req)
        if form.has_key("session_id"):
            # Are we uploading using Flash, which does not transmit
            # cookie? The expect to receive session_id as a form
            # parameter.  First check that IP addresses do not
            # mismatch. A ValueError will be raises if there is
            # something wrong
            session = get_session(req=req, sid=argd['session_id'])
            try:
                session = get_session(req=req, sid=argd['session_id'])
            except ValueError, e:
                raise apache.SERVER_RETURN(apache.HTTP_BAD_REQUEST)

            # Retrieve user information. We cannot rely on the session here.
            res = run_sql("SELECT uid FROM session WHERE session_key=%s", (argd['session_id'],))
            if len(res):
                uid = res[0][0]
                user_info = collect_user_info(uid)
                try:
                    act_fd = file(os.path.join(curdir, 'act'))
                    action = act_fd.read()
                    act_fd.close()
                except:
                    action = ""
def perform_moderate_linkback(req, linkbackid, action):
    """
    Moderate linkbacks
    @param linkbackid: linkback id
    @param action: of CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION
    @return CFG_WEBLINKBACK_ACTION_RETURN_CODE
    """
    if action == CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION['APPROVE']:
        approve_linkback(linkbackid, collect_user_info(req))
    elif action == CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION['REJECT']:
        reject_linkback(linkbackid, collect_user_info(req))
    else:
        return CFG_WEBLINKBACK_ACTION_RETURN_CODE['INVALID_ACTION']

    return CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK']
Example #3
0
def linkbacks(req, status, returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'], ln=CFG_SITE_LANG):
    """
    Display linkbacks
    @param ln: language
    @param status: of CFG_WEBLINKBACK_STATUS, currently only CFG_WEBLINKBACK_STATUS['PENDING'] is supported
    """
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links +=' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    else:
        return page(title=_("Pending Linkbacks"),
                    body=perform_request_display_linkbacks(return_code=return_code, status=status, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    req=req)
def check_login(req):
    """Check that the user is logged in"""
    user_info = collect_user_info(req)
    if user_info['email'] == 'guest':
        # 1. User is guest: must login prior to upload
        # return 'Please login before uploading file.'
        pass
Example #5
0
def user_can_perform_action(uid, action, target_pid):
    '''
    ArXive login and stuff checking
    @param uid: the user ID to check permissions for
    @param action: in ['claim_own_paper','claim_other_paper']

    @return: is user allowed to perform action?
    @rtype: boolean
    '''
    #If no EXTERNAL_CLAIMED_RECORDS_KEY we bypass this check
    if not bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        return True

    uinfo = collect_user_info(uid)
    keys = []
    for k in bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        if k in uinfo:
            keys.append(k)

    full_key = False
    for k in keys:
        if uinfo[k]:
            full_key = True
            break

    return full_key
    def display(self, req, form):
        """
        Display approved latest added linkbacks of the invenio instance
        """
        argd = wash_urlargd(form, {'rg': (int, CFG_WEBLINKBACK_LATEST_COUNT_DEFAULT)})
        # count must be positive
        if argd['rg'] < 0:
            argd['rg'] = -argd['rg']

        _ = gettext_set_language(argd['ln'])

        user_info = collect_user_info(req)

        body = perform_request_display_approved_latest_added_linkbacks_to_accessible_records(argd['rg'], argd['ln'], user_info, weblinkback_templates=weblinkback_templates)

        navtrail = 'Recent Linkbacks'

        mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader()

        return pageheaderonly(title=navtrail,
                              navtrail=navtrail,
                              verbose=1,
                              metaheaderadd = mathjaxheader + jqueryheader,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
               body + \
               websearch_templates.tmpl_search_pageend(argd['ln']) + \
               pagefooteronly(language=argd['ln'], req=req)
Example #7
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, err:
                    register_exception(req=req, alert_admin=True)
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
def user_can_perform_action(uid, action, target_pid):
    '''
    ArXive login and stuff checking
    @param uid: the user ID to check permissions for
    @param action: in ['claim_own_paper','claim_other_paper']

    @return: is user allowed to perform action?
    @rtype: boolean
    '''
    #If no EXTERNAL_CLAIMED_RECORDS_KEY we bypass this check
    if not bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        return True

    uinfo = collect_user_info(uid)
    keys = []
    for k in bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        if k in uinfo:
            keys.append(k)

    full_key = False
    for k in keys:
        if uinfo[k]:
            full_key = True
            break

    return full_key
Example #9
0
def lists(req, urlfieldvalue='', returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'], ln=CFG_SITE_LANG):
    """
    Display whitelist and blacklist
    @param urlFieldValue: value of the url input field
    @return_code: might indicate errors from a previous action, of CFG_WEBLINKBACK_ACTION_RETURN_CODE
    @param ln: language
    """
    # is passed as a string, must be an integer
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links +=' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    userInfo = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(userInfo, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    else:
        return page(title=_("Linkback Whitelist/Blacklist Manager"),
                    body=perform_request_display_list(return_code=return_code, url_field_value=urlfieldvalue, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    req=req)
Example #10
0
    def getattachedfile(self, req, form):
        """
        Returns a file uploaded to the submission 'drop box' by the
        CKEditor.
        """
        argd = wash_urlargd(form, {
            'file': (str, None),
            'type': (str, None),
            'uid': (int, 0)
        })

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)

        if not argd['file'] is None:
            # Prepare path to file on disk. Normalize the path so that
            # ../ and other dangerous components are removed.
            path = os.path.abspath(CFG_PREFIX + '/var/tmp/attachfile/' + \
                                   '/'  + str(argd['uid']) + \
                                   '/' + argd['type'] + '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith(CFG_PREFIX + '/var/tmp/attachfile/'
                               ) and os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        return (apache.HTTP_NOT_FOUND)
    def getattachedfile(self, req, form):
        """
        Returns a file uploaded to the submission 'drop box' by the
        CKEditor.
        """
        argd = wash_urlargd(form, {"file": (str, None), "type": (str, None), "uid": (int, 0)})

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)

        if not argd["file"] is None:
            # Prepare path to file on disk. Normalize the path so that
            # ../ and other dangerous components are removed.
            path = os.path.abspath(
                CFG_PREFIX + "/var/tmp/attachfile/" + "/" + str(argd["uid"]) + "/" + argd["type"] + "/" + argd["file"]
            )

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith(CFG_PREFIX + "/var/tmp/attachfile/") and os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        return apache.HTTP_NOT_FOUND
    def search_type_distribution(self, req, form):
        """Search type distribution statistics page."""
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        argd = wash_urlargd(form, {'timespan': (str, "today"),
                                   'format': (str, SUITABLE_GRAPH_FORMAT),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link':(ln != CFG_SITE_LANG and '?ln='+ln) or ''},
                text=auth_msg,
                navmenuid='search type distribution',
                ln=ln)

        return page(title="Search type distribution",
                    body=perform_display_keyevent('search type distribution', argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln='+ln) or ''),
                    description="CDS, Statistics, Search type distribution",
                    keywords="CDS, statistics, search type distribution",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='search type distribution',
                    language=ln)
    def customevent(self, req, form):
        """Custom event statistics page"""
        arg_format = {'ids': (list, []),
                     'timespan': (str, "today"),
                     'format': (str, SUITABLE_GRAPH_FORMAT),
                     'ln': (str, CFG_SITE_LANG)}
        for key in form.keys():
            if key[:4] == 'cols':
                i = key[4:]
                arg_format['cols'+i]=(list, [])
                arg_format['col_value'+i]=(list, [])
                arg_format['bool'+i]=(list, [])
        argd = wash_urlargd(form, arg_format)

        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link':(ln != CFG_SITE_LANG and '?ln='+ln) or ''},
                text=auth_msg,
                navmenuid='custom event',
                ln=ln)

        body = perform_display_customevent(argd['ids'], argd, req=req, ln=ln)
        return page(title="Custom event",
                    body=body,
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln='+ln) or ''),
                    description="CDS Personalize, Statistics, Custom event",
                    keywords="CDS, statistics, custom event",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='custom event',
                    language=ln)
    def custom_summary(self, req, form):
        """Custom report page"""
        argd = wash_urlargd(form, {'query': (str, ""),
                                   'tag': (str, CFG_JOURNAL_TAG.replace("%", "p")),
                                   'title': (str, "Publications"),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='custom query summary',
                ln=ln)

        return page(title="Custom query summary",
                    body=perform_display_custom_summary(argd, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Custom Query Summary",
                    keywords="CDS, statistics, custom query summary",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='custom query summary',
                    language=ln)
    def export(self, req, form):
        """Exports data"""
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='export',
                ln=ln)

        argd = wash_urlargd(form, {"filename": (str, ""),
                                   "mime": (str, "")})

        # Check that the particular file exists and that it's OK to export
        webstat_files = [x for x in os.listdir(CFG_TMPDIR) if x.startswith("webstat")]
        if argd["filename"] not in webstat_files:
            return "Bad file."

        # Set correct header type
        req.content_type = argd["mime"]
        req.send_http_header()

        # Rebuild path, send it to the user, and clean up.
        filename = CFG_TMPDIR + '/' + argd["filename"]
        req.sendfile(filename)
        os.remove(filename)
Example #16
0
def is_external_user(uid):
    '''
    Check for SSO user and if external claims will affect the
    decision wether or not the user may use the Invenio claiming platform

    @param uid: the user ID to check permissions for
    @type uid: int

    @return: is user allowed to perform actions?
    @rtype: boolean
    '''
    #If no EXTERNAL_CLAIMED_RECORDS_KEY we bypass this check
    if not bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        return False

    uinfo = collect_user_info(uid)
    keys = []
    for k in bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        if k in uinfo:
            keys.append(k)

    full_key = False
    for k in keys:
        if uinfo[k]:
            full_key = True
            break

    return full_key
    def user_lists(self, req, form):
        """Number of loans lists page."""
        argd = wash_urlargd(
            form, {
                'user_address': (str, ""),
                'timespan': (str, "today"),
                's_date': (str, ""),
                'f_date': (str, ""),
                'format': (str, SUITABLE_GRAPH_FORMAT),
                'ln': (str, CFG_SITE_LANG)
            })
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info,
                                                     'runwebstatadmin')
        if auth_code:
            return page_not_authorized(
                req,
                navtrail=self.navtrail %
                {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='user lists',
                ln=ln)

        return page(title="Users lists",
                    body=perform_display_keyevent('user lists', argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Users lists",
                    keywords="CDS, statistics, Users lists",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='user lists',
                    language=ln)
def acc_authorize_action(req, name_action, authorized_if_no_roles=False, **arguments):
    """
    Given the request object (or the user_info dictionary, or the uid), checks
    if the user is allowed to run name_action with the given parameters.
    If authorized_if_no_roles is True and no role exists (different
    than superadmin) that are authorized to execute the given action, the
    authorization will be granted.
    Returns (0, msg) when the authorization is granted, (1, msg) when it's not.
    """
    user_info = collect_user_info(req)
    roles = acc_find_possible_roles(name_action, always_add_superadmin=False, **arguments)
    for id_role in roles:
        if acc_is_user_in_role(user_info, id_role):
            ## User belong to at least one authorized role.
            return (0, CFG_WEBACCESS_WARNING_MSGS[0])
    if acc_is_user_in_role(user_info, CFG_SUPERADMINROLE_ID):
        ## User is SUPERADMIN
        return (0, CFG_WEBACCESS_WARNING_MSGS[0])
    if not roles:
        ## No role is authorized for the given action/arguments
        if authorized_if_no_roles:
            ## User is authorized because no authorization exists for the given
            ## action/arguments
            return (0, CFG_WEBACCESS_WARNING_MSGS[0])
        else:
            ## User is not authorized.
            return (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action))
    ## User is not authorized
    in_a_web_request_p = bool(user_info['uri'])
    return (1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info['uri']), CFG_WEBACCESS_MSGS[1]) or "")))
def metadata_upload(req,
                    metafile=None,
                    mode=None,
                    exec_date=None,
                    exec_time=None,
                    metafilename=None,
                    ln=CFG_SITE_LANG):
    """
    Metadata web upload service. Get upload parameters and exec bibupload for the given file.
    Finally, write upload history.
    @return: tuple (error code, message)
        error code: code that indicates if an error ocurred
        message: message describing the error
    """
    # start output:
    req.content_type = "text/html"
    req.send_http_header()

    # write temporary file:
    metafile = metafile.value
    user_info = collect_user_info(req)
    (fd, filename) = tempfile.mkstemp(prefix="batchupload_" + \
        user_info['nickname'] + "_" + time.strftime("%Y%m%d%H%M%S",
        time.localtime()) + "_" + metafilename + "_",
        dir=CFG_TMPDIR)
    filedesc = os.fdopen(fd, 'w')
    filedesc.write(metafile)
    filedesc.close()

    # check if this client can run this file:
    allow = _check_client_can_submit_file(req=req,
                                          metafile=metafile,
                                          webupload=1,
                                          ln=ln)
    if allow[0] != 0:
        return (allow[0], allow[1])

    # run upload command:
    if exec_date:
        date = "\'" + exec_date + ' ' + exec_time + "\'"
        jobid = task_low_level_submission('bibupload', user_info['nickname'],
                                          mode, "--name=" + metafilename, "-t",
                                          date, filename)
    else:
        jobid = task_low_level_submission('bibupload', user_info['nickname'],
                                          mode, "--name=" + metafilename,
                                          filename)

    # write batch upload history
    run_sql(
        """INSERT INTO hstBATCHUPLOAD (user, submitdate,
            filename, execdate, id_schTASK, batch_mode)
            VALUES (%s, NOW(), %s, %s, %s, "metadata")""", (
            user_info['nickname'],
            metafilename,
            exec_date != "" and (exec_date + ' ' + exec_time)
            or time.strftime("%Y-%m-%d %H:%M:%S"),
            str(jobid),
        ))
    return (0, "Task %s queued" % str(jobid))
    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 = "/youraccount/login" + make_canonical_urlargd(
                {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_URL + user_info["uri"]}, {}
            )
            return redirect_to_url(req, target, norobot=True)

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/record/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_URL,
            self.recid,
            str(-success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
Example #21
0
def index(req):
    user_info = collect_user_info(req)
    if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")):
        return page_not_authorized(req=req)

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

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

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

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

    req.write(pagefooteronly(req=req))
    return ""
Example #22
0
    def customevent_help(self, req, form):
        """Custom event help page"""
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info,
                                                     'runwebstatadmin')
        if auth_code:
            return page_not_authorized(
                req,
                navtrail=self.navtrail %
                {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='custom event help',
                ln=ln)

        return page(title="Custom event help",
                    body=perform_display_customevent_help(ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln='+ln) or ''),
                    description="CDS Personalize, Statistics, Custom event help",
                    keywords="CDS, statistics, custom event help",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='custom event help',
                    language=ln)
Example #23
0
    def search_type_distribution(self, req, form):
        """Search type distribution statistics page."""
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info,
                                                     'runwebstatadmin')
        argd = wash_urlargd(
            form, {
                'timespan': (str, "today"),
                'format': (str, SUITABLE_GRAPH_FORMAT),
                'ln': (str, CFG_SITE_LANG)
            })
        ln = argd['ln']
        if auth_code:
            return page_not_authorized(
                req,
                navtrail=self.navtrail %
                {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='search type distribution',
                ln=ln)

        return page(title="Search type distribution",
                    body=perform_display_keyevent('search type distribution', argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln='+ln) or ''),
                    description="CDS, Statistics, Search type distribution",
                    keywords="CDS, statistics, search type distribution",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='search type distribution',
                    language=ln)
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)
    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)
    def authorships(self, req, form):
        """
        Return list of authors used for auto-completion
        in the authors field.

        Return response as JSON.
        """
        argd = wash_urlargd(form, {
            'publicationid': (str, ''),
            'term': (str, '')
        })
        user_info = collect_user_info(req)
        uid = user_info['uid']
        req.content_type = 'application/json'
        term = argd['term']
        publicationid = argd['publicationid']
        ret = get_favourite_authorships_for_user(uid, publicationid, term)
        if ret:
            return json.dumps(ret)
        if ':' in term:
            ## an institution is being typed
            name, institute = term.split(':', 1)
            institute = institute.strip()
            if len(institute) > 1:
                institutes = [
                    row[0] for row in get_kbr_keys(
                        'institutes', searchkey=institute, searchtype='s')
                ]
                institutes.sort()
                return json.dumps([
                    "%s: %s" % (name, institute)
                    for institute in institutes[:100]
                ])
        return json.dumps([])
Example #27
0
def _upload_file_with_bibupload(file_path, upload_mode, num_records, req):
    """
    Uploads file with bibupload

       @param file_path: path to the file where the XML will be saved.
       @param upload_mode: -c for correct or -r for replace
       @return tuple formed by status of the upload:
           0-changes to be made instantly
           1-changes to be made only in limited hours
           2-user is superadmin. Changes made in limited hours
           3-no rights to upload
           and the upload file path
    """
    if num_records < CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING:
        task_low_level_submission('bibupload', 'multiedit', '-P', '5',
                                  upload_mode, '%s' % file_path)
        return (0, file_path)
    elif num_records < CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING:
        task_low_level_submission(
            'bibupload', 'multiedit', '-P', '5', upload_mode, '-L',
            CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME, '%s' % file_path)
        return (1, file_path)
    else:
        user_info = collect_user_info(req)
        if isUserSuperAdmin(user_info):
            task_low_level_submission(
                'bibupload', 'multiedit', '-P', '5', upload_mode, '-L',
                CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME,
                '%s' % file_path)
            return (2, file_path)
        return (3, file_path)
    def ill_requests_graph(self, req, form):
        """Percentage of satisfied ILL requests graph page."""
        argd = wash_urlargd(form, {'user_address': (str, ""),
                                   'doctype': (str, ""),
                                   'status': (str, ""),
                                   'supplier': (str, ""),
                                   'timespan': (str, "today"),
                                   's_date': (str, ""),
                                   'f_date': (str, ""),
                                   'format': (str, SUITABLE_GRAPH_FORMAT),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='percentage satisfied ill requests',
                ln=ln)

        return page(title="Percentage of satisfied ILL requests",
                    body=perform_display_keyevent('percentage satisfied ill requests',
                                                  argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Percentage of satisfied ILL requests",
                    keywords="CDS, statistics, Percentage of satisfied ILL requests",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='percentage satisfied ill requests',
                    language=ln)
    def authorships(self, req, form):
        """
        Return list of authors used for auto-completion
        in the authors field.

        Return response as JSON.
        """
        argd = wash_urlargd(
            form, {'publicationid': (str, ''), 'term': (str, '')})
        user_info = collect_user_info(req)
        uid = user_info['uid']
        req.content_type = 'application/json'
        term = argd['term']
        publicationid = argd['publicationid']
        ret = get_favourite_authorships_for_user(uid, publicationid, term)
        if ret:
            return json.dumps(ret)
        if ':' in term:
            ## an institution is being typed
            name, institute = term.split(':', 1)
            institute = institute.strip()
            if len(institute) > 1:
                institutes = [row[0] for row in get_kbr_keys(
                    'institutes', searchkey=institute, searchtype='s')]
                institutes.sort()
                return json.dumps(["%s: %s" % (name, institute) for institute in institutes[:100]])
        return json.dumps([])
    def items_list(self, req, form):
        """Number of loans lists page."""
        argd = wash_urlargd(form, {'library': (str, ""),
                                   'status': (str, ""),
                                   'format': (str, ""),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='items list',
                ln=ln)

        return page(title="Items list",
                    body=perform_display_keyevent('items list', argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Items list",
                    keywords="CDS, statistics, Items list",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='items list',
                    language=ln)
    def export(self, req, form):
        """Exports data"""
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info,
                                                     'runwebstatadmin')
        if auth_code:
            return page_not_authorized(
                req,
                navtrail=self.navtrail %
                {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='export',
                ln=ln)

        argd = wash_urlargd(form, {"filename": (str, ""), "mime": (str, "")})

        # Check that the particular file exists and that it's OK to export
        webstat_files = [
            x for x in os.listdir(CFG_TMPDIR) if x.startswith("webstat")
        ]
        if argd["filename"] not in webstat_files:
            return "Bad file."

        # Set correct header type
        req.content_type = argd["mime"]
        req.send_http_header()

        # Rebuild path, send it to the user, and clean up.
        filename = CFG_TMPDIR + '/' + argd["filename"]
        req.sendfile(filename)
        os.remove(filename)
Example #32
0
def get_pretty_wide_client_info(req):
    """Return in a pretty way all the avilable information about the current
    user/client"""
    if req:
        from invenio.webuser import collect_user_info

        user_info = collect_user_info(req)
        keys = user_info.keys()
        keys.sort()
        max_key = max([len(key) for key in keys])
        ret = ""
        fmt = "%% %is: %%s\n" % max_key
        for key in keys:
            if RE_PWD.search(key):
                continue
            if key in ("uri", "referer"):
                ret += fmt % (key, "<%s>" % user_info[key])
            else:
                ret += fmt % (key, user_info[key])
        if ret.endswith("\n"):
            return ret[:-1]
        else:
            return ret
    else:
        return "No client information available"
Example #33
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 #34
0
def perform_info(req, ln):
    """Display the main features of CDS personalize"""
    out = ""
    uid = getUid(req)

    user_info = collect_user_info(req)
    return websession_templates.tmpl_account_info(ln=ln, uid=uid, guest=isGuestUser(uid), CFG_CERN_SITE=CFG_CERN_SITE)
    def collections(self, req, form):
        """Collections statistics page"""
        argd = wash_urlargd(form, {'collection': (str, "All"),
                                   'timespan': (str, "this month"),
                                   's_date': (str, ""),
                                   'f_date': (str, ""),
                                   'format': (str, "flot"),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                navmenuid='collections',
                text=auth_msg,
                ln=ln)

        if collection_restricted_p(argd['collection']):
            (auth_code_coll, auth_msg_coll) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=argd['collection'])
            if auth_code_coll:
                return page_not_authorized(req,
                                           navmenuid='collections',
                                           text=auth_msg_coll,
                                           ln=ln)
        return page(title="Statistics of %s" % argd['collection'],
                    body=perform_display_stats_per_coll(argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Collection %s" % argd['collection'],
                    keywords="CDS, statistics, %s" % argd['collection'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='collections',
                    language=ln)
    def user_lists(self, req, form):
        """Number of loans lists page."""
        argd = wash_urlargd(form, {'timespan': (str, "today"),
                                   's_date': (str, ""),
                                   'f_date': (str, ""),
                                   'format': (str, SUITABLE_GRAPH_FORMAT),
                                   'sql': (int, 0),
                                   'ln': (str, CFG_SITE_LANG)})
        ln = argd['ln']
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = acc_authorize_action(user_info, 'runwebstatadmin')
        if auth_code:
            return page_not_authorized(req,
                navtrail=self.navtrail % {'ln_link': (ln != CFG_SITE_LANG and '?ln=' + ln) or ''},
                text=auth_msg,
                navmenuid='circulation users lists',
                ln=ln)

        return page(title="Circulation users lists",
                    body=perform_display_keyevent('user lists', argd, req, ln=ln),
                    navtrail="""<a class="navtrail" href="%s/stats/%s">Statistics</a>""" % \
                    (CFG_SITE_URL, (ln != CFG_SITE_LANG and '?ln=' + ln) or ''),
                    description="CDS, Statistics, Circulation users lists",
                    keywords="CDS, statistics, Circulation users lists",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='circulation users lists',
                    language=ln)
Example #37
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, err:
                    register_exception(req=req, alert_admin=True)
                    raise SERVER_RETURN(HTTP_NOT_FOUND)
    def test_check_bibdoc_authorization(self):
        """bibdocfile - check_bibdoc_authorization function"""
        from invenio.webuser import collect_user_info, get_uid_from_email
        jekyll = collect_user_info(get_uid_from_email('*****@*****.**'))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role:thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role:  thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertNotEqual(check_bibdoc_authorization(jekyll, 'Role:  thesesviewer')[0], 0)
        self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))

        juliet = collect_user_info(get_uid_from_email('*****@*****.**'))
        self.assertEqual(check_bibdoc_authorization(juliet, 'restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(juliet, 'status: restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertNotEqual(check_bibdoc_authorization(juliet, 'restricted_video')[0], 0)
        self.assertNotEqual(check_bibdoc_authorization(juliet, 'status: restricted_video')[0], 0)
    def authorships(self, req, form):
        """
        Return list of authors used for auto-completion
        in the authors field.

        Return response as JSON.
        """
        argd = wash_urlargd(form, {"publicationid": (str, ""), "term": (str, "")})
        user_info = collect_user_info(req)
        uid = user_info["uid"]
        req.content_type = "application/json"
        term = argd["term"]
        publicationid = argd["publicationid"]
        ret = get_favourite_authorships_for_user(uid, publicationid, term)
        if ret:
            return json.dumps(ret)
        if ":" in term:
            ## an institution is being typed
            name, institute = term.split(":", 1)
            institute = institute.strip()
            if len(institute) > 1:
                institutes = [row[0] for row in get_kbr_keys("institutes", searchkey=institute, searchtype="s")]
                institutes.sort()
                return json.dumps(["%s: %s" % (name, institute) for institute in institutes[:100]])
        return json.dumps([])
def is_external_user(uid):
    '''
    Check for SSO user and if external claims will affect the
    decision wether or not the user may use the Invenio claiming platform

    @param uid: the user ID to check permissions for
    @type uid: int

    @return: is user allowed to perform actions?
    @rtype: boolean
    '''
    #If no EXTERNAL_CLAIMED_RECORDS_KEY we bypass this check
    if not bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        return False

    uinfo = collect_user_info(uid)
    keys = []
    for k in bconfig.EXTERNAL_CLAIMED_RECORDS_KEY:
        if k in uinfo:
            keys.append(k)

    full_key = False
    for k in keys:
        if uinfo[k]:
            full_key = True
            break

    return full_key
def _upload_file_with_bibupload(file_path, upload_mode, num_records, req):
    """
    Uploads file with bibupload

       @param file_path: path to the file where the XML will be saved.
       @param upload_mode: -c for correct or -r for replace
       @return tuple formed by status of the upload:
           0-changes to be made instantly
           1-changes to be made only in limited hours
           2-user is superadmin. Changes made in limited hours
           3-no rights to upload
           and the upload file path
    """
    if num_records < CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING:
        task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '%s' % file_path)
        return (0, file_path)
    elif num_records < CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING:
        task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '-L', CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME,'%s' % file_path)
        return (1, file_path)
    else:
        user_info = collect_user_info(req)
        if isUserSuperAdmin(user_info):
            task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '-L', CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME, '%s' % file_path)
            return (2, file_path)
        return (3, file_path)
def check_login(req):
    """Check that the user is logged in"""
    user_info = collect_user_info(req)
    if user_info['email'] == 'guest':
        # 1. User is guest: must login prior to upload
        # return 'Please login before uploading file.'
        pass
    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 = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_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/record/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_URL, self.recid, str(success), argd['ln'])
        redirect_to_url(req, display_url)
Example #44
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)
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)
    def write(self, req, form):
        """ write(): interface for message composing
        @param msg_reply_id: if this message is a reply to another, id of the
                             other
        @param msg_to: if this message is not a reply, nickname of the user it
                       must be delivered to.
        @param msg_to_group: name of group to send message to
        @param ln: language
        @return: the compose page
        """
        argd = wash_urlargd(form, {'msg_reply_id': (int, 0),
                                   'msg_to': (str, ""),
                                   'msg_to_group': (str, ""),
                                   'msg_subject' : (str, ""),
                                   'msg_body' : (str, "")})

        # Check if user is logged
        uid = getUid(req)

        _ = gettext_set_language(argd['ln'])

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

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

        # Request the composing page
        body = perform_request_write(
                                     uid=uid,
                                     msg_reply_id=argd['msg_reply_id'],
                                     msg_to=argd['msg_to'],
                                     msg_to_group=argd['msg_to_group'],
                                     msg_subject=argd['msg_subject'],
                                     msg_body=argd['msg_body'],
                                     ln=argd['ln'])
        title = _("Write a message")

        return page(title       = title,
                    body        = body,
                    navtrail    = get_navtrail(argd['ln'], title),
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)
Example #47
0
    def test_check_bibdoc_authorization(self):
        """bibdocfile - check_bibdoc_authorization function"""
        from invenio.bibdocfile import check_bibdoc_authorization
        from invenio.webuser import collect_user_info, get_uid_from_email
        jekyll = collect_user_info(get_uid_from_email('*****@*****.**'))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role:thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'role:  thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'Role:  thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))

        juliet = collect_user_info(get_uid_from_email('*****@*****.**'))
        self.assertEqual(check_bibdoc_authorization(juliet, 'restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertEqual(check_bibdoc_authorization(juliet, 'status: restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0]))
        self.assertNotEqual(check_bibdoc_authorization(juliet, 'restricted_video')[0], 0)
        self.assertNotEqual(check_bibdoc_authorization(juliet, 'status: restricted_video')[0], 0)
Example #48
0
def perform_display_account(req, username, bask, aler, sear, msgs, loan, grps, sbms, appr, admn, ln):
    """Display a dynamic page that shows the user's account."""

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

    uid = getUid(req)
    user_info = collect_user_info(req)
    #your account
    if isGuestUser(uid):
        user = "******"
        login = "******" % (CFG_SITE_SECURE_URL, ln)
        accBody = _("You are logged in as guest. You may want to %(x_url_open)slogin%(x_url_close)s as a regular user.") %\
            {'x_url_open': '<a href="' + login + '">',
             'x_url_close': '</a>'}
        accBody += "<br /><br />"
        bask=aler=msgs= _("The %(x_fmt_open)sguest%(x_fmt_close)s users need to %(x_url_open)sregister%(x_url_close)s first") %\
            {'x_fmt_open': '<strong class="headline">',
             'x_fmt_close': '</strong>',
             'x_url_open': '<a href="' + login + '">',
             'x_url_close': '</a>'}
        sear= _("No queries found")
    else:
        user = username
        accBody = websession_templates.tmpl_account_body(
                    ln = ln,
                    user = user,
                  )

    #Display warnings if user is superuser
    roles = acc_find_user_role_actions(user_info)
    warnings = "0"
    for role in roles:
        if "superadmin" in role:
            warnings = "1"
            break

    warning_list = superuser_account_warnings()

    #check if tickets ok
    tickets = (acc_authorize_action(user_info, 'runbibedit')[0] == 0)

    return websession_templates.tmpl_account_page(
             ln = ln,
             warnings = warnings,
             warning_list = warning_list,
             accBody = accBody,
             baskets = bask,
             alerts = aler,
             searches = sear,
             messages = msgs,
             loans = loan,
             groups = grps,
             submissions = sbms,
             approvals = appr,
             tickets = tickets,
             administrative = admn
           )
Example #49
0
    def report(self, req, form):
        """
        Report a comment/review for inappropriate content
        @param comid: comment/review id
        @param recid: the id of the record the comment/review is associated with
        @param ln: language
        @param do: display order    hh = highest helpful score, review only
                                    lh = lowest helpful score, review only
                                    hs = highest star score, review only
                                    ls = lowest star score, review only
                                    od = oldest date
                                    nd = newest date
        @param ds: display since    all= no filtering by date
                                    nd = n days ago
                                    nw = n weeks ago
                                    nm = n months ago
                                    ny = n years ago
                                    where n is a single digit integer between 0 and 9
        @param nb: number of results per page
        @param p: results page
        @param referer: http address of the calling function to redirect to (refresh)
        @param reviews: boolean, enabled for reviews, disabled for comments
        """

        argd = wash_urlargd(form, {'comid': (int, -1),
                                   'recid': (int, -1),
                                   'do': (str, "od"),
                                   'ds': (str, "all"),
                                   'nb': (int, 100),
                                   'p': (int, 1),
                                   'referer': (str, None)
                                   })

        client_ip_address = req.remote_ip
        uid = getUid(req)

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

        success = perform_request_report(argd['comid'], client_ip_address, uid)
        if argd['referer']:
            argd['referer'] += "?ln=%s&amp;do=%s&amp;ds=%s&amp;nb=%s&amp;p=%s&amp;reported=%s&amp;" % (argd['ln'], argd['do'], argd['ds'], argd['nb'], argd['p'], str(success))

            redirect_to_url(req, argd['referer'])
        else:
            #Note: sent to comments display
            referer = "%s/%s/%s/%s/display?ln=%s&amp;voted=1"
            referer %= (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, self.discussion==1 and 'reviews' or 'comments', argd['ln'])
            redirect_to_url(req, referer)
        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)
Example #51
0
def _check_client_can_submit_file(client_ip="",
                                  metafile="",
                                  req=None,
                                  webupload=0,
                                  ln=CFG_SITE_LANG):
    """
    Is this client able to upload such a FILENAME?
    check 980 $a values and collection tags in the file to see if they are among the
    permitted ones as specified by CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS and ACC_AUTHORIZE_ACTION.
    Useful to make sure that the client does not override other records by
    mistake.
    """
    _ = gettext_set_language(ln)
    recs = create_records(metafile, 0, 0)
    user_info = collect_user_info(req)

    permitted_dbcollids = _get_client_authorized_collections(client_ip)
    if '*' in permitted_dbcollids:
        if not webupload:
            return True
        else:
            return (0, " ")

    filename_tag980_values = _detect_980_values_from_marcxml_file(recs)
    for filename_tag980_value in filename_tag980_values:
        if not filename_tag980_value:
            if not webupload:
                return False
            else:
                return (1, "Invalid collection in tag 980")
        if not webupload:
            if not filename_tag980_value in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(
                req, 'runbatchuploader', collection=filename_tag980_value)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_tag980_value}
                return (auth_code, error_msg)

    filename_rec_id_collections = _detect_collections_from_marcxml_file(recs)

    for filename_rec_id_collection in filename_rec_id_collections:
        if not webupload:
            if not filename_rec_id_collection in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(
                req, 'runbatchuploader', collection=filename_rec_id_collection)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_rec_id_collection}
                return (auth_code, error_msg)
    if not webupload:
        return True
    else:
        return (0, " ")
 def test_search_Nucl_Phys_B75_1974_461_with_spaces(self):
     """websearch - search '  Nucl.  Phys.   B75   (1974)  461   ', with JournalHintService"""
     user_info = collect_user_info(1)
     pattern = '  Nucl.  Phys.   B75   (1974)  461   '
     search_units = create_basic_search_units(None, pattern, '')
     response = self.plugin.answer(req=user_info, user_info=user_info, of='hb',
                                   cc=CFG_SITE_NAME, colls_to_search='', p=pattern,
                                   f='', search_units=search_units, ln='en')
     self.assertEqual(response, (0, ''))
 def test_search_D_S_Salopek_J_R_Bond_and_J_M_Bardeen_Phys_Rev_D40_1989_1753(self):
     """websearch - search 'D.S. Salopek, J.R.Bond and J.M.Bardeen,Phys.Rev.D40(1989)1753.', with JournalHintService"""
     user_info = collect_user_info(1)
     pattern = 'D.S. Salopek, J.R.Bond and J.M.Bardeen,Phys.Rev.D40(1989)1753.'
     search_units = create_basic_search_units(None, pattern, '')
     response = self.plugin.answer(req=user_info, user_info=user_info, of='hb',
                                   cc=CFG_SITE_NAME, colls_to_search='', p=pattern,
                                   f='', search_units=search_units, ln='en')
     self.assertEqual(response, (0, ''))
 def setUp(self):
     """setting up helper variables for tests"""
     self.user_info = {
         'email': '*****@*****.**',
         'uid': 1000,
         'group': ['patata', 'cetriolo'],
         'remote_ip': '127.0.0.1'
     }
     self.guest = collect_user_info({})
    def manage(self, req, form):
        """ Web interface for the management of the info space """
        uid = getUid(req)
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})

        # If it is an Ajax request, extract any JSON data.
        ajax_request = False
        if 'jsondata' in form:
            json_data = json.loads(str(form['jsondata']))
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}

        # Authorization.
        user_info = collect_user_info(req)
        if user_info['email'] == 'guest':
            # User is not logged in.
            if not ajax_request:
                # Do not display the introductory recID selection box to guest
                # users (as it used to be with v0.99.0):
                dummy_auth_code, auth_message = acc_authorize_action(
                    req, 'runinfomanager')
                referer = '/info'
                return page_not_authorized(req=req,
                                           referer=referer,
                                           text=auth_message)
            else:
                # Session has most likely timed out.
                json_response.update({'status': "timeout"})
                return json.dumps(json_response)
        # Handle request.
        if not ajax_request:
            body, errors, warnings = perform_request_init_info_interface()
            title = 'Info Space Manager'
            return page(title=title,
                        body=body,
                        errors=errors,
                        warnings=warnings,
                        uid=uid,
                        language=argd['ln'],
                        req=req)
        else:
            # Handle AJAX request.
            if json_data["action"] == "listFiles":
                json_response.update(
                    perform_request_edit_file(json_data["filename"]))
                try:
                    return json.dumps(json_response)
                except UnicodeDecodeError:
                    # Error decoding, the file can be a pdf, image or any kind
                    # of file non-editable
                    return json.dumps({"status": "error_file_not_readable"})

            if json_data["action"] == "saveContent":
                return json.dumps(
                    perform_request_save_file(json_data["filename"],
                                              json_data["filecontent"]))
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)