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)
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
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 #4
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 #5
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = '/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 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)
    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'])
Example #8
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 __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 #10
0
def extend_record_with_template(recid):
    """ Determine if the record has to be extended with the content
    of a template as defined in CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE
    @return: template name to be applied to record or False if no template
    has to be applied
    """
    rec_collection = guess_primary_collection_of_a_record(recid)
    if rec_collection in CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE:
        return CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE[rec_collection]
    return False
Example #11
0
def extend_record_with_template(recid):
    """ Determine if the record has to be extended with the content
    of a template as defined in CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE
    @return: template name to be applied to record or False if no template
    has to be applied
    """
    rec_collection = guess_primary_collection_of_a_record(recid)
    if rec_collection in CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE:
        return CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE[
            rec_collection]
    return False
        def getfile(req, form):
            args = wash_urlargd(form, websubmit_templates.files_default_urlargd)
            ln = args["ln"]

            _ = gettext_set_language(ln)

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

            verbose = args["verbose"]
            if verbose >= 1 and not isUserSuperAdmin(user_info):
                # Only SuperUser can see all the details!
                verbose = 0

            if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE > 1:
                return page_not_authorized(req, "/%s/%s" % (CFG_SITE_RECORD, self.recid), navmenuid="submit")

            if record_exists(self.recid) < 1:
                msg = "<p>%s</p>" % _("Requested record does not seem to exist.")
                return warningMsg(msg, req, CFG_SITE_NAME, ln)

            if record_empty(self.recid):
                msg = "<p>%s</p>" % _("Requested record does not seem to have been integrated.")
                return warningMsg(msg, req, CFG_SITE_NAME, ln)

            (auth_code, auth_message) = check_user_can_view_record(user_info, self.recid)
            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 = "/youraccount/login" + make_canonical_urlargd(
                    {"action": cookie, "ln": 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_message)

            readonly = CFG_ACCESS_CONTROL_LEVEL_SITE == 1

            # From now on: either the user provided a specific file
            # name (and a possible version), or we return a list of
            # all the available files. In no case are the docids
            # visible.
            try:
                bibarchive = BibRecDocs(self.recid)
            except InvenioWebSubmitFileError, e:
                register_exception(req=req, alert_admin=True)
                msg = "<p>%s</p><p>%s</p>" % (
                    _("The system has encountered an error in retrieving the list of files for this document."),
                    _("The error has been logged and will be taken in consideration as soon as possible."),
                )
                return warningMsg(msg, req, CFG_SITE_NAME, ln)
Example #13
0
def check_user_can_view_linkbacks(user_info, recid):
    """
    Check if the user is authorized to view linkbacks for a given recid.
    Returns the same type as acc_authorize_action
    """
    # check user cannot view the record itself
    (auth_code, auth_msg) = check_user_can_view_record(user_info, recid)
    if auth_code:
        return (auth_code, auth_msg)

    # check if user can view the linkbacks
    record_primary_collection = guess_primary_collection_of_a_record(recid)
    return acc_authorize_action(user_info, 'viewlinkbacks', authorized_if_no_roles=True, collection=record_primary_collection)
Example #14
0
def can_record_have_physical_copies(recid):
    """Determine if the record can have physical copies
    (addable through the bibCirculation module).
    The information is derieved using the tabs displayed for a given record.
    Only records already saved within the collection may have the physical copies
    @return: True or False
    """
    if get_record(recid) == None:
        return False

    col_id = get_colID(guess_primary_collection_of_a_record(recid))
    collections = get_detailed_page_tabs(col_id, recid)

    if (not collections.has_key("holdings")) or (not collections["holdings"].has_key("visible")):
        return False

    return collections["holdings"]["visible"] == True
Example #15
0
def can_record_have_physical_copies(recid):
    """Determine if the record can have physical copies
    (addable through the bibCirculation module).
    The information is derieved using the tabs displayed for a given record.
    Only records already saved within the collection may have the physical copies
    @return: True or False
    """
    if get_record(recid) == None:
        return False

    col_id = get_colID(guess_primary_collection_of_a_record(recid))
    collections = get_detailed_page_tabs(col_id, recid)

    if (not collections.has_key("holdings")) or \
        (not collections["holdings"].has_key("visible")):
        return False

    return collections["holdings"]["visible"] == True
Example #16
0
def send_request_notification_to_all_linkback_moderators(recid, origin_url, linkback_type, ln):
    """
    Send notification emails to all linkback moderators for linkback request
    @param recid
    @param origin_url: URL of the requestor
    @param linkback_type: of CFG_WEBLINKBACK_LIST_TYPE
    """
    content = """There is a new %(linkback_type)s request for %(recordURL)s from %(origin_url)s which you should approve or reject.
              """ % {'linkback_type': linkback_type,
                     'recordURL': generate_redirect_url(recid, ln),
                     'origin_url': origin_url}

    html_content = """There is a new %(linkback_type)s request for %(record)s (<a href="%(recordURL)s">%(recordURL)s</a>) from <a href="%(origin_url)s">%(title)s</a> (<a href="%(origin_url)s">%(origin_url)s</a>) which you should approve or reject.
                   """ % {'linkback_type': linkback_type,
                          'record': format_record(recID=recid, of='hs', ln=ln),
                          'recordURL': generate_redirect_url(recid, ln),
                          'origin_url': origin_url,
                          'title': origin_url}

    for email in acc_get_authorized_emails('moderatelinkbacks', collection = guess_primary_collection_of_a_record(recid)):
        send_email(CFG_SITE_ADMIN_EMAIL, email, 'New ' + linkback_type + ' request', content, html_content)
Example #17
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

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

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

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(-success), argd['ln'])
        redirect_to_url(req, display_url)
    def send(self, req, form):
        """
        Create a new hold request.
        """
        argd = wash_urlargd(form, {'period_from': (str, ""),
                                   'period_to': (str, ""),
                                   'barcode': (str, "")
                                   })

        uid = getUid(req)

        body = perform_new_request_send(recid=self.recid,
                                        uid=uid,
                                        period_from=argd['period_from'],
                                        period_to=argd['period_to'],
                                        barcode=argd['barcode'])

        ln = CFG_SITE_LANG
        _ = gettext_set_language(ln)


        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)



        unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                    self.recid,
                                                    ln=ln)
        ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % ln
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(self.recid,
                                                               tabs,
                                                               argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                     tabs,
                                                                     argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">'% (CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__,
                                             language=argd['ln'], req=req)
Example #19
0
    def __call__(self, req, form):
        """ Perform a search. """
        argd = wash_search_urlargd(form)

        _ = gettext_set_language(argd['ln'])

        if req.method == 'POST':
            raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

        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 area."),
                                       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

        involved_collections = set()
        involved_collections.update(argd['c'])
        involved_collections.add(argd['cc'])

        if argd['id'] > 0:
            argd['recid'] = argd['id']
        if argd['idb'] > 0:
            argd['recidb'] = argd['idb']
        if argd['sysno']:
            tmp_recid = find_record_from_sysno(argd['sysno'])
            if tmp_recid:
                argd['recid'] = tmp_recid
        if argd['sysnb']:
            tmp_recid = find_record_from_sysno(argd['sysnb'])
            if tmp_recid:
                argd['recidb'] = tmp_recid

        if argd['recid'] > 0:
            if argd['recidb'] > argd['recid']:
                # Hack to check if among the restricted collections
                # at least a record of the range is there and
                # then if the user is not authorized for that
                # collection.
                recids = intbitset(xrange(argd['recid'], argd['recidb']))
                restricted_collection_cache.recreate_cache_if_needed()
                for collname in restricted_collection_cache.cache:
                    (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=collname)
                    if auth_code and user_info['email'] == 'guest':
                        coll_recids = get_collection(collname).reclist
                        if coll_recids & recids:
                            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : collname})
                            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')
            else:
                involved_collections.add(guess_primary_collection_of_a_record(argd['recid']))

        # If any of the collection requires authentication, redirect
        # to the authentication form.
        for coll in involved_collections:
            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

        # 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 #20
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)

        argd['recid'] = self.recid

        argd['tab'] = self.tab

        # do we really enter here ?

        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

        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')

        from invenio.search_engine import record_exists, get_merged_recid
        # check if the current record has been deleted
        # and has been merged, case in which the deleted record
        # will be redirect to the new one
        record_status = record_exists(argd['recid'])
        merged_recid = get_merged_recid(argd['recid'])
        if record_status == -1 and merged_recid:
            url = CFG_SITE_URL + '/' + CFG_SITE_RECORD + '/%s?ln=%s'
            url %= (str(merged_recid), argd['ln'])
            redirect_to_url(req, url)
        elif record_status == -1:
            req.status = apache.HTTP_GONE ## The record is gone!

        # 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 #21
