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)
Example #2
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 __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)
        user_info = collect_user_info(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 not form.has_key('rg'):
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        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

        record_primary_collection = guess_primary_collection_of_a_record(self.recid)

        if collection_restricted_p(record_primary_collection):
            (auth_code, dummy) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=record_primary_collection)
            if auth_code:
                return page_not_authorized(req, "../",
                    text="You are not authorized to view this record.",
                    navmenuid='search')

        # Keep all the arguments, they might be reused in the
        # record page itself to derivate other queries
        req.argd = argd

        # 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
    def managedocfilesasync(self, req, form):
        "Upload file and returns upload interface"

        argd = wash_urlargd(
            form, {"ln": (str, ""), "recid": (int, 1), "doctype": (str, ""), "access": (str, ""), "indir": (str, "")}
        )

        user_info = collect_user_info(req)
        include_headers = False
        # User submitted either through WebSubmit, or admin interface.
        if form.has_key("doctype") and form.has_key("indir") and form.has_key("access"):
            # Submitted through WebSubmit. Check rights
            include_headers = True
            working_dir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, argd["indir"], argd["doctype"], argd["access"])
            try:
                assert working_dir == os.path.abspath(working_dir)
            except AssertionError:
                return apache.HTTP_UNAUTHORIZED
            try:
                # Retrieve recid from working_dir, safer.
                recid_fd = file(os.path.join(working_dir, "SN"))
                recid = int(recid_fd.read())
                recid_fd.close()
            except:
                recid = ""
            try:
                act_fd = file(os.path.join(working_dir, "act"))
                action = act_fd.read()
                act_fd.close()
            except:
                action = ""

            # Is user authorized to perform this action?
            (auth_code, auth_msg) = acc_authorize_action(user_info, "submit", doctype=argd["doctype"], act=action)
            if not acc_is_role("submit", doctype=argd["doctype"], act=action):
                # There is NO authorization plugged. User should have access
                auth_code = 0
        else:
            # User must be allowed to attach files
            (auth_code, auth_msg) = acc_authorize_action(user_info, "runbibdocfile")
            recid = argd["recid"]

        if auth_code:
            return apache.HTTP_UNAUTHORIZED

        return create_file_upload_interface(
            recid=recid,
            ln=argd["ln"],
            print_outside_form_tag=False,
            print_envelope=False,
            form=form,
            include_headers=include_headers,
            sbm_indir=argd["indir"],
            sbm_access=argd["access"],
            sbm_doctype=argd["doctype"],
            uid=user_info["uid"],
        )[1]
    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 not form.has_key('rg'):
                    # 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
Example #6
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 not form.has_key('rg'):
                    # 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
Example #7
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)
        user_info = collect_user_info(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 not form.has_key('rg'):
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        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

        record_primary_collection = guess_primary_collection_of_a_record(self.recid)

        if collection_restricted_p(record_primary_collection):
            (auth_code, dummy) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=record_primary_collection)
            if auth_code:
                return page_not_authorized(req, "../",
                    text="You are not authorized to view this record.",
                    navmenuid='search')

        # Keep all the arguments, they might be reused in the
        # record page itself to derivate other queries
        req.argd = argd

        # 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