0
class WebInterfaceCommentsPages(WebInterfaceDirectory):
    """Defines the set of /comments pages."""

    _exports = [
        '', 'display', 'add', 'vote', 'report', 'index', 'attachments',
        'subscribe', 'unsubscribe'
    ]

    def __init__(self, recid=-1, reviews=0):
        self.recid = recid
        self.discussion = reviews  # 0:comments, 1:reviews
        self.attachments = WebInterfaceCommentsFiles(recid, reviews)

    def index(self, req, form):
        """
        Redirects to display function
        """
        return self.display(req, form)

    def display(self, req, form):
        """
        Display comments (reviews if enabled) associated with record having id recid where recid>0.
        This function can also be used to display remarks associated with basket having id recid where recid<-99.
        @param ln: language
        @param recid: record id, integer
        @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 voted: boolean, active if user voted for a review, see vote function
        @param reported: int, active if user reported a certain comment/review, see report function
        @param reviews: boolean, enabled for reviews, disabled for comments
        @param subscribed: int, 1 if user just subscribed to discussion, -1 if unsubscribed
        @return the full html page.
        """
        argd = wash_urlargd(
            form,
            {
                'do': (str, "od"),
                'ds': (str, "all"),
                'nb': (int, 100),
                'p': (int, 1),
                'voted': (int, -1),
                'reported': (int, -1),
                'subscribed': (int, 0),
                'cmtgrp': (list, ["latest"]
                           )  # 'latest' is now a reserved group/round name
            })

        _ = gettext_set_language(argd['ln'])
        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 and 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_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        can_send_comments = False
        (auth_code,
         auth_msg) = check_user_can_send_comments(user_info, self.recid)
        if not auth_code:
            can_send_comments = True

        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        subscription = get_user_subscription_to_discussion(self.recid, uid)
        if subscription == 1:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = True
        elif subscription == 2:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = False
        else:
            user_is_subscribed_to_discussion = False
            user_can_unsubscribe_from_discussion = False

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']

        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['comments', 'reviews'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]

        tabs_counts = get_detailed_page_tabs_counts(self.recid)
        citedbynum = tabs_counts['Citations']
        references = tabs_counts['References']
        discussions = tabs_counts['Discussions']

        top = webstyle_templates.detailed_record_container_top(
            self.recid,
            tabs,
            argd['ln'],
            citationnum=citedbynum,
            referencenum=references,
            discussionnum=discussions)
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"]
        display_comment_rounds = argd['cmtgrp']

        check_warnings = []

        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings,
                                                argd['ln'])
        if ok:
            body = perform_request_display_comments_or_remarks(
                req=req,
                recID=self.recid,
                display_order=argd['do'],
                display_since=argd['ds'],
                nb_per_page=argd['nb'],
                page=argd['p'],
                ln=argd['ln'],
                voted=argd['voted'],
                reported=argd['reported'],
                subscribed=argd['subscribed'],
                reviews=self.discussion,
                uid=uid,
                can_send_comments=can_send_comments,
                can_attach_files=can_attach_files,
                user_is_subscribed_to_discussion=
                user_is_subscribed_to_discussion,
                user_can_unsubscribe_from_discussion=
                user_can_unsubscribe_from_discussion,
                display_comment_rounds=display_comment_rounds)

            title, description, keywords = websearch_templates.tmpl_record_page_header_content(
                req, self.recid, argd['ln'])
            navtrail = create_navtrail_links(
                cc=guess_primary_collection_of_a_record(self.recid),
                ln=argd['ln'])
            if navtrail:
                navtrail += ' &gt; '
            navtrail += '<a class="navtrail" href="%s/%s/%s?ln=%s">' % (
                CFG_SITE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
            navtrail += title
            navtrail += '</a>'
            navtrail += ' &gt; <a class="navtrail">%s</a>' % (
                self.discussion == 1 and _("Reviews") or _("Comments"))

            mathjaxheader = ''
            if CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS:
                mathjaxheader = get_mathjax_header(req.is_https())
            jqueryheader = '''
            <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script>
            ''' % {
                'CFG_SITE_URL': CFG_SITE_URL
            }


            return pageheaderonly(title=title,
                        navtrail=navtrail,
                        uid=uid,
                        verbose=1,
                        metaheaderadd = mathjaxheader + jqueryheader,
                        req=req,
                        language=argd['ln'],
                        navmenuid='search',
                        navtrail_append_title_p=0) + \
                    websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                    top + body + bottom + \
                    websearch_templates.tmpl_search_pageend(argd['ln']) + \
                    pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
        else:
            return page(title=_("Record Not Found"),
                        body=problem,
                        uid=uid,
                        verbose=1,
                        req=req,
                        language=argd['ln'],
                        navmenuid='search')

    # Return the same page wether we ask for /CFG_SITE_RECORD/123 or /CFG_SITE_RECORD/123/
    __call__ = index

    def add(self, req, form):
        """
        Add a comment (review) to record with id recid where recid>0
        Also works for adding a remark to basket with id recid where recid<-99
        @param ln: languange
        @param recid: record id
        @param action:  'DISPLAY' to display add form
                        'SUBMIT' to submit comment once form is filled
                        'REPLY' to reply to an already existing comment
        @param msg: the body of the comment/review or remark
        @param score: star score of the review
        @param note: title of the review
        @param comid: comment id, needed for replying
        @param editor_type: the type of editor used for submitting the
                            comment: 'textarea', 'ckeditor'.
        @param subscribe: if set, subscribe user to receive email
                          notifications when new comment are added to
                          this discussion
        @return the full html page.
        """
        argd = wash_urlargd(
            form, {
                'action': (str, "DISPLAY"),
                'msg': (str, ""),
                'note': (str, ''),
                'score': (int, 0),
                'comid': (int, 0),
                'editor_type': (str, ""),
                'subscribe': (str, ""),
                'cookie': (str, "")
            })
        _ = gettext_set_language(argd['ln'])

        actions = ['DISPLAY', 'REPLY', 'SUBMIT']
        uid = getUid(req)

        # Is site ready to accept comments?
        if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS
                         and not CFG_WEBCOMMENT_ALLOW_REVIEWS):
            return page_not_authorized(req,
                                       "../comments/add",
                                       navmenuid='search')

        # Is user allowed to post comment?
        user_info = collect_user_info(req)
        (auth_code_1,
         auth_msg_1) = check_user_can_view_comments(user_info, self.recid)
        (auth_code_2,
         auth_msg_2) = check_user_can_send_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            # Save user's value in cookie, so that these "POST"
            # parameters are not lost during login process
            msg_cookie = mail_cookie_create_common(
                'comment_msg', {
                    'msg': argd['msg'],
                    'note': argd['note'],
                    'score': argd['score'],
                    'editor_type': argd['editor_type'],
                    'subscribe': argd['subscribe']
                },
                onetime=True)
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {})
            return redirect_to_url(req, target, norobot=True)
        elif (auth_code_1 or auth_code_2):
            return page_not_authorized(req, "../", \
                text = auth_msg_1 + auth_msg_2)

        user_info = collect_user_info(req)
        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        warning_msgs = [
        ]  # list of warning tuples (warning_text, warning_color)
        added_files = {}
        if can_attach_files:
            # User is allowed to attach files. Process the files
            file_too_big = False
            formfields = form.get('commentattachment[]', [])
            if not hasattr(formfields,
                           "__getitem__"):  # A single file was uploaded
                formfields = [formfields]
            for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]:
                if hasattr(formfield, "filename") and formfield.filename:
                    filename = formfield.filename
                    dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment',
                                               str(uid))
                    try:
                        assert (dir_to_open.startswith(CFG_TMPDIR))
                    except AssertionError:
                        register_exception(req=req,
                                           prefix='User #%s tried to upload file to forbidden location: %s' \
                                           % (uid, dir_to_open))

                    if not os.path.exists(dir_to_open):
                        try:
                            os.makedirs(dir_to_open)
                        except:
                            register_exception(req=req, alert_admin=True)

                    ## Before saving the file to disc, wash the filename (in particular
                    ## washing away UNIX and Windows (e.g. DFS) paths):
                    filename = os.path.basename(filename.split('\\')[-1])
                    filename = filename.strip()
                    if filename != "":
                        # Check that file does not already exist
                        n = 1
                        while os.path.exists(
                                os.path.join(dir_to_open, filename)):
                            basedir, name, extension = decompose_file(filename)
                            new_name = propose_next_docname(name)
                            filename = new_name + extension

                        fp = open(os.path.join(dir_to_open, filename), "w")
                        # FIXME: temporary, waiting for wsgi handler to be
                        # fixed. Once done, read chunk by chunk
                        ##                         while formfield.file:
                        ##                             fp.write(formfield.file.read(10240))
                        fp.write(formfield.file.read())
                        fp.close()
                        # Isn't this file too big?
                        file_size = os.path.getsize(
                            os.path.join(dir_to_open, filename))
                        if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \
                               file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE:
                            os.remove(os.path.join(dir_to_open, filename))
                            # One file is too big: record that,
                            # dismiss all uploaded files and re-ask to
                            # upload again
                            file_too_big = True
                            try:
                                raise InvenioWebCommentWarning(
                                    _('The size of file \\"%s\\" (%s) is larger than maximum allowed file size (%s). Select files again.'
                                      ) %
                                    (cgi.escape(filename),
                                     str(file_size / 1024) + 'KB',
                                     str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE /
                                         1024) + 'KB'))
                            except InvenioWebCommentWarning, exc:
                                register_exception(stream='warning')
                                warning_msgs.append((exc.message, ''))
                            #warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB'))
                        else:
                            added_files[filename] = os.path.join(
                                dir_to_open, filename)

            if file_too_big:
                # One file was too big. Removed all uploaded filed
                for filepath in added_files.items():
                    try:
                        os.remove(filepath)
                    except:
                        # File was already removed or does not exist?
                        pass

        client_ip_address = req.remote_ip
        check_warnings = []
        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings,
                                                argd['ln'])
        if ok:
            title, description, keywords = websearch_templates.tmpl_record_page_header_content(
                req, self.recid, argd['ln'])
            navtrail = create_navtrail_links(
                cc=guess_primary_collection_of_a_record(self.recid))
            if navtrail:
                navtrail += ' &gt; '
            navtrail += '<a class="navtrail" href="%s/%s/%s?ln=%s">' % (
                CFG_SITE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
            navtrail += title
            navtrail += '</a>'
            navtrail += '&gt; <a class="navtrail" href="%s/%s/%s/%s/?ln=%s">%s</a>' % (
                CFG_SITE_URL, CFG_SITE_RECORD, self.recid,
                self.discussion == 1 and 'reviews' or 'comments', argd['ln'],
                self.discussion == 1 and _('Reviews') or _('Comments'))

            if argd['action'] not in actions:
                argd['action'] = 'DISPLAY'

            if not argd['msg']:
                # User had to login in-between, so retrieve msg
                # from cookie
                try:
                    (kind,
                     cookie_argd) = mail_cookie_check_common(argd['cookie'],
                                                             delete=True)

                    argd.update(cookie_argd)
                except InvenioWebAccessMailCookieDeletedError, e:
                    return redirect_to_url(req, CFG_SITE_SECURE_URL + '/'+ CFG_SITE_RECORD +'/' + \
                                           str(self.recid) + (self.discussion==1 and \
                                                              '/reviews' or '/comments'))
                except InvenioWebAccessMailCookieError, e:
                    # Invalid or empty cookie: continue
                    pass
Example #22
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_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 = 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_SECURE_URL, CFG_SITE_RECORD, self.recid,
                        self.discussion == 1 and 'reviews'
                        or 'comments', argd['ln'])
            redirect_to_url(req, referer)
                                req.status = apache.HTTP_UNAUTHORIZED
                                warn = print_warning(_("The requested file is hidden and can not be accessed."))

                        except InvenioWebSubmitFileError, msg:
                            register_exception(req=req, alert_admin=True)

            if docname and format and not warn:
                req.status = apache.HTTP_NOT_FOUND
                warn += print_warning(_("Requested file does not seem to exist."))
            filelist = bibarchive.display("", version, ln=ln, verbose=verbose, display_hidden=display_hidden)

            t = warn + websubmit_templates.tmpl_filelist(
                ln=ln, recid=self.recid, docname=args["docname"], version=version, filelist=filelist
            )

            cc = guess_primary_collection_of_a_record(self.recid)
            unordered_tabs = get_detailed_page_tabs(get_colID(cc), self.recid, ln)
            ordered_tabs_id = [(tab_id, values["order"]) for (tab_id, values) in unordered_tabs.iteritems()]
            ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
            link_ln = ""
            if ln != CFG_SITE_LANG:
                link_ln = "?ln=%s" % ln
            tabs = [
                (
                    unordered_tabs[tab_id]["label"],
                    "%s/%s/%s/%s%s" % (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln),
                    tab_id == "files",
                    unordered_tabs[tab_id]["enabled"],
                )
                for (tab_id, order) in ordered_tabs_id
                if unordered_tabs[tab_id]["visible"] == True
Example #24
0
                    _("Requested file does not seem to exist."))