Example #8
0
    def authenticate(self, req, form):
        """Restricted search results pages."""

        argd = wash_search_urlargd(form)

        user_info = collect_user_info(req)
        for coll in argd['c'] + [argd['cc']]:
            if collection_restricted_p(coll):
                (auth_code, auth_msg) = acc_authorize_action(user_info,
                                                             VIEWRESTRCOLL,
                                                             collection=coll)
                if auth_code and user_info['email'] == 'guest':
                    cookie = mail_cookie_create_authorize_action(
                        VIEWRESTRCOLL, {'collection': coll})
                    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')

        #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):
            auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
            if auth_code != 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

        # Keep all the arguments, they might be reused in the
        # search_engine itself to derivate other queries
        req.argd = argd

        uid = getUid(req)
        if uid > 0:
            pref = get_user_preferences(uid)
            try:
                if not form.has_key('rg'):
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        # 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
Example #9
0
    def authenticate(self, req, form):
        """Restricted search results pages."""

        argd = wash_search_urlargd(form)

        user_info = collect_user_info(req)
        for coll in argd['c'] + [argd['cc']]:
            if collection_restricted_p(coll):
                (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=coll)
                if auth_code and user_info['email'] == 'guest':
                    cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : coll})
                    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')

        #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):
            auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
            if auth_code != 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

        # Keep all the arguments, they might be reused in the
        # search_engine itself to derivate other queries
        req.argd = argd

        uid = getUid(req)
        if uid > 0:
            pref = get_user_preferences(uid)
            try:
                if not form.has_key('rg'):
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass


        # 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
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 user_authorization(req):
    """ Check user authorization to visit page """
    user_info = collect_user_info(req)
    if user_info['email'] == 'guest':
        auth_code, auth_message = acc_authorize_action(req, 'runbatchuploader')
        referer = '/batchuploader/'
        return page_not_authorized(req=req, referer=referer,
                                   text=auth_message, navmenuid="batchuploader")
    else:
        auth_code, auth_message = acc_authorize_action(req, 'runbatchuploader')
        if auth_code != 0:
            referer = '/batchuploader/'
            return page_not_authorized(req=req, referer=referer,
                                       text=auth_message, navmenuid="batchuploader")
Example #12
0
def index(req, p=""):
    auth_code, auth_message = acc_authorize_action(req, 'runsearchuser')
    if auth_code != 0:
        return page_not_authorized(req=req, text=auth_message)
    users = []
    if p:
        users = run_sql(
            "SELECT id, nickname, email, last_login FROM user WHERE email<>'' AND nickname LIKE %s OR email LIKE %s ORDER BY email LIMIT 100",
            ('%%%s%%' % p, '%%%s%%' % p))
    body = """
<form>
<label for="searchuser">Search user:</label> <input name="p" id="searchuser" value="%s" /></input><input type="submit" value="Search" />
</form>
""" % escape(p, True)
    if users:
        body += """<h2>Users found</h2>
<p>This is the list of the first 100 users found matching the criteria.</p>
<table border="1">
  <thead><tr><th>ID</th><th>Nickname</th><th>Email</th><th>Last login</th></tr></thead>
  <tbody>
"""
        for user in users:
            body += """<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>""" % (
                user[0], escape(user[1]), escape(user[2]), escape(str(
                    user[3])))
        body += """
  </tbody>
</table>
"""
    return page(req=req, title="Search users", body=body)