#            filelist = bibarchive.display("", version, ln=ln, verbose=verbose, display_hidden=display_hidden)
            filelist = bibdocfile_templates.tmpl_display_bibrecdocs(
                bibarchive,
                "",
                version,
                ln=ln,
                verbose=verbose,
                display_hidden=display_hidden)

            t = warn + bibdocfile_templates.tmpl_filelist(ln=ln,
                                                          filelist=filelist)

            cc = guess_primary_collection_of_a_record(self.recid)
            unordered_tabs = get_detailed_page_tabs(get_colID(cc), self.recid,
                                                    ln)
            ordered_tabs_id = [(tab_id, values['order'])
                               for (tab_id,
                                    values) in unordered_tabs.iteritems()]
            ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
            link_ln = ''
            if ln != CFG_SITE_LANG:
                link_ln = '?ln=%s' % ln
            tabs = [
                (unordered_tabs[tab_id]['label'], '%s/%s/%s/%s%s' %
                 (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln),
                 tab_id == 'files', unordered_tabs[tab_id]['enabled'])
                for (tab_id, dummy_order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] is True
Example #25
0
    def ill_register_request_with_recid(self, req, form):
        """
        Register ILL request.
        """

        argd = wash_urlargd(
            form, {
                'ln': (str, ""),
                'period_of_interest_from': (str, ""),
                'period_of_interest_to': (str, ""),
                'additional_comments': (str, ""),
                'conditions': (str, ""),
                'only_edition': (str, ""),
            })

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

        body = ill_register_request_with_recid(
            recid=self.recid,
            uid=uid,
            period_of_interest_from=argd['period_of_interest_from'],
            period_of_interest_to=argd['period_of_interest_to'],
            additional_comments=argd['additional_comments'],
            conditions=argd['conditions'],
            only_edition=argd['only_edition'],
            ln=argd['ln'])

        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req,
                                       "../holdings/ill_request_with_recid",
                                       navmenuid='yourbaskets')

        if isGuestUser(uid):
            if not CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS:
                return redirect_to_url(
                    req, "%s/youraccount/login%s" %
                    (CFG_SITE_SECURE_URL,
                     make_canonical_urlargd(
                         {
                             'referer':
                             "%s/record/%s/holdings/ill_request_with_recid%s" %
                             (CFG_SITE_URL, self.recid,
                              make_canonical_urlargd(argd, {})),
                             "ln":
                             argd['ln']
                         }, {})))

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_record(user_info, self.recid)
        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 = '/youraccount/login' + \
                     make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(
            self.recid, tabs, argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(
            req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(
            cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">' % (
            CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
Example #26
0
    def tmpl_alert_email_body(self, name, url, records, pattern,
                              collection_list, frequency, add_to_basket_p):

        recids_by_collection = {}
        for recid in records[0]:
            primary_collection = guess_primary_collection_of_a_record(recid)
            if primary_collection in collection_list:
                if not recids_by_collection.has_key(primary_collection):
                    recids_by_collection[primary_collection] = []
                recids_by_collection[primary_collection].append(recid)
            else:
                ancestors = get_coll_ancestors(primary_collection)
                ancestors.reverse()
                nancestors = 0
                for ancestor in ancestors:
                    nancestors += 1
                    if ancestor in collection_list:
                        if not recids_by_collection.has_key(ancestor):
                            recids_by_collection[ancestor] = []
                        recids_by_collection[ancestor].append(recid)
                        break
                    elif len(ancestors) == nancestors:
                        if not recids_by_collection.has_key(
                                'None of the above'):
                            recids_by_collection['None of the above'] = []
                        recids_by_collection['None of the above'].append(recid)

        collection_list = [
            coll for coll in recids_by_collection.keys()
            if coll != 'None of the above'
        ]
        for external_collection_results in records[1][0]:
            if external_collection_results[1][0]:
                collection_list.append(external_collection_results[0])

        l = len(collection_list)
        if l == 0:
            collections = ''
        elif l == 1:
            collections = "collection: %s\n" % collection_list[0]
        else:
            collections = "collections: %s\n" % wrap(
                ', '.join(collection_list))

        l = len(records[0])
        for external_collection_results in records[1][0]:
            l += len(external_collection_results[1][0])
        if l == 1:
            total = '1 record'
        else:
            total = '%d records' % l

        if pattern:
            pattern = 'pattern: %s\n' % pattern

        frequency = {
            'day': 'daily',
            'week': 'weekly',
            'month': 'monthly'
        }[frequency]

        body = """\
Hello:

Below are the results of the email notification alert that
you set up with the %(sitename)s.
This is an automatic message, please don't reply to it.
For any question, please use <%(sitesupportemail)s> instead.

alert name: %(name)s
%(pattern)s%(collections)sfrequency: %(frequency)s
run time: %(runtime)s
found: %(total)s
url: <%(url)s>
""" % {
            'sitesupportemail': CFG_SITE_SUPPORT_EMAIL,
            'name': name,
            'sitename': CFG_SITE_NAME,
            'pattern': pattern,
            'collections': collections,
            'frequency': frequency,
            'runtime': time.strftime("%a %Y-%m-%d %H:%M:%S"),
            'total': total,
            'url': url
        }

        index = 0

        for collection_recids in recids_by_collection.items():
            if collection_recids[0] != 'None of the above':
                body += "\nCollection: %s\n" % collection_recids[0]
                for recid in collection_recids[1]:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            if recids_by_collection.has_key('None of the above'):
                if len(recids_by_collection.keys()) > 1:
                    body += "\nNone of the above collections:\n"
                else:
                    # if the uncategorized collection is the only collection then present
                    # all the records as belonging to CFG_SITE_NAME
                    body += "\nCollection: %s\n" % CFG_SITE_NAME
                for recid in recids_by_collection['None of the above']:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            for external_collection_results in records[1][0]:
                body += "\nCollection: %s\n" % external_collection_results[0]
                for recid in external_collection_results[1][0]:
                    index += 1
                    body += "\n%i) " % (index)
                    # TODO: extend function to accept xml_record!
                    body += self.tmpl_alert_email_record(
                        xml_record=external_collection_results[1][1][recid])
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if l > CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            body += '''
Only the first %s records were displayed. Please consult the search
URL given at the top of this email to see all the results.
''' % (CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL, )
            if add_to_basket_p:
                body += '''
Only the first %s records were added to your basket. To manually add more
records please consult the search URL as described before.
''' % (CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL, )

        body += '''
--
%s Alert Service <%s>
Unsubscribe?  See <%s>
Need human intervention?  Contact <%s>
''' % (CFG_SITE_NAME, CFG_SITE_URL, CFG_SITE_URL + '/youralerts/list',
        CFG_SITE_SUPPORT_EMAIL)

        return body
Example #27
0
    def send(self, req, form):
        """
        Create a new hold request.
        """
        argd = wash_urlargd(form, {
            'period_from': (str, ""),
            'period_to': (str, ""),
            'barcode': (str, "")
        })

        uid = getUid(req)

        body = perform_new_request_send(recid=self.recid,
                                        uid=uid,
                                        period_from=argd['period_from'],
                                        period_to=argd['period_to'],
                                        barcode=argd['barcode'])

        ln = CFG_SITE_LANG
        _ = gettext_set_language(ln)

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_record(user_info, self.recid)
        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 = '/youraccount/login' + \
                     make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=ln)
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % ln
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(
            self.recid, tabs, argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(
            req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(
            cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">' % (
            CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__,
                                             language=argd['ln'], req=req)
Example #28
0
    def display(self, req, form):
        """
        Show the tab 'holdings'.
        """

        argd = wash_urlargd(
            form, {
                'do': (str, "od"),
                'ds': (str, "all"),
                'nb': (int, 100),
                'p': (int, 1),
                'voted': (int, -1),
                'reported': (int, -1),
            })
        _ = gettext_set_language(argd['ln'])

        record_exists_p = record_exists(self.recid)
        if record_exists_p != 1:
            if record_exists_p == -1:
                msg = _("The record has been deleted.")
            else:
                msg = _("Requested record does not seem to exist.")
            msg = '<span class="quicknote">' + msg + '</span>'
            title, description, keywords = \
                   websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])
            return page(title=title,
                        show_title_p=False,
                        body=msg,
                        description=description,
                        keywords=keywords,
                        uid=getUid(req),
                        language=argd['ln'],
                        req=req,
                        navmenuid='search')

        body = perform_get_holdings_information(self.recid, req, argd['ln'])

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_record(user_info, self.recid)
        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 = '/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)

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(
            self.recid, tabs, argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(
            req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(
            cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">' % (
            CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_URL,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
Example #29
0
        def getfile(req, form):
            args = wash_urlargd(form,
                                bibdocfile_templates.files_default_urlargd)
            ln = args['ln']

            _ = gettext_set_language(ln)

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

            verbose = args['verbose']
            if verbose >= 1 and not isUserSuperAdmin(user_info):
                # Only SuperUser can see all the details!
                verbose = 0

            if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE > 1:
                return page_not_authorized(req,
                                           "/%s/%s" %
                                           (CFG_SITE_RECORD, self.recid),
                                           navmenuid='submit')

            if record_exists(self.recid) < 1:
                msg = "<p>%s</p>" % _(
                    "Requested record does not seem to exist.")
                return warning_page(msg, req, ln)

            if record_empty(self.recid):
                msg = "<p>%s</p>" % _(
                    "Requested record does not seem to have been integrated.")
                return warning_page(msg, req, ln)

            (auth_code,
             auth_message) = check_user_can_view_record(user_info, self.recid)
            if auth_code and user_info['email'] == 'guest':
                if webjournal_utils.is_recid_in_released_issue(self.recid):
                    # We can serve the file
                    pass
                else:
                    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' : ln, 'referer' : \
                                                     CFG_SITE_SECURE_URL + user_info['uri']}, {})
                    return redirect_to_url(req, target, norobot=True)
            elif auth_code:
                if webjournal_utils.is_recid_in_released_issue(self.recid):
                    # We can serve the file
                    pass
                else:
                    return page_not_authorized(req, "../", \
                                               text = auth_message)

            readonly = CFG_ACCESS_CONTROL_LEVEL_SITE == 1

            # From now on: either the user provided a specific file
            # name (and a possible version), or we return a list of
            # all the available files. In no case are the docids
            # visible.
            try:
                bibarchive = BibRecDocs(self.recid)
            except InvenioBibDocFileError:
                register_exception(req=req, alert_admin=True)
                msg = "<p>%s</p><p>%s</p>" % (
                    _("The system has encountered an error in retrieving the list of files for this document."
                      ),
                    _("The error has been logged and will be taken in consideration as soon as possible."
                      ))
                return warning_page(msg, req, ln)

            if bibarchive.deleted_p():
                req.status = apache.HTTP_GONE
                return warning_page(
                    _("Requested record does not seem to exist."), req, ln)

            docname = ''
            docformat = ''
            version = ''
            warn = ''

            if filename:
                # We know the complete file name, guess which docid it
                # refers to
                ## TODO: Change the extension system according to ext.py from setlink
                ##       and have a uniform extension mechanism...
                docname = file_strip_ext(filename)
                docformat = filename[len(docname):]
                if docformat and docformat[0] != '.':
                    docformat = '.' + docformat
                if args['subformat']:
                    docformat += ';%s' % args['subformat']
            else:
                docname = args['docname']

            if not docformat:
                docformat = args['format']
                if args['subformat']:
                    docformat += ';%s' % args['subformat']

            if not version:
                version = args['version']

            ## Download as attachment
            is_download = False
            if args['download']:
                is_download = True

            # version could be either empty, or all or an integer
            try:
                int(version)
            except ValueError:
                if version != 'all':
                    version = ''

            display_hidden = isUserSuperAdmin(user_info)

            if version != 'all':
                # search this filename in the complete list of files
                for doc in bibarchive.list_bibdocs():
                    if docname == bibarchive.get_docname(doc.id):
                        try:
                            try:
                                docfile = doc.get_file(docformat, version)
                            except InvenioBibDocFileError, msg:
                                req.status = apache.HTTP_NOT_FOUND
                                if not CFG_INSPIRE_SITE and req.headers_in.get(
                                        'referer'):
                                    ## There must be a broken link somewhere.
                                    ## Maybe it's good to alert the admin
                                    register_exception(req=req,
                                                       alert_admin=True)
                                warn += write_warning(
                                    _("The format %s does not exist for the given version: %s"
                                      ) % (cgi.escape(docformat),
                                           cgi.escape(str(msg))))
                                break
                            (auth_code,
                             auth_message) = docfile.is_restricted(user_info)
                            if auth_code != 0 and not is_user_owner_of_record(
                                    user_info, self.recid):
                                if CFG_BIBDOCFILE_ICON_SUBFORMAT_RE.match(
                                        get_subformat_from_format(docformat)):
                                    return stream_restricted_icon(req)
                                if user_info['email'] == 'guest':
                                    cookie = mail_cookie_create_authorize_action(
                                        'viewrestrdoc',
                                        {'status': docfile.get_status()})
                                    target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                                    make_canonical_urlargd({'action': cookie, 'ln' : ln, 'referer' : \
                                        CFG_SITE_SECURE_URL + user_info['uri']}, {})
                                    redirect_to_url(req, target)
                                else:
                                    req.status = apache.HTTP_UNAUTHORIZED
                                    warn += write_warning(
                                        _("This file is restricted: ") +
                                        str(auth_message))
                                    break

                            if not docfile.hidden_p():
                                if not readonly:
                                    ip = str(req.remote_ip)
                                    doc.register_download(
                                        ip, docfile.get_version(), docformat,
                                        uid, self.recid)
                                try:
                                    return docfile.stream(req,
                                                          download=is_download)
                                except InvenioBibDocFileError, msg:
                                    register_exception(req=req,
                                                       alert_admin=True)
                                    req.status = apache.HTTP_INTERNAL_SERVER_ERROR
                                    warn += write_warning(
                                        _("An error has happened in trying to stream the request file."
                                          ))
                            else:
                                req.status = apache.HTTP_UNAUTHORIZED
                                warn += write_warning(
                                    _("The requested file is hidden and can not be accessed."
                                      ))

                        except InvenioBibDocFileError, msg:
                            register_exception(req=req, alert_admin=True)
    def _get(self, req, form):
        """
        Returns a file attached to a comment.

        Example:
        CFG_SITE_URL/record/5953/comments/attachments/get/652/myfile.pdf
        where 652 is the comment ID
        """
        argd = wash_urlargd(form, {'file': (str, None),
                                   'comid': (int, 0)})
        _ = gettext_set_language(argd['ln'])

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check that user can view record, and its comments (protected
        # with action "viewcomment")
        (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)

        # Does comment exist?
        if not query_get_comment(argd['comid']):
            req.status = apache.HTTP_NOT_FOUND
            return page(title=_("Page Not Found"),
                        body=_('The requested comment could not be found'),
                        req=req)

        # Check that user can view this particular comment, protected
        # using its own restriction
        (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        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('/opt/cds-invenio/var/data/comments/' + \
                                   str(self.recid) + '/'  + str(argd['comid']) + \
                                   '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith('/opt/cds-invenio/var/data/comments/' + \
                               str(self.recid)) and \
                   os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        req.status = apache.HTTP_NOT_FOUND
        return page(title=_("Page Not Found"),
                    body=_('The requested file could not be found'),
                    req=req,
                    language=argd['ln'])
Example #31
0
    def display(self, req, form):
        """
        Display comments (reviews if enabled) associated with record having id recid where recid>0.
        This function can also be used to display remarks associated with basket having id recid where recid<-99.
        @param ln: language
        @param recid: record id, integer
        @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 voted: boolean, active if user voted for a review, see vote function
        @param reported: int, active if user reported a certain comment/review, see report function
        @param reviews: boolean, enabled for reviews, disabled for comments
        @param subscribed: int, 1 if user just subscribed to discussion, -1 if unsubscribed
        @return the full html page.
        """
        argd = wash_urlargd(
            form,
            {
                'do': (str, "od"),
                'ds': (str, "all"),
                'nb': (int, 100),
                'p': (int, 1),
                'voted': (int, -1),
                'reported': (int, -1),
                'subscribed': (int, 0),
                'cmtgrp': (list, ["latest"]
                           )  # 'latest' is now a reserved group/round name
            })

        _ = gettext_set_language(argd['ln'])
        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 and 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_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        can_send_comments = False
        (auth_code,
         auth_msg) = check_user_can_send_comments(user_info, self.recid)
        if not auth_code:
            can_send_comments = True

        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        subscription = get_user_subscription_to_discussion(self.recid, uid)
        if subscription == 1:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = True
        elif subscription == 2:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = False
        else:
            user_is_subscribed_to_discussion = False
            user_can_unsubscribe_from_discussion = False

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']

        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['comments', 'reviews'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]

        tabs_counts = get_detailed_page_tabs_counts(self.recid)
        citedbynum = tabs_counts['Citations']
        references = tabs_counts['References']
        discussions = tabs_counts['Discussions']

        top = webstyle_templates.detailed_record_container_top(
            self.recid,
            tabs,
            argd['ln'],
            citationnum=citedbynum,
            referencenum=references,
            discussionnum=discussions)
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"]
        display_comment_rounds = argd['cmtgrp']

        check_warnings = []

        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings,
                                                argd['ln'])
        if ok:
            body = perform_request_display_comments_or_remarks(
                req=req,
                recID=self.recid,
                display_order=argd['do'],
                display_since=argd['ds'],
                nb_per_page=argd['nb'],
                page=argd['p'],
                ln=argd['ln'],
                voted=argd['voted'],
                reported=argd['reported'],
                subscribed=argd['subscribed'],
                reviews=self.discussion,
                uid=uid,
                can_send_comments=can_send_comments,
                can_attach_files=can_attach_files,
                user_is_subscribed_to_discussion=
                user_is_subscribed_to_discussion,
                user_can_unsubscribe_from_discussion=
                user_can_unsubscribe_from_discussion,
                display_comment_rounds=display_comment_rounds)

            title, description, keywords = websearch_templates.tmpl_record_page_header_content(
                req, self.recid, argd['ln'])
            navtrail = create_navtrail_links(
                cc=guess_primary_collection_of_a_record(self.recid),
                ln=argd['ln'])
            if navtrail:
                navtrail += ' &gt; '
            navtrail += '<a class="navtrail" href="%s/%s/%s?ln=%s">' % (
                CFG_SITE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
            navtrail += title
            navtrail += '</a>'
            navtrail += ' &gt; <a class="navtrail">%s</a>' % (
                self.discussion == 1 and _("Reviews") or _("Comments"))

            mathjaxheader = ''
            if CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS:
                mathjaxheader = get_mathjax_header(req.is_https())
            jqueryheader = '''
            <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script>
            ''' % {
                'CFG_SITE_URL': CFG_SITE_URL
            }


            return pageheaderonly(title=title,
                        navtrail=navtrail,
                        uid=uid,
                        verbose=1,
                        metaheaderadd = mathjaxheader + jqueryheader,
                        req=req,
                        language=argd['ln'],
                        navmenuid='search',
                        navtrail_append_title_p=0) + \
                    websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                    top + body + bottom + \
                    websearch_templates.tmpl_search_pageend(argd['ln']) + \
                    pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
        else:
            return page(title=_("Record Not Found"),
                        body=problem,
                        uid=uid,
                        verbose=1,
                        req=req,
                        language=argd['ln'],
                        navmenuid='search')
    def display(self, req, form):
        """
        Display the linkbacks of a record and admin approve/reject features
        """
        argd = wash_urlargd(form, {})

        _ = gettext_set_language(argd['ln'])

        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = check_user_can_view_linkbacks(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])

        show_admin = False
        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatelinkbacks', collection = guess_primary_collection_of_a_record(self.recid))
        if not auth_code:
            show_admin = True

        body = perform_request_display_record_linbacks(req, self.recid, show_admin, weblinkback_templates=weblinkback_templates, ln=argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]

        # navigation, tabs, top and bottom part
        navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        if navtrail:
            navtrail += ' &gt; '
        navtrail += '<a class="navtrail" href="%s/%s/%s?ln=%s">'% (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'
        navtrail += ' &gt; <a class="navtrail">Linkbacks</a>'

        mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader()

        unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                     '%s/%s/%s/%s%s' % (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                     tab_id in ['linkbacks'],
                     unordered_tabs[tab_id]['enabled']) \
                     for (tab_id, values) in ordered_tabs_id
                     if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(self.recid,
                                                              tabs,
                                                              argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                    tabs,
                                                                    argd['ln'])

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              metaheaderadd = mathjaxheader + jqueryheader,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
               top + body + bottom + \
               websearch_templates.tmpl_search_pageend(argd['ln']) + \
               pagefooteronly(language=argd['ln'], req=req)
    def ill_register_request_with_recid(self, req, form):
        """
        Register ILL request.
        """

        argd = wash_urlargd(form, {'ln': (str, ""),
                                   'period_of_interest_from': (str, ""),
                                   'period_of_interest_to': (str, ""),
                                   'additional_comments': (str, ""),
                                   'conditions': (str, ""),
                                   'only_edition': (str, ""),
                                   })

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

        body = ill_register_request_with_recid(recid=self.recid,
                                               uid=uid,
                                               period_of_interest_from =  argd['period_of_interest_from'],
                                               period_of_interest_to =  argd['period_of_interest_to'],
                                               additional_comments =  argd['additional_comments'],
                                               conditions = argd['conditions'],
                                               only_edition = argd['only_edition'],
                                               ln=argd['ln'])

        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "../holdings/ill_request_with_recid",
                                       navmenuid = 'yourbaskets')

        if isGuestUser(uid):
            if not CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS:
                return redirect_to_url(req, "%s/youraccount/login%s" % (
                    CFG_SITE_SECURE_URL,
                        make_canonical_urlargd({
                    'referer' : "%s/record/%s/holdings/ill_request_with_recid%s" % (
                        CFG_SITE_URL,
                        self.recid,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))


        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)



        unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                    self.recid,
                                                    ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(self.recid,
                                                               tabs,
                                                               argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                     tabs,
                                                                     argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">'% (CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
Example #34
0
    def tmpl_pagefooter(self,
                        req=None,
                        ln=CFG_SITE_LANG,
                        lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

        Parameters:

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

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

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

        Output:

        - HTML code of the page headers
        """
        from invenio.search_engine import guess_primary_collection_of_a_record

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

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

        # Prepare Piwik custom variables if we are in a detailed record page
        record_page_re = re.compile(
            "^/record/(?P<recid>[0-9]+)/?(?P<page_type>.*)")

        custom_variables = ""

        record_page_match = record_page_re.match(req.uri)
        if record_page_match:
            record_collection = guess_primary_collection_of_a_record(
                record_page_match.group('recid'))
            custom_variables = """
_paq.push(['setCustomVariable',
          1, // Index, the number from 1 to 5 where this custom variable name is stored
          "Collection", // Name, the name of the variable
          "%(collection_name)s", // Value
          "page" // Scope of the custom variable
          ]);
          """ % {
                'collection_name': record_collection
            }

            if record_page_match.group('page_type'):
                custom_variables += """
_paq.push(['setCustomVariable',
          2,
          "Type",
          "%(page_type)s",
          "page"
          ]);
_paq.push(['setCustomVariable',
          3,
          "CollectionType",
          "%(page_collection_type)s",
          "page"
          ]);
          """ % {
                    'page_type':
                    record_page_match.group('page_type'),
                    'page_collection_type':
                    record_collection + record_page_match.group('page_type')
                }

        out = """
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/terms-of-use">%(msg_terms)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/privacy-policy">%(msg_privacy)s</a>
  <br />
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
 </div>
 <div class="pagefooterstriperight">
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>
<!-- Piwik -->
 <script type="text/javascript">
 var _paq = _paq || [];
 (function(){ var u=(("https:" == document.location.protocol) ? "https://inspirehep.net/piwik/" : "http://inspirehep.net/piwik/");
 _paq.push(['setSiteId', '8']);
 %(custom_variables)s
 _paq.push(['setTrackerUrl', u+'piwik.php']);
 _paq.push(['trackPageView']);
 _paq.push(['enableLinkTracking']);
 var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.defer=true; g.async=true; g.src=u+'piwik.js';
 s.parentNode.insertBefore(g,s); })();
  </script>
  <noscript><p><img src="http://inspirehep.net/piwik/piwik.php?idsite=8" style="border:0" alt="" /></p></noscript>
  <!-- End Piwik Code -->
</body>
</html>
        """ % {
            'siteurl': CFG_BASE_URL,
            'sitesecureurl': CFG_SITE_SECURE_URL,
            'ln': ln,
            'langlink': '?ln=' + ln,
            'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
            'sitesupportemail': '*****@*****.**',
            'msg_search': _("Search"),
            'msg_help': _("Help"),
            'msg_terms': _("Terms of use"),
            'msg_privacy': _("Privacy policy"),
            'msg_poweredby': _("Powered by"),
            'msg_maintainedby': _("Problems/Questions to"),
            'msg_lastupdated': msg_lastupdated,
            'languagebox': self.tmpl_language_selection_box(req, ln),
            'version': self.trim_version(CFG_VERSION),
            'pagefooteradd': pagefooteradd,
            'custom_variables': custom_variables
        }
        return out
Example #35
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)

        argd['recid'] = self.recid

        argd['tab'] = self.tab

        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

        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')

        from invenio.search_engine import record_exists, get_merged_recid
        # check if the current record has been deleted
        # and has been merged, case in which the deleted record
        # will be redirect to the new one
        record_status = record_exists(argd['recid'])
        merged_recid = get_merged_recid(argd['recid'])
        if record_status == -1 and merged_recid:
            url = CFG_SITE_URL + '/' + CFG_SITE_RECORD + '/%s?ln=%s'
            url %= (str(merged_recid), argd['ln'])
            redirect_to_url(req, url)

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if out == []:
            return str(out)
        else:
            return out
Example #36
0
    def add(self, req, form):
        """
        Add a comment (review) to record with id recid where recid>0
        Also works for adding a remark to basket with id recid where recid<-99
        @param ln: languange
        @param recid: record id
        @param action:  'DISPLAY' to display add form
                        'SUBMIT' to submit comment once form is filled
                        'REPLY' to reply to an already existing comment
        @param msg: the body of the comment/review or remark
        @param score: star score of the review
        @param note: title of the review
        @param comid: comment id, needed for replying
        @param editor_type: the type of editor used for submitting the
                            comment: 'textarea', 'ckeditor'.
        @param subscribe: if set, subscribe user to receive email
                          notifications when new comment are added to
                          this discussion
        @return the full html page.
        """
        argd = wash_urlargd(
            form, {
                'action': (str, "DISPLAY"),
                'msg': (str, ""),
                'note': (str, ''),
                'score': (int, 0),
                'comid': (int, 0),
                'editor_type': (str, ""),
                'subscribe': (str, ""),
                'cookie': (str, "")
            })
        _ = gettext_set_language(argd['ln'])

        actions = ['DISPLAY', 'REPLY', 'SUBMIT']
        uid = getUid(req)

        # Is site ready to accept comments?
        if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS
                         and not CFG_WEBCOMMENT_ALLOW_REVIEWS):
            return page_not_authorized(req,
                                       "../comments/add",
                                       navmenuid='search')

        # Is user allowed to post comment?
        user_info = collect_user_info(req)
        (auth_code_1,
         auth_msg_1) = check_user_can_view_comments(user_info, self.recid)
        (auth_code_2,
         auth_msg_2) = check_user_can_send_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            # Save user's value in cookie, so that these "POST"
            # parameters are not lost during login process
            msg_cookie = mail_cookie_create_common(
                'comment_msg', {
                    'msg': argd['msg'],
                    'note': argd['note'],
                    'score': argd['score'],
                    'editor_type': argd['editor_type'],
                    'subscribe': argd['subscribe']
                },
                onetime=True)
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {})
            return redirect_to_url(req, target, norobot=True)
        elif (auth_code_1 or auth_code_2):
            return page_not_authorized(req, "../", \
                text = auth_msg_1 + auth_msg_2)

        user_info = collect_user_info(req)
        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        warning_msgs = [
        ]  # list of warning tuples (warning_text, warning_color)
        added_files = {}
        if can_attach_files:
            # User is allowed to attach files. Process the files
            file_too_big = False
            formfields = form.get('commentattachment[]', [])
            if not hasattr(formfields,
                           "__getitem__"):  # A single file was uploaded
                formfields = [formfields]
            for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]:
                if hasattr(formfield, "filename") and formfield.filename:
                    filename = formfield.filename
                    dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment',
                                               str(uid))
                    try:
                        assert (dir_to_open.startswith(CFG_TMPDIR))
                    except AssertionError:
                        register_exception(req=req,
                                           prefix='User #%s tried to upload file to forbidden location: %s' \
                                           % (uid, dir_to_open))

                    if not os.path.exists(dir_to_open):
                        try:
                            os.makedirs(dir_to_open)
                        except:
                            register_exception(req=req, alert_admin=True)

                    ## Before saving the file to disc, wash the filename (in particular
                    ## washing away UNIX and Windows (e.g. DFS) paths):
                    filename = os.path.basename(filename.split('\\')[-1])
                    filename = filename.strip()
                    if filename != "":
                        # Check that file does not already exist
                        n = 1
                        while os.path.exists(
                                os.path.join(dir_to_open, filename)):
                            basedir, name, extension = decompose_file(filename)
                            new_name = propose_next_docname(name)
                            filename = new_name + extension

                        fp = open(os.path.join(dir_to_open, filename), "w")
                        # FIXME: temporary, waiting for wsgi handler to be
                        # fixed. Once done, read chunk by chunk
                        ##                         while formfield.file:
                        ##                             fp.write(formfield.file.read(10240))
                        fp.write(formfield.file.read())
                        fp.close()
                        # Isn't this file too big?
                        file_size = os.path.getsize(
                            os.path.join(dir_to_open, filename))
                        if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \
                               file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE:
                            os.remove(os.path.join(dir_to_open, filename))
                            # One file is too big: record that,
                            # dismiss all uploaded files and re-ask to
                            # upload again
                            file_too_big = True
                            try:
                                raise InvenioWebCommentWarning(
                                    _('The size of file \\"%s\\" (%s) is larger than maximum allowed file size (%s). Select files again.'
                                      ) %
                                    (cgi.escape(filename),
                                     str(file_size / 1024) + 'KB',
                                     str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE /
                                         1024) + 'KB'))
                            except InvenioWebCommentWarning, exc:
                                register_exception(stream='warning')
                                warning_msgs.append((exc.message, ''))
                            #warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB'))
                        else:
                            added_files[filename] = os.path.join(
                                dir_to_open, filename)

            if file_too_big:
                # One file was too big. Removed all uploaded filed
                for filepath in added_files.items():
                    try:
                        os.remove(filepath)
                    except:
                        # File was already removed or does not exist?
                        pass
Example #37
0
    def __call__(self, req, form):
        """ Perform a search. """
        argd = wash_search_urlargd(form)

        _ = gettext_set_language(argd['ln'])

        if req.method == 'POST':
            raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

        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 area."),
                                       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

        involved_collections = set()
        involved_collections.update(argd['c'])
        involved_collections.add(argd['cc'])

        if argd['id'] > 0:
            argd['recid'] = argd['id']
        if argd['idb'] > 0:
            argd['recidb'] = argd['idb']
        if argd['sysno']:
            tmp_recid = find_record_from_sysno(argd['sysno'])
            if tmp_recid:
                argd['recid'] = tmp_recid
        if argd['sysnb']:
            tmp_recid = find_record_from_sysno(argd['sysnb'])
            if tmp_recid:
                argd['recidb'] = tmp_recid

        if argd['recid'] > 0:
            if argd['recidb'] > argd['recid']:
                # Hack to check if among the restricted collections
                # at least a record of the range is there and
                # then if the user is not authorized for that
                # collection.
                recids = intbitset(xrange(argd['recid'], argd['recidb']))
                restricted_collection_cache.recreate_cache_if_needed()
                for collname in restricted_collection_cache.cache:
                    (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=collname)
                    if auth_code and user_info['email'] == 'guest':
                        coll_recids = get_collection(collname).reclist
                        if coll_recids & recids:
                            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : collname})
                            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')
            else:
                involved_collections.add(guess_primary_collection_of_a_record(argd['recid']))

        # If any of the collection requires authentication, redirect
        # to the authentication form.
        for coll in involved_collections:
            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

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if out == []:
            return str(out)
        else:
            return out
    def vote(self, req, form):
        """
        Vote positively or negatively for a comment/review.
        @param comid: comment/review id
        @param com_value:   +1 to vote positively
                            -1 to vote negatively
        @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),
                'com_value': (int, 0),
                'recid': (int, -1),
                'do': (str, "od"),
                'ds': (str, "all"),
                'nb': (int, 100),
                'p': (int, 1),
                'referer': (str, None)
            })
        _ = gettext_set_language(argd['ln'])
        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 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 + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        # Check that comment belongs to this recid
        if not check_comment_belongs_to_record(argd['comid'], self.recid):
            return page_not_authorized(req, "../", \
                                       text = _("Specified comment does not belong to this record"))

        # Check that user can access the record
        (auth_code,
         auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
        if auth_code:
            return page_not_authorized(req, "../", \
                                       text = _("You do not have access to the specified comment"))

        # Check that comment is not currently deleted
        if is_comment_deleted(argd['comid']):
            return page_not_authorized(req, "../", \
                                       text = _("You cannot vote for a deleted comment"),
                                       ln=argd['ln'])

        success = perform_request_vote(argd['comid'], client_ip_address,
                                       argd['com_value'], uid)
        if argd['referer']:
            argd['referer'] += "?ln=%s&do=%s&ds=%s&nb=%s&p=%s&voted=%s&" % (
                argd['ln'], argd['do'], argd['ds'], argd['nb'], argd['p'],
                success)
            redirect_to_url(req, argd['referer'])
        else:
            #Note: sent to comments display
            referer = "%s/%s/%s/%s?&ln=%s&voted=1"
            referer %= (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid,
                        self.discussion == 1 and 'reviews'
                        or 'comments', argd['ln'])
            redirect_to_url(req, referer)
Example #39
0
    def tmpl_alert_email_body(self, name, url, records, pattern, collection_list, frequency, add_to_basket_p):

        recids_by_collection = {}
        for recid in records[0]:
            primary_collection = guess_primary_collection_of_a_record(recid)
            if primary_collection in collection_list:
                if not recids_by_collection.has_key(primary_collection):
                    recids_by_collection[primary_collection] = []
                recids_by_collection[primary_collection].append(recid)
            else:
                ancestors = get_coll_ancestors(primary_collection)
                ancestors.reverse()
                nancestors = 0
                for ancestor in ancestors:
                    nancestors += 1
                    if ancestor in collection_list:
                        if not recids_by_collection.has_key(ancestor):
                            recids_by_collection[ancestor] = []
                        recids_by_collection[ancestor].append(recid)
                        break
                    elif len(ancestors) == nancestors:
                        if not recids_by_collection.has_key("None of the above"):
                            recids_by_collection["None of the above"] = []
                        recids_by_collection["None of the above"].append(recid)

        collection_list = [coll for coll in recids_by_collection.keys() if coll != "None of the above"]
        for external_collection_results in records[1][0]:
            if external_collection_results[1][0]:
                collection_list.append(external_collection_results[0])

        l = len(collection_list)
        if l == 0:
            collections = ""
        elif l == 1:
            collections = "collection: %s\n" % collection_list[0]
        else:
            collections = "collections: %s\n" % wrap(", ".join(collection_list))

        l = len(records[0])
        for external_collection_results in records[1][0]:
            l += len(external_collection_results[1][0])
        if l == 1:
            total = "1 record"
        else:
            total = "%d records" % l

        if pattern:
            pattern = "pattern: %s\n" % pattern

        frequency = {"day": "daily", "week": "weekly", "month": "monthly"}[frequency]

        body = """\
Hello:

Below are the results of the email notification alert that
you set up with the %(sitename)s.
This is an automatic message, please don't reply to it.
For any question, please use <%(sitesupportemail)s> instead.

alert name: %(name)s
%(pattern)s%(collections)sfrequency: %(frequency)s
run time: %(runtime)s
found: %(total)s
url: <%(url)s>
""" % {
            "sitesupportemail": CFG_SITE_SUPPORT_EMAIL,
            "name": name,
            "sitename": CFG_SITE_NAME,
            "pattern": pattern,
            "collections": collections,
            "frequency": frequency,
            "runtime": time.strftime("%a %Y-%m-%d %H:%M:%S"),
            "total": total,
            "url": url,
        }

        index = 0

        for collection_recids in recids_by_collection.items():
            if collection_recids[0] != "None of the above":
                body += "\nCollection: %s\n" % collection_recids[0]
                for recid in collection_recids[1]:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            if recids_by_collection.has_key("None of the above"):
                if len(recids_by_collection.keys()) > 1:
                    body += "\nNone of the above collections:\n"
                else:
                    # if the uncategorized collection is the only collection then present
                    # all the records as belonging to CFG_SITE_NAME
                    body += "\nCollection: %s\n" % CFG_SITE_NAME
                for recid in recids_by_collection["None of the above"]:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            for external_collection_results in records[1][0]:
                body += "\nCollection: %s\n" % external_collection_results[0]
                for recid in external_collection_results[1][0]:
                    index += 1
                    body += "\n%i) " % (index)
                    # TODO: extend function to accept xml_record!
                    body += self.tmpl_alert_email_record(xml_record=external_collection_results[1][1][recid])
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if l > CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            body += """
Only the first %s records were displayed. Please consult the search
URL given at the top of this email to see all the results.
""" % (
                CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL,
            )
            if add_to_basket_p:
                body += """
Only the first %s records were added to your basket. To manually add more
records please consult the search URL as described before.
""" % (
                    CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL,
                )

        body += """
--
%s Alert Service <%s>
Unsubscribe?  See <%s>
Need human intervention?  Contact <%s>
""" % (
            CFG_SITE_NAME,
            CFG_SITE_URL,
            CFG_SITE_URL + "/youralerts/list",
            CFG_SITE_SUPPORT_EMAIL,
        )

        return body
Example #40
0
    def _get(self, req, form):
        """
        Returns a file attached to a comment.

        Example:
        CFG_SITE_URL/CFG_SITE_RECORD/5953/comments/attachments/get/652/myfile.pdf
        where 652 is the comment ID
        """
        argd = wash_urlargd(form, {'file': (str, None), 'comid': (int, 0)})
        _ = gettext_set_language(argd['ln'])

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check that user can view record, and its comments (protected
        # with action "viewcomment")
        (auth_code,
         auth_msg) = check_user_can_view_comments(user_info, self.recid)
        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 = '/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)

        # Does comment exist?
        if not query_get_comment(argd['comid']):
            req.status = apache.HTTP_NOT_FOUND
            return page(title=_("Page Not Found"),
                        body=_('The requested comment could not be found'),
                        req=req)

        # Check that user can view this particular comment, protected
        # using its own restriction
        (auth_code,
         auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
        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 = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        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/data/comments/' + \
                                   str(self.recid) + '/'  + str(argd['comid']) + \
                                   '/' + argd['file'])

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

        # Send error 404 in all other cases
        req.status = apache.HTTP_NOT_FOUND
        return page(title=_("Page Not Found"),
                    body=_('The requested file could not be found'),
                    req=req,
                    language=argd['ln'])
    def display(self, req, form):
        """
        Display the linkbacks of a record and admin approve/reject features
        """
        argd = wash_urlargd(form, {})

        _ = gettext_set_language(argd['ln'])

        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code,
         auth_msg) = check_user_can_view_linkbacks(user_info, 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'])

        show_admin = False
        (auth_code, auth_msg) = acc_authorize_action(
            req,
            'moderatelinkbacks',
            collection=guess_primary_collection_of_a_record(self.recid))
        if not auth_code:
            show_admin = True

        body = perform_request_display_record_linbacks(
            req,
            self.recid,
            show_admin,
            weblinkback_templates=weblinkback_templates,
            ln=argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(
            req, self.recid, argd['ln'])[0]

        # navigation, tabs, top and bottom part
        navtrail = create_navtrail_links(
            cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        if navtrail:
            navtrail += ' &gt; '
        navtrail += '<a class="navtrail" href="%s/%s/%s?ln=%s">' % (
            CFG_SITE_URL, CFG_SITE_RECORD, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'
        navtrail += ' &gt; <a class="navtrail">Linkbacks</a>'

        mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader(
        )

        unordered_tabs = get_detailed_page_tabs(get_colID(
            guess_primary_collection_of_a_record(self.recid)),
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                     '%s/%s/%s/%s%s' % (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \
                     tab_id in ['linkbacks'],
                     unordered_tabs[tab_id]['enabled']) \
                     for (tab_id, values) in ordered_tabs_id
                     if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(
            self.recid, tabs, argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(
            self.recid, tabs, argd['ln'])

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              metaheaderadd = mathjaxheader + jqueryheader,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
               top + body + bottom + \
               websearch_templates.tmpl_search_pageend(argd['ln']) + \
               pagefooteronly(language=argd['ln'], req=req)
Example #42
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
    def tmpl_pagefooter(self, req=None, ln=CFG_SITE_LANG, lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

        Parameters:

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

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

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

        Output:

        - HTML code of the page headers
        """
        from invenio.search_engine import guess_primary_collection_of_a_record

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

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

        # Prepare Piwik custom variables if we are in a detailed record page
        record_page_re = re.compile("^/record/(?P<recid>[0-9]+)/?(?P<page_type>.*)")

        custom_variables = ""

        record_page_match = record_page_re.match(req.uri)
        if record_page_match:
          record_collection = guess_primary_collection_of_a_record(record_page_match.group('recid'))
          custom_variables = """
_paq.push(['setCustomVariable',
          1, // Index, the number from 1 to 5 where this custom variable name is stored
          "Collection", // Name, the name of the variable
          "%(collection_name)s", // Value
          "page" // Scope of the custom variable
          ]);
          """ % {
            'collection_name': record_collection
          }

          if record_page_match.group('page_type'):
            custom_variables += """
_paq.push(['setCustomVariable',
          2,
          "Type",
          "%(page_type)s",
          "page"
          ]);
_paq.push(['setCustomVariable',
          3,
          "CollectionType",
          "%(page_collection_type)s",
          "page"
          ]);
          """ % {
            'page_type': record_page_match.group('page_type'),
            'page_collection_type': record_collection + record_page_match.group('page_type')
          }

        out = """
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/terms-of-use">%(msg_terms)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/privacy-policy">%(msg_privacy)s</a>
  <br />
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
 </div>
 <div class="pagefooterstriperight">
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>
<!-- Piwik -->
 <script type="text/javascript">
 var _paq = _paq || [];
 (function(){ var u=(("https:" == document.location.protocol) ? "https://inspirehep.net/piwik/" : "http://inspirehep.net/piwik/");
 _paq.push(['setSiteId', '8']);
 %(custom_variables)s
 _paq.push(['setTrackerUrl', u+'piwik.php']);
 _paq.push(['trackPageView']);
 _paq.push(['enableLinkTracking']);
 var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.defer=true; g.async=true; g.src=u+'piwik.js';
 s.parentNode.insertBefore(g,s); })();
  </script>
  <noscript><p><img src="http://inspirehep.net/piwik/piwik.php?idsite=8" style="border:0" alt="" /></p></noscript>
  <!-- End Piwik Code -->
</body>
</html>
        """ % {
          'siteurl' : CFG_BASE_URL,
          'sitesecureurl' : CFG_SITE_SECURE_URL,
          'ln' : ln,
          'langlink': '?ln=' + ln,

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

          'msg_search' : _("Search"),
          'msg_help' : _("Help"),

          'msg_terms': _("Terms of use"),
          'msg_privacy': _("Privacy policy"),

          'msg_poweredby' : _("Powered by"),
          'msg_maintainedby' : _("Problems/Questions to"),

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

          'pagefooteradd' : pagefooteradd,
          'custom_variables': custom_variables
          }
        return out
Example #44
0
    def add(self, req, form):
        """
        Add a comment (review) to record with id recid where recid>0
        Also works for adding a remark to basket with id recid where recid<-99
        @param ln: languange
        @param recid: record id
        @param action:  'DISPLAY' to display add form
                        'SUBMIT' to submit comment once form is filled
                        'REPLY' to reply to an already existing comment
        @param msg: the body of the comment/review or remark
        @param score: star score of the review
        @param note: title of the review
        @param comid: comment id, needed for replying
        @param editor_type: the type of editor used for submitting the
                            comment: 'textarea', 'fckeditor'.
        @param subscribe: if set, subscribe user to receive email
                          notifications when new comment are added to
                          this discussion
        @return the full html page.
        """
        argd = wash_urlargd(
            form, {
                'action': (str, "DISPLAY"),
                'msg': (str, ""),
                'note': (str, ''),
                'score': (int, 0),
                'comid': (int, 0),
                'editor_type': (str, ""),
                'subscribe': (str, ""),
                'cookie': (str, "")
            })
        _ = gettext_set_language(argd['ln'])

        actions = ['DISPLAY', 'REPLY', 'SUBMIT']
        uid = getUid(req)

        # Is site ready to accept comments?
        if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS
                         and not CFG_WEBCOMMENT_ALLOW_REVIEWS):
            return page_not_authorized(req,
                                       "../comments/add",
                                       navmenuid='search')

        # Is user allowed to post comment?
        user_info = collect_user_info(req)
        (auth_code_1,
         auth_msg_1) = check_user_can_view_comments(user_info, self.recid)
        (auth_code_2,
         auth_msg_2) = check_user_can_send_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            # Save user's value in cookie, so that these "POST"
            # parameters are not lost during login process
            msg_cookie = mail_cookie_create_common(
                'comment_msg', {
                    'msg': argd['msg'],
                    'note': argd['note'],
                    'score': argd['score'],
                    'editor_type': argd['editor_type'],
                    'subscribe': argd['subscribe']
                },
                onetime=True)
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {})
            return redirect_to_url(req, target, norobot=True)
        elif (auth_code_1 or auth_code_2):
            return page_not_authorized(req, "../", \
                text = auth_msg_1 + auth_msg_2)

        if argd['comid']:
            # If replying to a comment, are we on a record that
            # matches the original comment user is replying to?
            if not check_comment_belongs_to_record(argd['comid'], self.recid):
                return page_not_authorized(req, "../", \
                                           text = _("Specified comment does not belong to this record"))

            # Is user trying to reply to a restricted comment? Make
            # sure user has access to it.  We will then inherit its
            # restriction for the new comment
            (auth_code,
             auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
            if auth_code:
                return page_not_authorized(req, "../", \
                                           text = _("You do not have access to the specified comment"))

            # Is user trying to reply to a deleted comment? If so, we
            # let submitted comment go (to not lose possibly submitted
            # content, if comment is submitted while original is
            # deleted), but we "reset" comid to make sure that for
            # action 'REPLY' the original comment is not included in
            # the reply
            if is_comment_deleted(argd['comid']):
                argd['comid'] = 0

        user_info = collect_user_info(req)
        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        warning_msgs = []
        added_files = {}
        if can_attach_files:
            # User is allowed to attach files. Process the files
            file_too_big = False
            formfields = form.get('commentattachment[]', [])
            if not hasattr(formfields,
                           "__getitem__"):  # A single file was uploaded
                formfields = [formfields]
            for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]:
                if hasattr(formfield, "filename") and formfield.filename:
                    filename = formfield.filename
                    dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment',
                                               str(uid))
                    try:
                        assert (dir_to_open.startswith(CFG_TMPDIR))
                    except AssertionError:
                        register_exception(req=req,
                                           prefix='User #%s tried to upload file to forbidden location: %s' \
                                           % (uid, dir_to_open))

                    if not os.path.exists(dir_to_open):
                        try:
                            os.makedirs(dir_to_open)
                        except:
                            register_exception(req=req, alert_admin=True)

                    ## Before saving the file to disc, wash the filename (in particular
                    ## washing away UNIX and Windows (e.g. DFS) paths):
                    filename = os.path.basename(filename.split('\\')[-1])
                    filename = filename.strip()
                    if filename != "":
                        # Check that file does not already exist
                        n = 1
                        while os.path.exists(
                                os.path.join(dir_to_open, filename)):
                            basedir, name, extension = decompose_file(filename)
                            new_name = propose_next_docname(name)
                            filename = new_name + extension

                        fp = open(os.path.join(dir_to_open, filename), "w")
                        # FIXME: temporary, waiting for wsgi handler to be
                        # fixed. Once done, read chunk by chunk
                        ##                         while formfield.file:
                        ##                             fp.write(formfield.file.read(10240))
                        fp.write(formfield.file.read())
                        fp.close()
                        # Isn't this file too big?
                        file_size = os.path.getsize(
                            os.path.join(dir_to_open, filename))
                        if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \
                               file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE:
                            os.remove(os.path.join(dir_to_open, filename))
                            # One file is too big: record that,
                            # dismiss all uploaded files and re-ask to
                            # upload again
                            file_too_big = True
                            warning_msgs.append(
                                ('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED',
                                 cgi.escape(filename),
                                 str(file_size / 1024) + 'KB',
                                 str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE / 1024)
                                 + 'KB'))
                        else:
                            added_files[filename] = os.path.join(
                                dir_to_open, filename)

            if file_too_big:
                # One file was too big. Removed all uploaded filed
                for filepath in added_files.items():
                    try:
                        os.remove(filepath)
                    except:
                        # File was already removed or does not exist?
                        pass

        client_ip_address = req.remote_ip
        check_warnings = []
        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings,
                                                argd['ln'])
        if ok:
            title, description, keywords = websearch_templates.tmpl_record_page_header_content(
                req, self.recid, argd['ln'])
            navtrail = create_navtrail_links(
                cc=guess_primary_collection_of_a_record(self.recid))
            # Infoscience modification
            navtrail += '<li><a href="%s/record/%s?ln=%s">%s</a></li>' % (
                CFG_SITE_URL, self.recid, argd['ln'], title)
            navtrail += '<li class="last">%s</li>' % (
                self.discussion == 1 and _('Reviews') or _('Comments'))

            if argd['action'] not in actions:
                argd['action'] = 'DISPLAY'

            if not argd['msg']:
                # User had to login in-between, so retrieve msg
                # from cookie
                try:
                    (kind,
                     cookie_argd) = mail_cookie_check_common(argd['cookie'],
                                                             delete=True)

                    argd.update(cookie_argd)
                except InvenioWebAccessMailCookieDeletedError, e:
                    return redirect_to_url(req, CFG_SITE_URL + '/record/' + \
                                           str(self.recid) + (self.discussion==1 and \
                                                              '/reviews' or '/comments'))
                except InvenioWebAccessMailCookieError, e:
                    # Invalid or empty cookie: continue
                    pass
Example #45
0
    def tmpl_pagefooter(self,
                        req=None,
                        ln=CFG_SITE_LANG,
                        lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

        Parameters:

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

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

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

        Output:

        - HTML code of the page headers
        """
        from invenio.search_engine import guess_primary_collection_of_a_record

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

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

        # Prepare Piwik custom variables if we are in a detailed record page

        custom_variables = ""
        record_collection = ""
        page_type = ""

        parsed_uri = urlparse(req.unparsed_uri)

        # HACK: I know it's horrible code. :-(
        record_page_match = re.match(
            "^/record/(?P<recid>[0-9]+)(/(?P<page_type>.+)?)?$",
            parsed_uri.path)
        if record_page_match:
            record_collection = guess_primary_collection_of_a_record(
                record_page_match.group('recid'))
            page_type = record_page_match.group('page_type') or 'detailed'
        if re.match("^/search/?$", parsed_uri.path):
            cc = parse_qs(parsed_uri.query).get('cc', [CFG_SITE_NAME])
            record_collection = cc.pop()
        collection_page_match = re.match(
            "^/$|^/collection/(?P<collection>.+)/?$", parsed_uri.path)
        if collection_page_match:
            record_collection = collection_page_match.groupdict().get(
                'collection', CFG_SITE_NAME)
        if record_collection:
            custom_variables = """\
_paq.push(['setCustomVariable',
          1, // Index, the number from 1 to 5 where this custom variable name is stored
          "Collection", // Name, the name of the variable
          %(collection_name)s, // Value
          "page" // Scope of the custom variable
          ]);
          """ % {
                'collection_name': js_escape(record_collection)
            }

        if page_type:
            custom_variables += """\
_paq.push(['setCustomVariable',
          2,
          "Type",
          %(page_type)s,
          "page"
          ]);
_paq.push(['setCustomVariable',
          3,
          "CollectionType",
          %(page_collection_type)s,
          "page"
          ]);
          """ % {
                'page_type': js_escape(page_type),
                'page_collection_type':
                js_escape(record_collection + page_type)
            }

        out = """\
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/terms-of-use">%(msg_terms)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/privacy-policy">%(msg_privacy)s</a>
  <br />
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
 </div>
 <div class="pagefooterstriperight">
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>
""" % {
            'siteurl': CFG_BASE_URL,
            'sitesecureurl': CFG_SITE_SECURE_URL,
            'ln': ln,
            'langlink': '?ln=' + ln,
            'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
            'sitesupportemail': '*****@*****.**',
            'msg_search': _("Search"),
            'msg_help': _("Help"),
            'msg_terms': _("Terms of use"),
            'msg_privacy': _("Privacy policy"),
            'msg_poweredby': _("Powered by"),
            'msg_maintainedby': _("Problems/Questions to"),
            'msg_lastupdated': msg_lastupdated,
            'languagebox': self.tmpl_language_selection_box(req, ln),
            'version': self.trim_version(CFG_VERSION),
            'pagefooteradd': pagefooteradd,
        }
        if not isUserAdmin(collect_user_info(req)):
            out += """\
<!-- Piwik -->
<script type="text/javascript">
  try {
    var _paq = _paq || [];
    _paq.push(['trackPageView']);
    _paq.push(['enableLinkTracking']);
    (function() {
        var u="//piwik.inspirehep.net/";
        _paq.push(['setTrackerUrl', u+'piwik.php']);
        _paq.push(['setSiteId', 8]);
        %(custom_variables)s
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
    })();}
    catch(err) {
        (function() {
            var img = document.createElement('img');
            img.src = '//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1';
            document.body.appendChild(img);
    })();
    }
</script>
<noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
""" % {
                'custom_variables': custom_variables
            }

        out += """\
</body>
</html>
"""
        return out
    def add(self, req, form):
        """
        Add a comment (review) to record with id recid where recid>0
        Also works for adding a remark to basket with id recid where recid<-99
        @param ln: languange
        @param recid: record id
        @param action:  'DISPLAY' to display add form
                        'SUBMIT' to submit comment once form is filled
                        'REPLY' to reply to an already existing comment
        @param msg: the body of the comment/review or remark
        @param score: star score of the review
        @param note: title of the review
        @param comid: comment id, needed for replying
        @param editor_type: the type of editor used for submitting the
                            comment: 'textarea', 'fckeditor'.
        @param subscribe: if set, subscribe user to receive email
                          notifications when new comment are added to
                          this discussion
        @return the full html page.
        """
        argd = wash_urlargd(form, {'action': (str, "DISPLAY"),
                                   'msg': (str, ""),
                                   'note': (str, ''),
                                   'score': (int, 0),
                                   'comid': (int, -1),
                                   'editor_type': (str, ""),
                                   'subscribe': (str, ""),
                                   'cookie': (str, "")
                                   })
        _ = gettext_set_language(argd['ln'])

        actions = ['DISPLAY', 'REPLY', 'SUBMIT']
        uid = getUid(req)

        # Is site ready to accept comments?
        if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS and not CFG_WEBCOMMENT_ALLOW_REVIEWS):
            return page_not_authorized(req, "../comments/add",
                                       navmenuid='search')

        # Is user allowed to post comment?
        user_info = collect_user_info(req)
        (auth_code_1, auth_msg_1) = check_user_can_view_comments(user_info, self.recid)
        (auth_code_2, auth_msg_2) = check_user_can_send_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            # Save user's value in cookie, so that these "POST"
            # parameters are not lost during login process
            msg_cookie = mail_cookie_create_common('comment_msg',
                                                    {'msg': argd['msg'],
                                                     'note': argd['note'],
                                                     'score': argd['score'],
                                                     'editor_type': argd['editor_type'],
                                                     'subscribe': argd['subscribe']},
                                                    onetime=True)
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {})
            return redirect_to_url(req, target, norobot=True)
        elif (auth_code_1 or auth_code_2):
            return page_not_authorized(req, "../", \
                text = auth_msg_1 + auth_msg_2)

        user_info = collect_user_info(req)
        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest' or user_info['apache_user']):
            can_attach_files = True

        warning_msgs = []
        added_files = {}
        if can_attach_files:
            # User is allowed to attach files. Process the files
            file_too_big = False
            formfields = form.get('commentattachment[]', [])
            if not hasattr(formfields, "__getitem__"): # A single file was uploaded
                formfields = [formfields]
            for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]:
                if hasattr(formfield, "filename") and formfield.filename:
                    filename = formfield.filename
                    dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment', str(uid))
                    try:
                        assert(dir_to_open.startswith(CFG_TMPDIR))
                    except AssertionError:
                        register_exception(req=req,
                                           prefix='User #%s tried to upload file to forbidden location: %s' \
                                           % (uid, dir_to_open))

                    if not os.path.exists(dir_to_open):
                        try:
                            os.makedirs(dir_to_open)
                        except:
                            register_exception(req=req, alert_admin=True)

                    ## Before saving the file to disc, wash the filename (in particular
                    ## washing away UNIX and Windows (e.g. DFS) paths):
                    filename = os.path.basename(filename.split('\\')[-1])
                    filename = filename.strip()
                    if filename != "":
                        # Check that file does not already exist
                        n = 1
                        while os.path.exists(os.path.join(dir_to_open, filename)):
                            basedir, name, extension = decompose_file(filename)
                            new_name = propose_next_docname(name)
                            filename = new_name + extension

                        fp = open(os.path.join(dir_to_open, filename), "w")
                        # FIXME: temporary, waiting for wsgi handler to be
                        # fixed. Once done, read chunk by chunk
##                         while formfield.file:
##                             fp.write(formfield.file.read(10240))
                        fp.write(formfield.file.read())
                        fp.close()
                        # Isn't this file too big?
                        file_size = os.path.getsize(os.path.join(dir_to_open, filename))
                        if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \
                               file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE:
                            os.remove(os.path.join(dir_to_open, filename))
                            # One file is too big: record that,
                            # dismiss all uploaded files and re-ask to
                            # upload again
                            file_too_big = True
                            warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB'))
                        else:
                            added_files[filename] = os.path.join(dir_to_open, filename)

            if file_too_big:
                # One file was too big. Removed all uploaded filed
                for filepath in added_files.items():
                    try:
                        os.remove(filepath)
                    except:
                        # File was already removed or does not exist?
                        pass

        client_ip_address = req.remote_ip
        check_warnings = []
        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln'])
        if ok:
            title, description, keywords = websearch_templates.tmpl_record_page_header_content(req,
                                                                                               self.recid,
                                                                                               argd['ln'])
            navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid))
            if navtrail:
                navtrail += ' &gt; '
            navtrail += '<a class="navtrail" href="%s/record/%s?ln=%s">'% (CFG_SITE_URL, self.recid, argd['ln'])
            navtrail += title
            navtrail += '</a>'
            navtrail += '&gt; <a class="navtrail" href="%s/record/%s/%s/?ln=%s">%s</a>' % (CFG_SITE_URL,
                                                                                           self.recid,
                                                                                           self.discussion==1 and 'reviews' or 'comments',
                                                                                           argd['ln'],
                                                                                           self.discussion==1 and _('Reviews') or _('Comments'))

            if argd['action'] not in actions:
                argd['action'] = 'DISPLAY'

            if not argd['msg']:
                # User had to login in-between, so retrieve msg
                # from cookie
                try:
                    (kind, cookie_argd) = mail_cookie_check_common(argd['cookie'],
                                                                    delete=True)

                    argd.update(cookie_argd)
                except InvenioWebAccessMailCookieDeletedError, e:
                    return redirect_to_url(req, CFG_SITE_URL + '/record/' + \
                                           str(self.recid) + (self.discussion==1 and \
                                                              '/reviews' or '/comments'))
                except InvenioWebAccessMailCookieError, e:
                    # Invalid or empty cookie: continue
                    pass
    def display(self, req, form):
        """
        Show the tab 'holdings'.
        """

        argd = wash_urlargd(form, {'do': (str, "od"),
                                   'ds': (str, "all"),
                                   'nb': (int, 100),
                                   'p': (int, 1),
                                   'voted': (int, -1),
                                   'reported': (int, -1),
                                   })
        _ = gettext_set_language(argd['ln'])

        record_exists_p = record_exists(self.recid)
        if record_exists_p != 1:
            if record_exists_p == -1:
                msg = _("The record has been deleted.")
            else:
                msg = _("Requested record does not seem to exist.")
            msg = '<span class="quicknote">' + msg + '</span>'
            title, description, keywords = \
                   websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])
            return page(title = title,
                        show_title_p = False,
                        body = msg,
                        description = description,
                        keywords = keywords,
                        uid = getUid(req),
                        language = argd['ln'],
                        req = req,
                        navmenuid='search')

        body = perform_get_holdings_information(self.recid, req, argd['ln'])

        uid = getUid(req)


        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)


        unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                    self.recid,
                                                    ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
        ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
        link_ln = ''
        if argd['ln'] != CFG_SITE_LANG:
            link_ln = '?ln=%s' % argd['ln']
        tabs = [(unordered_tabs[tab_id]['label'], \
                 '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                 tab_id in ['holdings'],
                 unordered_tabs[tab_id]['enabled']) \
                for (tab_id, _order) in ordered_tabs_id
                if unordered_tabs[tab_id]['visible'] == True]
        top = webstyle_templates.detailed_record_container_top(self.recid,
                                                               tabs,
                                                               argd['ln'])
        bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                     tabs,
                                                                     argd['ln'])

        title = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])[0]
        navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
        navtrail += ' &gt; <a class="navtrail" href="%s/record/%s?ln=%s">'% (CFG_SITE_URL, self.recid, argd['ln'])
        navtrail += title
        navtrail += '</a>'

        return pageheaderonly(title=title,
                              navtrail=navtrail,
                              uid=uid,
                              verbose=1,
                              req=req,
                              metaheaderadd = "<link rel=\"stylesheet\" href=\"%s/img/jquery-ui.css\" type=\"text/css\" />" % CFG_SITE_URL,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                              top + body + bottom + \
                              websearch_templates.tmpl_search_pageend(argd['ln']) + \
                              pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
    def display(self, req, form):
        """
        Display comments (reviews if enabled) associated with record having id recid where recid>0.
        This function can also be used to display remarks associated with basket having id recid where recid<-99.
        @param ln: language
        @param recid: record id, integer
        @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 voted: boolean, active if user voted for a review, see vote function
        @param reported: int, active if user reported a certain comment/review, see report function
        @param reviews: boolean, enabled for reviews, disabled for comments
        @param subscribed: int, 1 if user just subscribed to discussion, -1 if unsubscribed
        @return the full html page.
        """

        argd = wash_urlargd(form, {'do': (str, "od"),
                                   'ds': (str, "all"),
                                   'nb': (int, 100),
                                   'p': (int, 1),
                                   'voted': (int, -1),
                                   'reported': (int, -1),
                                   'subscribed': (int, 0),
                                   'cmtgrp': (list, ["latest"]) # 'latest' is now a reserved group/round name
                                   })

        _ = gettext_set_language(argd['ln'])
        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 and user_info['email'] == 'guest' and not user_info['apache_user']:
            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)

        can_send_comments = False
        (auth_code, auth_msg) = check_user_can_send_comments(user_info, self.recid)
        if not auth_code:
            can_send_comments = True

        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest' or user_info['apache_user']):
            can_attach_files = True

        subscription = get_user_subscription_to_discussion(self.recid, uid)
        if subscription == 1:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = True
        elif subscription == 2:
            user_is_subscribed_to_discussion = True
            user_can_unsubscribe_from_discussion = False
        else:
            user_is_subscribed_to_discussion = False
            user_can_unsubscribe_from_discussion = False

        #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"]
        display_comment_rounds = argd['cmtgrp']

        check_warnings = []

        (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln'])
        if ok:
            (body, errors, warnings) = perform_request_display_comments_or_remarks(req=req, recID=self.recid,
                display_order=argd['do'],
                display_since=argd['ds'],
                nb_per_page=argd['nb'],
                page=argd['p'],
                ln=argd['ln'],
                voted=argd['voted'],
                reported=argd['reported'],
                subscribed=argd['subscribed'],
                reviews=self.discussion,
                uid=uid,
                can_send_comments=can_send_comments,
                can_attach_files=can_attach_files,
                user_is_subscribed_to_discussion=user_is_subscribed_to_discussion,
                user_can_unsubscribe_from_discussion=user_can_unsubscribe_from_discussion,
                display_comment_rounds=display_comment_rounds
                )

            unordered_tabs = get_detailed_page_tabs(get_colID(guess_primary_collection_of_a_record(self.recid)),
                                                    self.recid,
                                                    ln=argd['ln'])
            ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()]
            ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1]))
            link_ln = ''
            if argd['ln'] != CFG_SITE_LANG:
                link_ln = '?ln=%s' % argd['ln']
            tabs = [(unordered_tabs[tab_id]['label'], \
                     '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \
                     tab_id in ['comments', 'reviews'],
                     unordered_tabs[tab_id]['enabled']) \
                    for (tab_id, order) in ordered_tabs_id
                    if unordered_tabs[tab_id]['visible'] == True]
            top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                    tabs,
                                                                    argd['ln'])
            bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                         tabs,
                                                                         argd['ln'])

            title, description, keywords = websearch_templates.tmpl_record_page_header_content(req, self.recid, argd['ln'])
            navtrail = create_navtrail_links(cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln'])
            if navtrail:
                navtrail += ' &gt; '
            navtrail += '<a class="navtrail" href="%s/record/%s?ln=%s">'% (CFG_SITE_URL, self.recid, argd['ln'])
            navtrail += title
            navtrail += '</a>'
            navtrail += ' &gt; <a class="navtrail">%s</a>' % (self.discussion==1 and _("Reviews") or _("Comments"))

            jsmathheader = ''
            if CFG_WEBCOMMENT_USE_JSMATH_IN_COMMENTS:
                jsmathheader = """ <script type='text/javascript'>
                                    jsMath = {
                                        Controls: {cookie: {printwarn: 0}}
                                    };
                                    </script>
                                    <script src='/jsMath/easy/invenio-jsmath.js' type='text/javascript'></script>
                               """
            jqueryheader = '''
            <script src="%(CFG_SITE_URL)s/js/jquery.min.js" type="text/javascript" language="javascript"></script>
            <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script>
            ''' % {'CFG_SITE_URL': CFG_SITE_URL}


            return pageheaderonly(title=title,
                        navtrail=navtrail,
                        uid=uid,
                        verbose=1,
                        metaheaderadd = jsmathheader + jqueryheader,
                        req=req,
                        language=argd['ln'],
                        navmenuid='search',
                        navtrail_append_title_p=0) + \
                    websearch_templates.tmpl_search_pagestart(argd['ln']) + \
                    top + body + bottom + \
                    websearch_templates.tmpl_search_pageend(argd['ln']) + \
                    pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req)
        else:
            return page(title=_("Record Not Found"),
                        body=problem,
                        uid=uid,
                        verbose=1,
                        req=req,
                        language=argd['ln'],
                        warnings=check_warnings, errors=[],
                        navmenuid='search')
    def decorated(recid, *args, **kwargs):
        # ensure recid to be integer
        recid = int(recid)
        g.collection = collection = Collection.query.filter(
            Collection.name == guess_primary_collection_of_a_record(recid)).\
            one()

        (auth_code, auth_msg) = check_user_can_view_record(current_user, recid)

        # only superadmins can use verbose parameter for obtaining debug information
        if not current_user.is_super_admin and 'verbose' in kwargs:
            kwargs['verbose'] = 0

        if auth_code and current_user.is_guest:
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL,
                {'collection': guess_primary_collection_of_a_record(recid)})
            url_args = {
                'action': cookie,
                'ln': g.ln,
                'referer': request.referrer
            }
            flash(_("Authorization failure"), 'error')
            return redirect(url_for('webaccount.login', **url_args))
        elif auth_code:
            flash(auth_msg, 'error')
            abort(apache.HTTP_UNAUTHORIZED)

        from invenio.search_engine import record_exists, get_merged_recid
        # check if the current record has been deleted
        # and has been merged, case in which the deleted record
        # will be redirect to the new one
        record_status = record_exists(recid)
        merged_recid = get_merged_recid(recid)
        if record_status == -1 and merged_recid:
            return redirect(url_for('record.metadata', recid=merged_recid))
        elif record_status == -1:
            abort(apache.HTTP_GONE)  # The record is gone!

        g.record = record = Bibrec.query.get(recid)
        user = None
        if not current_user.is_guest:
            user = User.query.get(current_user.get_id())
        title = get_fieldvalues(recid, '245__a')
        title = title[0] if len(title) > 0 else ''

        b = [(_('Home'), '')] + collection.breadcrumbs()[1:]
        b += [(title, 'record.metadata', dict(recid=recid))]
        current_app.config['breadcrumbs_map'][request.endpoint] = b
        g.record_tab_keys = []
        tabs = []
        counts = get_detailed_page_tabs_counts(recid)
        for k, v in get_detailed_page_tabs(collection.id, recid,
                                           g.ln).iteritems():
            t = {}
            b = 'record'
            if k == '':
                k = 'metadata'
            if k == 'comments' or k == 'reviews':
                b = 'webcomment'
            if k == 'linkbacks':
                b = 'weblinkback'
                k = 'index'

            t['key'] = b + '.' + k
            t['count'] = counts.get(k.capitalize(), -1)

            t.update(v)
            tabs.append(t)
            if v['visible']:
                g.record_tab_keys.append(b + '.' + k)

        if CFG_WEBLINKBACK_TRACKBACK_ENABLED:

            @register_template_context_processor
            def trackback_context():
                from invenio.weblinkback_templates import get_trackback_auto_discovery_tag
                return dict(headerLinkbackTrackbackLink=
                            get_trackback_auto_discovery_tag(recid))

        @register_template_context_processor
        def record_context():
            return dict(recid=recid,
                        record=record,
                        user=user,
                        tabs=tabs,
                        title=title,
                        get_mini_reviews=lambda *args, **kwargs:
                        get_mini_reviews(*args, **kwargs).decode('utf8'),
                        collection=collection,
                        format_record=lambda recID, of='hb', ln=g.ln:
                        format_record(recID,
                                      of=of,
                                      ln=ln,
                                      verbose=0,
                                      search_pattern='',
                                      on_the_fly=False))

        return f(recid, *args, **kwargs)
    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 and not user_info['apache_user']) 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/record/%s/%s/display?ln=%s&amp;voted=1"
            referer %= (CFG_SITE_URL, self.recid, self.discussion==1 and 'reviews' or 'comments', argd['ln'])
            redirect_to_url(req, referer)