Example #13
0
def hot(req, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    View most active comments/reviews
    @param req: request object to obtain user information
    @param ln: language
    @param comments: boolean enabled for comments, disabled for reviews
    @param top: number of results to be shown
    @param collection: filter results by collection
    """
    ln = wash_language(ln)
    collection = wash_url_argument(collection, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgwebcomment')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    return page(title=(comments=='0' and _("View most reviewed records") or
                           _("View most commented records")),
                    body=perform_request_hot(req, ln=ln, comments=comments, top=top, collection=collection),
                    uid=user_info['uid'],
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
Example #14
0
def filter_hidden_fields(recxml, user_info=None, filter_tags=CFG_BIBFORMAT_HIDDEN_TAGS, force_filtering=False):
    """
    Filter out tags specified by filter_tags from MARCXML. If the user
    is allowed to run bibedit, then filter nothing, unless
    force_filtering is set to True.

    @param recxml: marcxml presentation of the record
    @param user_info: user information; if None, then assume invoked via CLI with all rights
    @param filter_tags: list of MARC tags to be filtered
    @param force_filtering: do we force filtering regardless of user rights?
    @return: recxml without the hidden fields
    """
    if force_filtering:
        pass
    else:
        if user_info is None:
            # by default
            return recxml
        else:
            if acc_authorize_action(user_info, "runbibedit")[0] == 0:
                # no need to filter
                return recxml
    # filter..
    out = ""
    omit = False
    for line in recxml.splitlines(True):
        # check if this block needs to be omitted
        for htag in filter_tags:
            if line.count('datafield tag="' + str(htag) + '"'):
                omit = True
        if not omit:
            out += line
        if omit and line.count("</datafield>"):
            omit = False
    return out
def generate_keywords(req, recid, argd):
    """Extracts keywords from the fulltexts (if found) for the
    given recid. It first checks whether the keywords are not already
    stored in the temp file (maybe from the previous run).
    @var req: req object
    @var recid: record id
    @var argd: arguments passed from web
    @keyword store_keywords: boolean, whether to save records in the file
    @return: standard dictionary of kw objects or {}
    """

    ln = argd['ln']
    _ = gettext_set_language(ln)
    keywords = {}

    # check the files were not already generated
    abs_path = bibclassify_engine.get_tmp_file(recid)
    if os.path.exists(abs_path):
        try:
            # Try to load the data from the tmp file
            recs = bibupload.xml_marc_to_records(bibupload.open_marc_file(abs_path))
            return record_get_keywords(recs[0])
        except:
            pass

    # check it is allowed (for this user) to generate pages
    (exit_stat, msg) = acce.acc_authorize_action(req, 'runbibclassify')
    if exit_stat != 0:
        log.info('Access denied: ' + msg)
        msg = _("The site settings do not allow automatic keyword extraction")
        req.write(template.tmpl_page_msg(msg=msg))
        return 0, keywords, None

    # register generation
    bibdocfiles = BibRecDocs(recid).list_latest_files()
    if bibdocfiles:
        # User arrived at a page, but no keywords are available
        inprogress, msg = _doc_already_submitted(recid)
        if argd['generate'] != 'yes':
            # Display a form and give them possibility to generate keywords
            if inprogress:
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' % _(msg)))
            else:
                req.write(template.tmpl_page_generate_keywords(req=req, **argd))
            return 0, keywords, None
        else: # after user clicked on "generate" button
            if inprogress:
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' % _(msg) ))
            else:
                schedule_extraction(recid, taxonomy=bconfig.CFG_EXTRACTION_TAXONOMY)
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' %
                                                 _('We have registered your request, the automated'
                'keyword extraction will run after some time. Please return back in a while.')))

    else:
        req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' %
                    _("Unfortunately, we don't have a PDF fulltext for this record in the storage, \
                    keywords cannot be generated using an automated process.")))

    return 0, keywords, None
def format(bfo, style):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    collection = guess_primary_collection_of_a_record(bfo.recID)
    (auth_code, auth_message) = acc_authorize_action(user_info, "runbibedit", collection=collection)
    if auth_code == 0:
        linkattrd = {}
        if style != "":
            linkattrd["style"] = style

        out += create_html_link(
            CFG_SITE_URL + "/record/" + str(bfo.recID) + "/edit/",
            urlargd={"ln": bfo.lang, "recid": str(bfo.recID)},
            link_label=_("Edit This Record"),
            linkattrd=linkattrd,
        )

    return out
Example #17
0
def format_element(bfo, style):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style

        out += create_html_link(CFG_BASE_URL +
                                '/%s/managedocfiles' % CFG_SITE_RECORD,
                                urlargd={
                                    'ln': bfo.lang,
                                    'recid': str(bfo.recID)
                                },
                                link_label=_("Manage Files of This Record"),
                                linkattrd=linkattrd)
    return out
    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 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)
Example #20
0
def Is_Referee(parameters, curdir, form, user_info=None):
    """
    This function checks whether the currently logged user is a
    referee for this document.
    """
    global uid_email,sysno,rn,uid
    doctype = form['doctype']
    # Get document category
    res = run_sql("SELECT categ FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(res) >0:
        categ = res[0][0]
        if categ == "unknown":
            ## FIXME: This was necessary for document types without categories,
            ## such as DEMOBOO:
            categ = "*"
    else:
        categ=""
    # Try to retrieve the referee's email from the referee's database
    (auth_code, auth_message) = acc_authorize_action(user_info, "referee",doctype=doctype, categ=categ)
    if auth_code != 0:
        raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
        document.forms[0].action="/submit";
        document.forms[0].curpage.value = 1;
        document.forms[0].step.value = 0;
        user_must_confirm_before_leaving_page = false;
        document.forms[0].submit();
        alert('Sorry you (%s) have not been recognized as a referee for this type of document.\\nIf you think this is an error, please contact %s');
</SCRIPT>""" % (uid_email,CFG_SITE_SUPPORT_EMAIL))
    return ""
    def decorated(*args, **kwargs):
        uid = current_user.get_id()
        name = name_getter()
        if name:
            collection = Collection.query.filter(
                Collection.name == name).first_or_404()
        elif default_collection:
            collection = Collection.query.get_or_404(1)
        else:
            return abort(404)

        if collection.is_restricted:
            (auth_code,
             auth_msg) = acc_authorize_action(uid,
                                              VIEWRESTRCOLL,
                                              collection=collection.name)
            if auth_code:
                flash(_('This collection is restricted.'), 'error')
            if auth_code and current_user.is_guest:
                return redirect(
                    url_for('webaccount.login', referer=request.url))
            elif auth_code:
                return abort(401)

        return method(collection, *args, **kwargs)
    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 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 user_can_view_CMP(uid):
    action = bconfig.CLAIMPAPER_VIEW_PID_UNIVERSE
    auth = acc_authorize_action(uid, action)
    if auth[0] == 0:
        return True
    else:
        return False
Example #25
0
def format_element(bfo, style):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style

        out += create_html_link(CFG_SITE_URL + '/submit/managedocfiles',
                         urlargd={'ln': bfo.lang,
                                  'recid': str(bfo.recID)},
                         link_label=_("Manage Files of This Record"),
                         linkattrd=linkattrd)
    return out
Example #26
0
def index(req,
          c=CFG_SITE_NAME,
          ln=CFG_SITE_LANG,
          order="",
          doctype="",
          deletedId="",
          deletedAction="",
          deletedDoctype=""):
    global uid
    ln = wash_language(ln)

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

    t = ""
    # get user ID:
    try:
        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,
                                       "../yoursubmissions.py/index",
                                       navmenuid='yoursubmissions',
                                       text=auth_message)
        u_email = get_email(uid)
    except Error, e:
        return error_page(str(e), req, ln=ln)
    def compare_revisions(self, req, form):
        """Handle the compare revisions request"""
        argd = wash_urlargd(form, { \
                'ln': (str, CFG_SITE_LANG), \
                'rev1' : (str, ''), \
                'rev2' : (str, ''), \
                'recid': (int, 0)})

        ln = argd['ln']
        uid = getUid(req)
        _ = gettext_set_language(ln)

        # Checking if currently logged user has permission to perform this request

        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)
        recid = argd['recid']
        rev1 = argd['rev1']
        rev2 = argd['rev2']
        ln = argd['ln']

        body, errors, warnings = perform_request_compare(ln, recid, rev1, rev2)

        return page(title = _("Comparing two record revisions"),
                    body =  body,
                    errors = errors,
                    warnings = warnings,
                    uid = uid,
                    language = ln,
                    navtrail    = navtrail,
                    lastupdated = __lastupdated__,
                    req         = req)
    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 #29
0
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    linkattrd = {}
    if style != '':
        linkattrd['style'] = style
    if css_class != '':
        linkattrd['class'] = css_class

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label,
                            linkattrd=linkattrd)
    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)