Example #51
0
    def index(self, req, form):
        """Handle all BibMerge requests.
        The responsibilities of this functions are:
        * JSON decoding and encoding.
        * Redirection, if necessary.
        * Authorization.
        * Calling the appropriate function from the engine.
        """
        # If it is an Ajax request, extract any JSON data.
        ajax_request, recid1, recid2 = False, None, None
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        if form.has_key('jsondata'):
            json_data = json.loads(str(form['jsondata']))
            # Deunicode all strings (Invenio doesn't have unicode
            # support).
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}
            if json_data.has_key('recID1'):
                recid1 = json_data['recID1']
            if json_data.has_key('recID2'):
                recid2 = json_data['recID2']

        # 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):
                auth_code, auth_message = acc_authorize_action(
                    req, 'runbibmerge')
                referer = '/merge/'
                return page_not_authorized(req=req,
                                           referer=referer,
                                           text=auth_message,
                                           navtrail=navtrail)
            else:
                # Session has most likely timed out.
                json_response.update({
                    'resultCode': 1,
                    'resultText': 'Error: Not logged in'
                })
                return json.dumps(json_response)

        elif self.recid:
            # Handle RESTful call by storing recid and redirecting to
            # generic URL.
            redirect_to_url(req,
                            '%s/%s/merge/' % (CFG_SITE_URL, CFG_SITE_RECORD))

        if recid1 is not None:
            # Authorize access to record 1.
            auth_code, auth_message = acc_authorize_action(
                req,
                'runbibmerge',
                collection=guess_primary_collection_of_a_record(recid1))
            if auth_code != 0:
                json_response.update({
                    'resultCode':
                    1,
                    'resultText':
                    'No access to record %s' % recid1
                })
                return json.dumps(json_response)
        if recid2 is not None:
            # Authorize access to record 2.
            auth_code, auth_message = acc_authorize_action(
                req,
                'runbibmerge',
                collection=guess_primary_collection_of_a_record(recid2))
            if auth_code != 0:
                json_response.update({
                    'resultCode':
                    1,
                    'resultText':
                    'No access to record %s' % recid2
                })
                return json.dumps(json_response)

        # Handle request.
        uid = getUid(req)
        if not ajax_request:
            # Show BibEdit start page.
            body, errors, warnings = perform_request_init()
            metaheaderadd = """<script type="text/javascript" src="%(site)s/js/jquery.min.js"></script>
  <script type="text/javascript" src="%(site)s/js/json2.js"></script>
  <script type="text/javascript" src="%(site)s/js/bibmerge_engine.js"></script>""" % {
                'site': CFG_SITE_URL
            }
            title = 'Record Merger'
            return page(title=title,
                        metaheaderadd=metaheaderadd,
                        body=body,
                        errors=errors,
                        warnings=warnings,
                        uid=uid,
                        language=argd['ln'],
                        navtrail=navtrail,
                        lastupdated=__lastupdated__,
                        req=req)
        else:
            # Handle AJAX request.
            json_response = perform_request_ajax(req, uid, json_data)
            return json.dumps(json_response)
    def check_authorization_moderatelinkbacks(self, req, argd):
        """
        Check if user has authorization moderate linkbacks
        @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized
        """
        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatelinkbacks', collection = guess_primary_collection_of_a_record(self.recid))
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])
    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_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(-success), argd['ln'])
        redirect_to_url(req, display_url)