Example #31
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 loans_request_lists(self, req, form):
        """Number of loans request lists page."""
        argd = wash_urlargd(
            form, {
                'user_address': (str, ""),
                'udc': (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='loans request lists',
                ln=ln)

        return page(title="Loans request lists",
                    body=perform_display_keyevent('loans request 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, Loans  request lists",
                    keywords="CDS, statistics, Loans request lists",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='loans request lists',
                    language=ln)
Example #33
0
 def can_view_restricted_comment(self, restriction):
     #restriction =  self.comment.restriction
     if restriction == "":
         return (0, '')
     return acc_authorize_action(self.uid,
                                 'viewrestrcomment',
                                 status=restriction)
    def error_log(self, req, form):
        """Number of loans request lists 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='error log analyzer',
                ln=ln)

        return page(title="Error log analyzer",
                    body=perform_display_error_log_analyzer(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, Error log analyzer",
                    keywords="CDS, statistics, Error log analyzer",
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='error log analyzer',
                    language=ln)
Example #35
0
def format_element(bfo, style, css_class):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(CFG_SITE_URL + '/%s/managedocfiles' % CFG_SITE_RECORD,
                         urlargd={'ln': bfo.lang,
                                  'recid': str(bfo.recID)},
                         link_label= """<i class="icon-file"></i> %s""" % _("Manage Files"),
                         linkattrd=linkattrd)
    return out
    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)
    def custom_summary(self, req, form):
        """Custom report page"""
        argd = wash_urlargd(
            form, {
                'query': (str, ""),
                'tag': (str, "909C4p"),
                '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 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)
def Is_Original_Submitter(parameters, curdir, form, user_info=None):
    """
    This function compares the current logged in user email with the
    email of the original submitter of the record. If it is the same
    (or if the current user has superuser rights), we go on. If it
    differs, an error message is issued.
    """
    global uid_email,sysno,uid
    doctype = form['doctype']
    act = form['act']
    email = Get_Field("8560_f",sysno)
    email = re.sub("[\n\r ]+","",email)
    uid_email = re.sub("[\n\r ]+","",uid_email)
    (auth_code, auth_message) = acc_authorize_action(user_info, "submit",verbose=0,doctype=doctype, act=act)
    if re.search(uid_email,email,re.IGNORECASE) is None and auth_code != 0:
        raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
   document.forms[0].action="/submit";
   document.forms[0].curpage.value = 1;
   document.forms[0].step.value = 0;
   user_must_confirm_before_leaving_page = false;
   document.forms[0].submit();
   alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).');
</SCRIPT>""" % (uid_email,email))
    elif re.search(uid_email,email, re.IGNORECASE) is None and \
             auth_code == 0:
        if not os.path.exists(os.path.join(curdir, 'is_original_submitter_warning')):
            write_file(os.path.join(curdir, 'is_original_submitter_warning'), '')
            return ("""
<SCRIPT>
alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).\\n\\nAnyway, as you have a special authorization for this type of documents,\\nyou are allowed to proceed! Watch out your actions!');
</SCRIPT>""" % (uid_email,email))

    return ""
    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)
Example #41
0
def index(req, p=""):
    auth_code, auth_message = acc_authorize_action(req, 'runsearchuser')
    if auth_code != 0:
        return page_not_authorized(req=req, text=auth_message)
    users = []
    if p:
        users = run_sql(
            "SELECT id, nickname, email, last_login FROM user WHERE email<>'' AND nickname LIKE %s OR email LIKE %s OR id=%s ORDER BY email LIMIT 100", ('%%%s%%' % p, '%%%s%%' % p, p))
    body = """
<form>
<label for="searchuser">Search user:</label> <input name="p" id="searchuser" value="%s" /></input><input type="submit" value="Search" />
</form>
""" % escape(p, True)
    if users:
        body += """<h2>Users found</h2>
<p>This is the list of the first 100 users found matching the criteria.</p>
<table border="1">
  <thead><tr><th>ID</th><th>Nickname</th><th>Email</th><th>Last login</th><th>Profile info</th></tr></thead>
  <tbody>
"""
        for user in users:
            body += """<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>""" % (
                user[0], escape(user[1]), escape(user[2]), escape(str(user[3])), _get_personid_info(user[0]))
        body += """
  </tbody>
</table>
"""
    return page(req=req, title="Search users", body=body)
Example #42
0
def user_can_edit_record_collection(req, recid):
    """ Check if user has authorization to modify a collection
    the recid belongs to
    """
    record_collections = get_all_collections_of_a_record(recid)
    if not record_collections:
        # Check if user has access to all collections
        auth_code, auth_message = acc_authorize_action(req, "runbibedit", collection="")
        if auth_code == 0:
            return True
    else:
        for collection in record_collections:
            auth_code, auth_message = acc_authorize_action(req, "runbibedit", collection=collection)
            if auth_code == 0:
                return True
    return False
    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 = '/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'])
    def index(self, req, form):
        """ The function called by default"""

        argd = wash_urlargd(form, {
                                   self._JSON_DATA_KEY: (str, ""),
                                   })

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

        # check user credentials
        (auth_code, auth_msg) = acc_authorize_action(req, "runbibeditmulti")
        if 0 != auth_code:
            return page_not_authorized(req = req,
                                       ln = language,
                                       text = auth_msg)

        if argd[self._JSON_DATA_KEY]:
            return self._process_json_request(form, req)

        body = multi_edit_engine.perform_request_index(language)
        title = _("Multi-Record Editor")
        metaheaderadd = multi_edit_engine.get_scripts()
        metaheaderadd = metaheaderadd + multi_edit_engine.get_css()

        return page(title = title,
            metaheaderadd = metaheaderadd,
            body = body,
            req = req,
            language = language)
Example #45
0
def format_element(bfo, style):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    collection = guess_primary_collection_of_a_record(bfo.recID)
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibedit',
                                                     collection=collection)
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        out += create_html_link(CFG_SITE_URL +
                                '/record/edit/?ln=%s#state=edit&recid=%s' %
                                (bfo.lang, str(bfo.recID)), {},
                                link_label=_("Edit This Record"),
                                linkattrd=linkattrd)

    return out
Example #46
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)
 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 = getUid(req)
     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)
         else:
             #redirect..
             redirect_to_url(req, url)
Example #48
0
def generate_keywords(req, recid, argd):
    """Extracts keywords from the fulltexts (if found) for the
    given recid. It first checks whether the keywords are not already
    stored in the temp file (maybe from the previous run).
    @var req: req object
    @var recid: record id
    @var argd: arguments passed from web
    @keyword store_keywords: boolean, whether to save records in the file
    @return: standard dictionary of kw objects or {}
    """

    ln = argd['ln']
    _ = gettext_set_language(ln)
    keywords = {}

    # check the files were not already generated
    abs_path = bibclassify_engine.get_tmp_file(recid)
    if os.path.exists(abs_path):
        try:
            # Try to load the data from the tmp file
            recs = bibupload.xml_marc_to_records(bibupload.open_marc_file(abs_path))
            return record_get_keywords(recs[0])
        except:
            pass

    # check it is allowed (for this user) to generate pages
    (exit_stat, msg) = acce.acc_authorize_action(req, 'runbibclassify')
    if exit_stat != 0:
        log.info('Access denied: ' + msg)
        msg = _("The site settings do not allow automatic keyword extraction")
        req.write(template.tmpl_page_msg(msg=msg))
        return 0, keywords, None

    # register generation
    bibdocfiles = BibRecDocs(recid).list_latest_files()
    if bibdocfiles:
        # User arrived at a page, but no keywords are available
        inprogress, msg = _doc_already_submitted(recid)
        if argd['generate'] != 'yes':
            # Display a form and give them possibility to generate keywords
            if inprogress:
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' % _(msg)))
            else:
                req.write(template.tmpl_page_generate_keywords(req=req, **argd))
            return 0, keywords, None
        else: # after user clicked on "generate" button
            if inprogress:
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' % _(msg) ))
            else:
                schedule_extraction(recid, taxonomy=bconfig.CFG_EXTRACTION_TAXONOMY)
                req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' %
                                                 _('We have registered your request, the automated'
                'keyword extraction will run after some time. Please return back in a while.')))

    else:
        req.write(template.tmpl_page_msg(msg='<div class="warningbox">%s</div>' %
                    _("Unfortunately, we don't have a PDF fulltext for this record in the storage, \
                    keywords cannot be generated using an automated process.")))

    return 0, keywords, None
Example #49
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 #50
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(bfo, style):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    collection = guess_primary_collection_of_a_record(bfo.recID)
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibedit',
                                                     collection=collection)
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        out += create_html_link(CFG_SITE_URL +
               '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)),
               {},
               link_label=_("Edit This Record"),
               linkattrd=linkattrd)

    return out
Example #52
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 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)
def format(bfo, style):
    """
    Prints a link to BibEdit, if authorization is granted
    @param style the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)
    out = []
    
    if can_edit(bfo):    
        out.append('<a href="/curator/submit/edit?recid=%s&ln=%s">%s</a>' % \
                    (bfo.recID, bfo.lang, _("Edit this record")))
    
    user_info = bfo.user_info
    # before verifing access, assert that the user has a remote_ip and this is not
    # an internal call
    remote_ip = user_info.get('remote_ip', '')    
    
    if remote_ip:
        (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibedit')
        if auth_code == 0:
            out.append('<a href="/record/edit/#state=edit&recid=%s&ln=%s">%s</a>' % \
                    (str(bfo.recID), bfo.lang, _("Edit this record (BibEdit)")))
        
    user_uid = user_info.get('uid')

    if user_uid and not isGuestUser(user_uid):
        out.append(get_ask_for_removal_form(bfo))
        
    out = '&nbsp;&nbsp;|&nbsp;&nbsp;'.join(out)
    
    if remote_ip and auth_code == 0:
        return out + get_pending_informations(bfo) 
    else:
        return out