Example #54
0
    def tmpl_alert_email_body(self, name, description, url, records, pattern,
                              collection_list, frequency, add_to_basket_p):

        recids_by_collection = {}
        for recid in records[0]:
            primary_collection = guess_primary_collection_of_a_record(recid)
            if primary_collection in collection_list or \
                primary_collection == CFG_SITE_NAME: # common case, when the primary coll can not be guessed
                if not recids_by_collection.has_key(primary_collection):
                    recids_by_collection[primary_collection] = []
                recids_by_collection[primary_collection].append(recid)
            else:
                ancestors = get_coll_ancestors(primary_collection)
                ancestors.reverse()
                nancestors = 0
                for ancestor in ancestors:
                    nancestors += 1
                    if ancestor in collection_list:
                        if not recids_by_collection.has_key(ancestor):
                            recids_by_collection[ancestor] = []
                        recids_by_collection[ancestor].append(recid)
                        break
                    elif len(ancestors) == nancestors:
                        if not recids_by_collection.has_key('None of the above'):
                            recids_by_collection['None of the above'] = []
                        recids_by_collection['None of the above'].append(recid)

        collection_list = [coll for coll in recids_by_collection.keys() if coll != 'None of the above']
        for external_collection_results in records[1][0]:
            if external_collection_results[1][0]:
                collection_list.append(external_collection_results[0])

        l = len(collection_list)
        if l == 0:
            collections = ''
        elif l == 1:
            collections = "collection: %s\n" % collection_list[0]
        else:
            collections = "collections: %s\n" % wrap(', '.join(collection_list))

        l = len(records[0])
        for external_collection_results in records[1][0]:
            l += len(external_collection_results[1][0])
        if l == 1:
            total = '1 record'
        else:
            total = '%d records' % l

        if pattern:
            pattern = 'pattern: %s\n' % pattern

        frequency = {'day': 'daily',
                     'week': 'weekly',
                     'month': 'monthly'}[frequency]

        body = """\
Hello:

Below are the results of the email notification alert that
was set up with the %(sitename)s.
%(description)s
This is an automatic message, please don't reply to it.
For any question, please use <%(sitesupportemail)s> instead.

alert name: %(name)s
%(pattern)s%(collections)sfrequency: %(frequency)s
run time: %(runtime)s
found: %(total)s
url: <%(url)s>
""" % {'sitesupportemail': CFG_SITE_SUPPORT_EMAIL,
       'name': name,
       'sitename': CFG_SITE_NAME,
       'description': description and '\n' + description + '\n' or '',
       'pattern': pattern,
       'collections': collections,
       'frequency': frequency,
       'runtime': time.strftime("%a %Y-%m-%d %H:%M:%S"),
       'total': total,
       'url': url}

        index = 0

        for collection_recids in recids_by_collection.items():
            if collection_recids[0] != 'None of the above':
                body += "\nCollection: %s\n" % collection_recids[0]
                for recid in collection_recids[1]:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            if recids_by_collection.has_key('None of the above'):
                if len(recids_by_collection.keys()) > 1:
                    body += "\nNone of the above collections:\n"
                else:
                    # if the uncategorized collection is the only collection then present
                    # all the records as belonging to CFG_SITE_NAME
                    body += "\nCollection: %s\n" % CFG_SITE_NAME
                for recid in recids_by_collection['None of the above']:
                    index += 1
                    body += "\n%i) " % (index)
                    body += self.tmpl_alert_email_record(recid=recid)
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break

        if index < CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            for external_collection_results in records[1][0]:
                body += "\nCollection: %s\n" % external_collection_results[0]
                for recid in external_collection_results[1][0]:
                    index += 1
                    body += "\n%i) " % (index)
                    # TODO: extend function to accept xml_record!
                    body += self.tmpl_alert_email_record(xml_record=external_collection_results[1][1][recid])
                    body += "\n"
                    if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                        break
                if index == CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
                    break

        if l > CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL:
            body += '''
Only the first %s records were displayed. Please consult the search
URL given at the top of this email to see all the results.
''' % (CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL,)
            if add_to_basket_p:
                body += '''
Only the first %s records were added to your basket. To manually add more
records please consult the search URL as described before.
''' % (CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL,)


        body += '''
--
%s Alert Service <%s>
Unsubscribe?  See <%s>
Need human intervention?  Contact <%s>
''' % (CFG_SITE_NAME, CFG_SITE_URL, CFG_SITE_URL + '/youralerts/list', CFG_SITE_SUPPORT_EMAIL)

        return body
    def index(self, req, form):
        """Handle all BibMerge requests.
        The responsibilities of this functions are:
        * JSON decoding and encoding.
        * Redirection, if necessary.
        * Authorization.
        * Calling the appropriate function from the engine.
        """
        # If it is an Ajax request, extract any JSON data.
        ajax_request, recid1, recid2 = False, None, None
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        if form.has_key('jsondata'):
            json_data = json.loads(str(form['jsondata']))
            # Deunicode all strings (Invenio doesn't have unicode
            # support).
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}
            if json_data.has_key('recID1'):
                recid1 = json_data['recID1']
            if json_data.has_key('recID2'):
                recid2 = json_data['recID2']

        # 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):
                auth_code, auth_message = acc_authorize_action(req, 'runbibmerge')
                referer = '/merge/'
                return page_not_authorized(req=req, referer=referer,
                                           text=auth_message, navtrail=navtrail)
            else:
                # Session has most likely timed out.
                json_response.update({'resultCode': 1,
                                      'resultText': 'Error: Not logged in'})
                return json.dumps(json_response)

        elif self.recid:
            # Handle RESTful call by storing recid and redirecting to
            # generic URL.
            redirect_to_url(req, '%s/record/merge/' % CFG_SITE_URL )

        if recid1 is not None:
            # Authorize access to record 1.
            auth_code, auth_message = acc_authorize_action(req, 'runbibmerge',
                collection=guess_primary_collection_of_a_record(recid1))
            if auth_code != 0:
                json_response.update({'resultCode': 1, 'resultText': 'No access to record %s' % recid1})
                return json.dumps(json_response)
        if recid2 is not None:
            # Authorize access to record 2.
            auth_code, auth_message = acc_authorize_action(req, 'runbibmerge',
                collection=guess_primary_collection_of_a_record(recid2))
            if auth_code != 0:
                json_response.update({'resultCode': 1, 'resultText': 'No access to record %s' % recid2})
                return json.dumps(json_response)

        # Handle request.
        uid = getUid(req)
        if not ajax_request:
            # Show BibEdit start page.
            body, errors, warnings = perform_request_init()
            metaheaderadd = """<script type="text/javascript" src="%(site)s/js/jquery.min.js"></script>
  <script type="text/javascript" src="%(site)s/js/json2.js"></script>
  <script type="text/javascript" src="%(site)s/js/bibmerge_engine.js"></script>""" % {'site': CFG_SITE_URL}
            title = 'Record Merger'
            return page(title         = title,
                        metaheaderadd = metaheaderadd,
                        body          = body,
                        errors        = errors,
                        warnings      = warnings,
                        uid           = uid,
                        language      = argd['ln'],
                        navtrail      = navtrail,
                        lastupdated   = __lastupdated__,
                        req           = req)
        else:
            # Handle AJAX request.
            json_response = perform_request_ajax(req, uid, json_data)
            return json.dumps(json_response)
    def index(self, req, form):
        """Handle all BibEdit requests.
        The responsibilities of this functions is:
        * JSON decoding and encoding.
        * Redirection, if necessary.
        * Authorization.
        * Calling the appropriate function from the engine.

        """
        uid = getUid(req)
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        # Abort if the simplejson module isn't available
        if not simplejson_available:
            title = 'Record Editor'
            body = '''Sorry, the record editor cannot operate when the
                `simplejson' module is not installed.  Please see the INSTALL
                file.'''
            return page(title       = title,
                        body        = body,
                        errors      = [],
                        warnings    = [],
                        uid         = uid,
                        language    = argd['ln'],
                        navtrail    = navtrail,
                        lastupdated = __lastupdated__,
                        req         = req)

        # If it is an Ajax request, extract any JSON data.
        ajax_request, recid = False, None
        if form.has_key('jsondata'):
            json_data = json.loads(str(form['jsondata']))
            # Deunicode all strings (Invenio doesn't have unicode
            # support).
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            if json_data.has_key('recID'):
                recid = json_data['recID']
            json_response = {'resultCode': 0, 'ID': json_data['ID']}

        # 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):
                auth_code, auth_message = acc_authorize_action(req,
                                                               'runbibedit')
                referer = '/edit/'
                if self.recid:
                    referer = '/record/%s/edit/' % self.recid
                return page_not_authorized(req=req, referer=referer,
                                           text=auth_message, navtrail=navtrail)
            else:
                # Session has most likely timed out.
                json_response.update({'resultCode': 100})
                return json.dumps(json_response)

        elif self.recid:
            # Handle RESTful calls from logged in users by redirecting to
            # generic URL.
            redirect_to_url(req, '%s/record/edit/#state=edit&recid=%s&recrev=%s' % (
                    CFG_SITE_URL, self.recid, ""))

        elif recid is not None:
            json_response.update({'recID': recid})
            # Authorize access to record.
            auth_code, auth_message = acc_authorize_action(req, 'runbibedit',
                collection=guess_primary_collection_of_a_record(recid))
            if auth_code != 0:
                json_response.update({'resultCode': 101})
                return json.dumps(json_response)

        # Handle request.
        if not ajax_request:
            # Show BibEdit start page.
            body, errors, warnings = perform_request_init(uid, argd['ln'], req, __lastupdated__)
            title = 'Record Editor'
            return page(title       = title,
                        body        = body,
                        errors      = errors,
                        warnings    = warnings,
                        uid         = uid,
                        language    = argd['ln'],
                        navtrail    = navtrail,
                        lastupdated = __lastupdated__,
                        req         = req)
        else:
            # Handle AJAX request.
            json_response.update(perform_request_ajax(req, recid, uid,
                                                      json_data))
            return json.dumps(json_response)
        def getfile(req, form):
            args = wash_urlargd(form, bibdocfile_templates.files_default_urlargd)
            ln = args['ln']

            _ = gettext_set_language(ln)

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

            verbose = args['verbose']
            if verbose >= 1 and not isUserSuperAdmin(user_info):
                # Only SuperUser can see all the details!
                verbose = 0

            if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE > 1:
                return page_not_authorized(req, "/%s/%s" % (CFG_SITE_RECORD, self.recid),
                                           navmenuid='submit')

            if record_exists(self.recid) < 1:
                msg = "<p>%s</p>" % _("Requested record does not seem to exist.")
                return warning_page(msg, req, ln)

            if record_empty(self.recid):
                msg = "<p>%s</p>" % _("Requested record does not seem to have been integrated.")
                return warning_page(msg, req, ln)

            (auth_code, auth_message) = check_user_can_view_record(user_info, self.recid)
            if auth_code and user_info['email'] == 'guest':
                if webjournal_utils.is_recid_in_released_issue(self.recid):
                    # We can serve the file
                    pass
                else:
                    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' : ln, 'referer' : \
                                                     CFG_SITE_SECURE_URL + user_info['uri']}, {})
                    return redirect_to_url(req, target, norobot=True)
            elif auth_code:
                if webjournal_utils.is_recid_in_released_issue(self.recid):
                    # We can serve the file
                    pass
                else:
                    return page_not_authorized(req, "../", \
                                               text = auth_message)


            readonly = CFG_ACCESS_CONTROL_LEVEL_SITE == 1

            # From now on: either the user provided a specific file
            # name (and a possible version), or we return a list of
            # all the available files. In no case are the docids
            # visible.
            try:
                bibarchive = BibRecDocs(self.recid)
            except InvenioBibDocFileError:
                register_exception(req=req, alert_admin=True)
                msg = "<p>%s</p><p>%s</p>" % (
                    _("The system has encountered an error in retrieving the list of files for this document."),
                    _("The error has been logged and will be taken in consideration as soon as possible."))
                return warning_page(msg, req, ln)

            if bibarchive.deleted_p():
                req.status = apache.HTTP_GONE
                return warning_page(_("Requested record does not seem to exist."), req, ln)

            docname = ''
            docformat = ''
            version = ''
            warn = ''

            if filename:
                # We know the complete file name, guess which docid it
                # refers to
                ## TODO: Change the extension system according to ext.py from setlink
                ##       and have a uniform extension mechanism...
                docname = file_strip_ext(filename)
                docformat = filename[len(docname):]
                if docformat and docformat[0] != '.':
                    docformat = '.' + docformat
                if args['subformat']:
                    docformat += ';%s' % args['subformat']
            else:
                docname = args['docname']

            if not docformat:
                docformat = args['format']
                if args['subformat']:
                    docformat += ';%s' % args['subformat']

            if not version:
                version = args['version']

            ## Download as attachment
            is_download = False
            if args['download']:
                is_download = True

            # version could be either empty, or all or an integer
            try:
                int(version)
            except ValueError:
                if version != 'all':
                    version = ''

            display_hidden = isUserSuperAdmin(user_info)

            if version != 'all':
                # search this filename in the complete list of files
                for doc in bibarchive.list_bibdocs():
                    if docname == bibarchive.get_docname(doc.id):
                        try:
                            try:
                                docfile = doc.get_file(docformat, version)
                            except InvenioBibDocFileError, msg:
                                req.status = apache.HTTP_NOT_FOUND
                                if req.headers_in.get('referer'):
                                    ## There must be a broken link somewhere.
                                    ## Maybe it's good to alert the admin
                                    register_exception(req=req, alert_admin=True)
                                warn += write_warning(_("The format %s does not exist for the given version: %s") % (cgi.escape(docformat), cgi.escape(str(msg))))
                                break
                            (auth_code, auth_message) = docfile.is_restricted(user_info)
                            if auth_code != 0 and not is_user_owner_of_record(user_info, self.recid):
                                if CFG_BIBDOCFILE_ICON_SUBFORMAT_RE.match(get_subformat_from_format(docformat)):
                                    return stream_restricted_icon(req)
                                if user_info['email'] == 'guest':
                                    cookie = mail_cookie_create_authorize_action('viewrestrdoc', {'status' : docfile.get_status()})
                                    target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                                    make_canonical_urlargd({'action': cookie, 'ln' : ln, 'referer' : \
                                        CFG_SITE_SECURE_URL + user_info['uri']}, {})
                                    redirect_to_url(req, target)
                                else:
                                    req.status = apache.HTTP_UNAUTHORIZED
                                    warn += write_warning(_("This file is restricted: ") + str(auth_message))
                                    break

                            if not docfile.hidden_p():
                                if not readonly:
                                    ip = str(req.remote_ip)
                                    doc.register_download(ip, version, docformat, uid)
                                try:
                                    return docfile.stream(req, download=is_download)
                                except InvenioBibDocFileError, msg:
                                    register_exception(req=req, alert_admin=True)
                                    req.status = apache.HTTP_INTERNAL_SERVER_ERROR
                                    warn += write_warning(_("An error has happened in trying to stream the request file."))
                            else:
                                req.status = apache.HTTP_UNAUTHORIZED
                                warn += write_warning(_("The requested file is hidden and can not be accessed."))

                        except InvenioBibDocFileError, msg:
                            register_exception(req=req, alert_admin=True)