Exemplo n.º 1
0
    def display(self, req, form):
        """Display search history page.  A misnomer."""

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

        uid = getUid(req)

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

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

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

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

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

        return page(title=_title,
                    body=webalert.perform_display(argd['p'], uid, ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemplo n.º 2
0
    def write(self, req, form):
        """ write(): interface for message composing
        @param msg_reply_id: if this message is a reply to another, id of the
                             other
        @param msg_to: if this message is not a reply, nickname of the user it
                       must be delivered to.
        @param msg_to_group: name of group to send message to
        @param ln: language
        @return: the compose page
        """
        argd = wash_urlargd(form, {'msg_reply_id': (int, 0),
                                   'msg_to': (str, ""),
                                   'msg_to_group': (str, ""),
                                   'msg_subject' : (str, ""),
                                   'msg_body' : (str, "")})

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

        _ = gettext_set_language(argd['ln'])

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

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

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

        return page(title       = title,
                    body        = body,
                    navtrail    = get_navtrail(argd['ln'], title),
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)
Exemplo n.º 3
0
    def display(self, req, form):
        """Display search history page.  A misnomer."""

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

        uid = getUid(req)

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

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

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

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

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

        return page(title=_title,
                    body=webalert.perform_display(argd['p'], uid, ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemplo n.º 4
0
        def _index(req, c, ln, doctype, act, startPg, access,
                   mainmenu, fromdir, nextPg, nbPg, curpage, step,
                   mode):
            auth_args = {}
            if doctype:
                auth_args['doctype'] = doctype
            if act:
                auth_args['act'] = act
            uid = getUid(req)

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

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

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

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

                        return page_not_authorized(req, "../submit",
                                                   uid=uid,
                                                   navmenuid='submit')
                return home(req, catalogues_text, c, ln)
            elif act == "":
                return action(req, c, ln, doctype)
            elif int(step)==0:
                return interface(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage)
            else:
                return endaction(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode)
Exemplo n.º 5
0
    def index(self, req, form):
        """Index page."""

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

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

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

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

        return page(title=_("Your Comments"),
                    body=perform_display_your_comments(user_info,
                                                       page_number=argd['page'],
                                                       selected_order_by_option=argd['order_by'],
                                                       selected_display_number_option=argd['per_page'],
                                                       selected_display_format_option=argd['format'],
                                                       ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemplo n.º 6
0
    def index(self, req, form):
        """Index page."""

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

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

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

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

        return page(title=_("Your Comments"),
                    body=perform_display_your_comments(user_info,
                                                       page_number=argd['page'],
                                                       selected_order_by_option=argd['order_by'],
                                                       selected_display_number_option=argd['per_page'],
                                                       selected_display_format_option=argd['format'],
                                                       ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
Exemplo n.º 7
0
    def display_msg(self, req, form):
        """
        Display a message
        @param msgid: id of message
        @param ln: languae
        @return: page
        """
        argd = wash_urlargd(form, {
            'msgid': (int, -1),
        })

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

        _ = gettext_set_language(argd['ln'])

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

        # Generate content
        body = perform_request_display_msg(uid, argd['msgid'], argd['ln'])
        title = _("Read a message")
        return page(title=title,
                    body=body,
                    navtrail=get_navtrail(argd['ln'], title),
                    uid=uid,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="yourmessages",
                    secure_page_p=1)
Exemplo n.º 8
0
    def delete_all(self, req, form):
        """
        Empty user's inbox
        @param confimed: 1 if message is confirmed
        @param ln: language
        \return page
        """
        argd = wash_urlargd(form, {
            'confirmed': (int, 0),
        })

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

        _ = gettext_set_language(argd['ln'])

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

        # Generate content
        body = perform_request_delete_all(uid, argd['confirmed'], argd['ln'])
        return page(title=_("Your Messages"),
                    body=body,
                    navtrail=get_navtrail(argd['ln']),
                    uid=uid,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="yourmessages",
                    secure_page_p=1)
Exemplo n.º 9
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

        uid = getUid(req)

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

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_SECURE_URL,
            CFG_SITE_RECORD,
            self.recid,
            str(success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
Exemplo n.º 10
0
    def check_authorization_moderatelinkbacks(self, req, argd):
        """
        Check if user has authorization moderate linkbacks
        @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized
        """
        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = acc_authorize_action(
            req,
            'moderatelinkbacks',
            collection=guess_primary_collection_of_a_record(self.recid))
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])
Exemplo n.º 11
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

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

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

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

        uid = getUid(req)

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

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(success), argd['ln'])
        redirect_to_url(req, display_url)
Exemplo n.º 13
0
    def display_msg(self, req, form):
        """
        Display a message
        @param msgid: id of message
        @param ln: languae
        @return: page
        """
        argd = wash_urlargd(form, {'msgid': (int, -1),
                                   })

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

        _ = gettext_set_language(argd['ln'])

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

        # Generate content
        body = perform_request_display_msg(uid,
                                           argd['msgid'],
                                           argd['ln'])
        title = _("Read a message")
        return page(title       = title,
                    body        = body,
                    navtrail    = get_navtrail(argd['ln'], title),
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)
Exemplo n.º 14
0
    def delete_all(self, req, form):
        """
        Empty user's inbox
        @param confimed: 1 if message is confirmed
        @param ln: language
        \return page
        """
        argd = wash_urlargd(form, {'confirmed': (int, 0),
                                   })

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

        _ = gettext_set_language(argd['ln'])

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

        # Generate content
        body = perform_request_delete_all(uid,
                                          argd['confirmed'],
                                          argd['ln'])
        return page(title       = _("Your Messages"),
                    body        = body,
                    navtrail    = get_navtrail(argd['ln']),
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)
Exemplo n.º 15
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)
        argd['recid'] = self.recid

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

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

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

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

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

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

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if isinstance(out, intbitset):
            return out.fastdump()
        elif out == []:
            return str(out)
        else:
            return out
Exemplo n.º 16
0
    def authenticate(self, req, form):
        """Restricted search results pages."""

        argd = wash_search_urlargd(form)

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

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

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

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

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


        # 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
Exemplo n.º 17
0
    def __call__(self, req, form):
        """ Perform a search. """

        argd = wash_search_urlargd(form)

        # We either jump into the generic search form, or the specific
        # /CFG_SITE_RECORD/... display if a recid is requested
        if argd['recid'] != -1:
            target = '/%s/%d' % (CFG_SITE_RECORD, argd['recid'])
            del argd['recid']

        else:
            target = '/search'

        target += make_canonical_urlargd(argd, search_results_default_urlargd)
        return redirect_to_url(req, target, apache.HTTP_MOVED_PERMANENTLY)
Exemplo n.º 18
0
    def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG):
        """Take URLARGS and LANGUAGE and return textual language
           selection box for the given page.

           Parameters:

          - 'req' - The mod_python request object

          - 'language' *string* - The selected language

        """

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

        # Work on a copy in order not to bork the arguments of the caller
        argd = {}
        if req and req.args:
            argd.update(cgi.parse_qs(req.args))

        parts = []

        for (lang, lang_namelong) in language_list_long():
            if lang == language:
                parts.append('<span class="langinfo">%s</span>' %
                             lang_namelong)
            else:
                # Update the 'ln' argument in the initial request
                argd['ln'] = lang
                if req and req.uri:
                    args = urllib.quote(
                        req.uri, '/:?') + make_canonical_urlargd(argd, {})
                else:
                    args = ""
                parts.append(
                    create_html_link(args, {}, lang_namelong,
                                     {'class': "langinfo"}))
        if len(parts) > 1:
            return _("This site is also available in the following languages:") + \
                 "<br />" + ' &nbsp;'.join(parts)
        else:
            ## There is only one (or zero?) languages configured,
            ## so there so need to display language alternatives.
            return ""
Exemplo n.º 19
0
    def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG):
        """Take URLARGS and LANGUAGE and return textual language
           selection box for the given page.

           Parameters:

          - 'req' - The mod_python request object

          - 'language' *string* - The selected language

        """

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

        # Work on a copy in order not to bork the arguments of the caller
        argd = {}
        if req and req.args:
            argd.update(cgi.parse_qs(req.args))

        parts = []

        for (lang, lang_namelong) in language_list_long():
            if lang == language:
                parts.append('<span class="langinfo">%s</span>' % lang_namelong)
            else:
                # Update the 'ln' argument in the initial request
                argd['ln'] = lang
                if req and req.uri:
                    args = urllib.quote(req.uri, '/:?') + make_canonical_urlargd(argd, {})
                else:
                    args = ""
                parts.append(create_html_link(args,
                                              {}, lang_namelong,
                                              {'class': "langinfo"}))
        if len(parts) > 1:
            return _("This site is also available in the following languages:") + \
                 "<br />" + ' &nbsp;'.join(parts)
        else:
            ## There is only one (or zero?) languages configured,
            ## so there so need to display language alternatives.
            return ""
Exemplo n.º 20
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

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

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

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(-success), argd['ln'])
        redirect_to_url(req, display_url)
Exemplo n.º 21
0
    def check_authorization_moderatelinkbacks(self, req, argd):
        """
        Check if user has authorization moderate linkbacks
        @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized
        """
        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatelinkbacks', collection = guess_primary_collection_of_a_record(self.recid))
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])
Exemplo n.º 22
0
    def legacy_collection(self, req, form):
        """Collection URL backward compatibility handling."""
        accepted_args = dict(legacy_collection_default_urlargd)
        argd = wash_urlargd(form, accepted_args)

        # Treat `as' argument specially:
        if 'as' in argd:
            argd['aas'] = argd['as']
            del argd['as']
        if argd.get('aas', CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE) not in CFG_WEBSEARCH_ENABLED_SEARCH_INTERFACES:
            argd['aas'] = CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE

        # If we specify no collection, then we don't need to redirect
        # the user, so that accessing <http://yoursite/> returns the
        # default collection.
        if 'c' not in form:
            return display_collection(req, **argd)

        # make the collection an element of the path, and keep the
        # other query elements as is. If the collection is CFG_SITE_NAME,
        # however, redirect to the main URL.
        c = argd['c']
        del argd['c']

        if c == CFG_SITE_NAME:
            target = '/'
        else:
            target = '/collection/' + quote(c)

        # Treat `as' argument specially:
        # We are going to redirect, so replace `aas' by `as' visible argument:
        if 'aas' in argd:
            argd['as'] = argd['aas']
            del argd['aas']

        target += make_canonical_urlargd(argd, legacy_collection_default_urlargd)
        return redirect_to_url(req, target)
Exemplo n.º 23
0
    def direct(self, req, form):
        """Directly redirected to an initialized submission."""
        args = wash_urlargd(form, {'sub': (str, ''),
                                   'access' : (str, '')})

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

        _ = gettext_set_language(ln)

        uid = getUid(req)

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "direct",
                                       navmenuid='submit',
                                       text=_("Submissions are not available"))

        myQuery = req.args
        if not sub:
            return warning_page(_("Sorry, 'sub' parameter missing..."), req, ln=ln)
        res = run_sql("SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s", (sub,))
        if not res:
            return warning_page(_("Sorry. Cannot analyse parameter"), req, ln=ln)
        else:
            # get document type
            doctype = res[0][0]
            # get action name
            action = res[0][1]
            # get category
            categ = req.form.get('combo%s' % doctype, '*')
        # retrieve other parameter values
        params = dict(form)

        # Check if user is authorized, based on doctype/action/categ,
        # in order to give guest users a chance to log in if needed:
        (auth_code, auth_message) = acc_authorize_action(req, 'submit',
                                                         authorized_if_no_roles=not isGuestUser(uid),
                                                         verbose=0,
                                                         doctype=doctype,
                                                         act=action,
                                                         categ=categ)
        if not auth_code == 0 and isGuestUser(uid):
            # Propose to login
            redirection_params = params
            redirection_params['referer'] = CFG_SITE_SECURE_URL + req.unparsed_uri
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd(redirection_params, {})),
                                   norobot=True)
        # else: continue, and let main interface control the access

        # find existing access number
        if not access:
            # create 'unique' access number
            pid = os.getpid()
            now = time.time()
            access = "%i_%s" % (now, pid)
        # retrieve 'dir' value
        res = run_sql ("SELECT dir FROM sbmACTION WHERE sactname=%s", (action,))
        dir = res[0][0]

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

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

        url = "%s/submit?%s" % (CFG_SITE_SECURE_URL, urlencode(params))
        redirect_to_url(req, url)
Exemplo n.º 24
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 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        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_reclist(collname)
                        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
Exemplo n.º 25
0
    def send(self, req, form):
        """
        Sends the message.

        Possible form keys:
        @param msg_to_user: comma separated usernames.
        @type msg_to_user: string
        @param msg_to_group: comma separated groupnames.
        @type msg_to_group: string
        @param msg_subject: message subject.
        @type msg_subject: string
        @param msg_body: message body.
        @type msg_body: string
        @param msg_send_year: year to send this message on.
        @type msg_send_year: int
        @param_msg_send_month: month to send this message on
        @type msg_send_month: year
        @param_msg_send_day: day to send this message on
        @type msg_send_day: int
        @param results_field: value determining which results field to display.
                              See CFG_WEBMESSAGE_RESULTS_FIELD in
                              webmessage_config.py.
        @param names_to_add: list of usernames to add to
                             msg_to_user / group.
        @type names_to_add: list of strings
        @param search_pattern: will search for users/groups with this pattern.
        @type search_pattern: string
        @param add_values: if 1 users_to_add will be added to msg_to_user
                           field.
        @type add_values: int
        @param *button: which button was pressed.
        @param ln: language.
        @type ln: string
        @return: body.
        """
        argd = wash_urlargd(
            form, {
                'msg_to_user': (str, ""),
                'msg_to_group': (str, ""),
                'msg_subject': (str, ""),
                'msg_body': (str, ""),
                'msg_send_year': (int, 0),
                'msg_send_month': (int, 0),
                'msg_send_day': (int, 0),
                'results_field': (str, CFG_WEBMESSAGE_RESULTS_FIELD['NONE']),
                'names_selected': (list, []),
                'search_pattern': (str, ""),
                'send_button': (str, ""),
                'search_user': (str, ""),
                'search_group': (str, ""),
                'add_user': (str, ""),
                'add_group': (str, ""),
            })
        # Check if user is logged
        uid = getUid(req)
        _ = gettext_set_language(argd['ln'])
        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourmessages/send" % \
                                             (CFG_SITE_URL,),
                                       navmenuid="yourmessages")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(
                req, "%s/youraccount/login%s" %
                (CFG_SITE_SECURE_URL,
                 make_canonical_urlargd(
                     {
                         'referer':
                         "%s/yourmessages/send%s" %
                         (CFG_SITE_SECURE_URL, make_canonical_urlargd(
                             argd, {})),
                         "ln":
                         argd['ln']
                     }, {})))

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

        if argd['send_button']:
            (body, title, navtrail) = perform_request_send(
                uid=uid,
                msg_to_user=argd['msg_to_user'],
                msg_to_group=argd['msg_to_group'],
                msg_subject=escape_html(argd['msg_subject']),
                msg_body=escape_email_quoted_text(argd['msg_body']),
                msg_send_year=argd['msg_send_year'],
                msg_send_month=argd['msg_send_month'],
                msg_send_day=argd['msg_send_day'],
                ln=argd['ln'])
        else:
            title = _('Write a message')
            navtrail = get_navtrail(argd['ln'], title)
            if argd['search_user']:
                argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['USER']
            elif argd['search_group']:
                argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['GROUP']
            add_values = 0
            if argd['add_group'] or argd['add_user']:
                add_values = 1
            body = perform_request_write_with_search(
                uid=uid,
                msg_to_user=argd['msg_to_user'],
                msg_to_group=argd['msg_to_group'],
                msg_subject=escape_html(argd['msg_subject']),
                msg_body=escape_email_quoted_text(argd['msg_body']),
                msg_send_year=argd['msg_send_year'],
                msg_send_month=argd['msg_send_month'],
                msg_send_day=argd['msg_send_day'],
                names_selected=argd['names_selected'],
                search_pattern=argd['search_pattern'],
                results_field=argd['results_field'],
                add_values=add_values,
                ln=argd['ln'])
        return page(title=title,
                    body=body,
                    navtrail=navtrail,
                    uid=uid,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="yourmessages",
                    secure_page_p=1)
Exemplo n.º 26
0
    def write(self, req, form):
        """ write(): interface for message composing
        @param msg_reply_id: if this message is a reply to another, id of the
                             other
        @param msg_to: if this message is not a reply, nickname of the user it
                       must be delivered to.
        @param msg_to_group: name of group to send message to
        @param ln: language
        @return: the compose page
        """
        argd = wash_urlargd(
            form, {
                'msg_reply_id': (int, 0),
                'msg_to': (str, ""),
                'msg_to_group': (str, ""),
                'msg_subject': (str, ""),
                'msg_body': (str, "")
            })

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

        _ = gettext_set_language(argd['ln'])

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

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

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

        return page(title=title,
                    body=body,
                    navtrail=get_navtrail(argd['ln'], title),
                    uid=uid,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="yourmessages",
                    secure_page_p=1)
Exemplo n.º 27
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),
            },
        )
        _ = 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 isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)}
            )
            target = (
                CFG_SITE_SECURE_URL
                + "/youraccount/login"
                + make_canonical_urlargd(
                    {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_SECURE_URL + user_info["uri"]}, {}
                )
            )
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", text=auth_msg)

        # 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 report a deleted comment"), ln=argd["ln"])

        success = perform_request_report(argd["comid"], client_ip_address, uid)
        if argd["referer"]:
            argd["referer"] += "?ln=%s&do=%s&ds=%s&nb=%s&p=%s&reported=%s&" % (
                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&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)
Exemplo n.º 28
0
    def remove(self, req, form):

        argd = wash_urlargd(form, {'name': (str, None),
                                   'idq': (int, None),
                                   'idb': (int, None),
                                   })

        uid = getUid(req)

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

        # load the right language
        _ = gettext_set_language(argd['ln'])
        user_info = collect_user_info(req)
        if not user_info['precached_usealerts']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use alerts."))

        try:
            html = webalert.perform_remove_alert(argd['name'], argd['idq'],
                                                 argd['idb'], uid, ln=argd['ln'])
        except webalert.AlertError as msg:
            return page(title=_("Error"),
                        body=webalert_templates.tmpl_errorMsg(ln=argd['ln'], error_msg=msg),
                        navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                     'sitesecureurl' : CFG_SITE_SECURE_URL,
                                     'ln': argd['ln'],
                                     'account' : _("Your Account"),
                                  },
                        description=_("%(x_name)s Personalize, Set a new alert", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                        keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                        uid=uid,
                        language=argd['ln'],
                        req=req,
                        lastupdated=__lastupdated__,
                        navmenuid='youralerts')


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

        # display success
        return page(title=_("Display alerts"),
                    body=html,
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s Personalize, Display alerts", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts')
Exemplo n.º 29
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 = CFG_SITE_SECURE_URL + '/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)

        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 = [
        ]  # 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_TMPSHAREDDIR, 'webcomment',
                                               str(uid))
                    try:
                        assert (dir_to_open.startswith(CFG_TMPSHAREDDIR))
                    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
                        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 \\"%(x_file)s\\" (%(x_size)s) is larger than maximum allowed file size (%(x_max)s). Select files again.',
                                      x_file=cgi.escape(filename),
                                      x_size=str(file_size / 1024) + 'KB',
                                      x_max=str(
                                          CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE /
                                          1024) + 'KB'))
                            except InvenioWebCommentWarning as 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 += cgi.escape(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:
                    return redirect_to_url(req, CFG_SITE_SECURE_URL + '/'+ CFG_SITE_RECORD +'/' + \
                                           str(self.recid) + (self.discussion==1 and \
                                                              '/reviews' or '/comments'))
                except InvenioWebAccessMailCookieError:
                    # Invalid or empty cookie: continue
                    pass

            subscribe = False
            if argd['subscribe'] and \
               get_user_subscription_to_discussion(self.recid, uid) == 0:
                # User is not already subscribed, and asked to subscribe
                subscribe = True

            body = perform_request_add_comment_or_remark(
                recID=self.recid,
                ln=argd['ln'],
                uid=uid,
                action=argd['action'],
                msg=argd['msg'],
                note=argd['note'],
                score=argd['score'],
                reviews=self.discussion,
                comID=argd['comid'],
                client_ip_address=client_ip_address,
                editor_type=argd['editor_type'],
                can_attach_files=can_attach_files,
                subscribe=subscribe,
                req=req,
                attached_files=added_files,
                warnings=warning_msgs)

            if self.discussion:
                title = _("Add Review")
            else:
                title = _("Add Comment")

            jqueryheader = '''
            <script src="%(CFG_SITE_URL)s/vendors/jquery-multifile/jquery.MultiFile.pack.js" type="text/javascript"></script>
            ''' % {
                'CFG_SITE_URL': CFG_SITE_URL
            }

            return page(title=title,
                        body=body,
                        navtrail=navtrail,
                        uid=uid,
                        language=CFG_SITE_LANG,
                        verbose=1,
                        req=req,
                        navmenuid='search',
                        metaheaderadd=jqueryheader)
        # id not in range
        else:
            return page(title=_("Record Not Found"),
                        body=problem,
                        uid=uid,
                        verbose=1,
                        req=req,
                        navmenuid='search')
Exemplo n.º 30
0
    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 iteritems(unordered_tabs)]
        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)
Exemplo n.º 31
0
    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(
        )

        col_id = Collection.query.filter_by(
            name=guess_primary_collection_of_a_record(self.recid)).value('id')
        unordered_tabs = get_detailed_page_tabs(col_id,
                                                self.recid,
                                                ln=argd['ln'])
        ordered_tabs_id = [(tab_id, values['order'])
                           for (tab_id, values) in iteritems(unordered_tabs)]
        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)
Exemplo n.º 32
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 = (
                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)

        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

        col_id = Collection.query.filter_by(name=guess_primary_collection_of_a_record(self.recid)).value("id")
        unordered_tabs = get_detailed_page_tabs(col_id, self.recid, ln=argd["ln"])
        ordered_tabs_id = [(tab_id, values["order"]) for (tab_id, values) in iteritems(unordered_tabs)]
        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 += cgi.escape(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/vendors/jquery-multifile/jquery.MultiFile.pack.js" type="text/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",
            )
Exemplo n.º 33
0
    def managedocfiles(self, req, form):
        """
        Display admin interface to manage files of a record
        """
        argd = wash_urlargd(
            form, {
                'ln': (str, ''),
                'access': (str, ''),
                'recid': (int, None),
                'do': (int, 0),
                'cancel': (str, None),
            })

        _ = gettext_set_language(argd['ln'])
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check authorization
        (auth_code, auth_msg) = acc_authorize_action(req, 'runbibdocfile')
        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_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="/%s/managedocfiles" %
                                       CFG_SITE_RECORD,
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'],
                                       navmenuid="admin")

        # Prepare navtrail
        navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> &gt; %(manage_files)s''' \
        % {'CFG_SITE_URL': CFG_SITE_URL,
           'manage_files': _("Manage Document Files")}

        body = ''
        if argd['do'] != 0 and not argd['cancel']:
            # Apply modifications
            working_dir = os.path.join(
                CFG_TMPSHAREDDIR,
                'websubmit_upload_interface_config_' + str(uid),
                argd['access'])
            if not os.path.isdir(working_dir):
                # We accessed the url without preliminary steps
                # (we did not upload a file)
                # Our working dir does not exist
                # Display the file manager
                argd['do'] = 0
            else:
                move_uploaded_files_to_storage(working_dir=working_dir,
                                               recid=argd['recid'],
                                               icon_sizes=['180>', '700>'],
                                               create_icon_doctypes=['*'],
                                               force_file_revision=False)
                # Clean temporary directory
                shutil.rmtree(working_dir)

                # Confirm modifications
                body += '<p style="color:#0f0">%s</p>' % \
                        (_('Your modifications to record #%(x_redid)i have been submitted', x_redid=argd['recid']))
        elif argd['cancel']:
            # Clean temporary directory
            working_dir = os.path.join(
                CFG_TMPSHAREDDIR,
                'websubmit_upload_interface_config_' + str(uid),
                argd['access'])
            shutil.rmtree(working_dir)
            body += '<p style="color:#c00">%s</p>' % \
                    (_('Your modifications to record #%(x_num)i have been cancelled', x_num=argd['recid']))

        if not argd['recid'] or argd['do'] != 0:
            body += '''
        <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">
        <label for="recid">%(edit_record)s:</label>
        <input type="text" name="recid" id="recid" />
        <input type="submit" value="%(edit)s" class="adminbutton" />
        </form>
        ''' % {
                'edit': _('Edit'),
                'edit_record': _('Edit record'),
                'CFG_SITE_URL': CFG_SITE_URL,
                'CFG_SITE_RECORD': CFG_SITE_RECORD
            }

        access = time.strftime('%Y%m%d_%H%M%S')
        if argd['recid'] and argd['do'] == 0:
            # Displaying interface to manage files
            # Prepare navtrail
            title, dummy_description, dummy_keywords = websearch_templates.tmpl_record_page_header_content(
                req, argd['recid'], argd['ln'])
            navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> &gt;
        <a class="navtrail" href="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">%(manage_files)s</a> &gt;
        %(record)s: %(title)s
        ''' \
            % {'CFG_SITE_URL': CFG_SITE_URL,
               'title': title,
               'manage_files': _("Document File Manager"),
               'record': _("Record #%(x_rec)i", x_rec=argd['recid']),
               'CFG_SITE_RECORD': CFG_SITE_RECORD}

            body += create_file_upload_interface(\
                recid=argd['recid'],
                ln=argd['ln'],
                uid=uid,
                sbm_access=access,
                display_hidden_files=True,
                restrictions_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_RESTRICTIONS,
                doctypes_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_DOCTYPES,
                **CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_MISC)[1]

            body += '''<br />
            <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">
            <input type="hidden" name="recid" value="%(recid)s" />
            <input type="hidden" name="do" value="1" />
            <input type="hidden" name="access" value="%(access)s" />
            <input type="hidden" name="ln" value="%(ln)s" />
            <div style="font-size:small">
    <input type="submit" name="cancel" value="%(cancel_changes)s" />
    <input type="submit" onclick="user_must_confirm_before_leaving_page=false;return true;" class="adminbutton" name="submit" id="applyChanges" value="%(apply_changes)s" />
    </div></form>''' % \
    {'apply_changes': _("Apply changes"),
            'cancel_changes': _("Cancel all changes"),
            'recid': argd['recid'],
            'access': access,
            'ln': argd['ln'],
            'CFG_SITE_URL': CFG_SITE_URL,
            'CFG_SITE_RECORD': CFG_SITE_RECORD}

            body += websubmit_templates.tmpl_page_do_not_leave_submission_js(
                argd['ln'], enabled=True)

        return page(title = _("Document File Manager") + (argd['recid'] and (': ' + _("Record #%(x_rec)i", x_rec=argd['recid'])) or ''),
                    navtrail=navtrail,
                    navtrail_append_title_p=0,
                    metaheaderadd = get_upload_file_interface_javascript(form_url_params='?access='+access) + \
                                    get_upload_file_interface_css(),
                    body = body,
                    uid = uid,
                    language=argd['ln'],
                    req=req,
                    navmenuid='admin')
Exemplo n.º 34
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 as 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 %(x_form)s does not exist for the given version: %(x_vers)s",
                                      x_form=cgi.escape(docformat),
                                      x_vers=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 as 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 as msg:
                            register_exception(req=req, alert_admin=True)

            # Prevent leaking of restricted file names
            req.status = apache.HTTP_NOT_FOUND
            return

            if docname and docformat and not warn:
                req.status = apache.HTTP_NOT_FOUND
                warn += write_warning(
                    _("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 iteritems(unordered_tabs)]
            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
            ]

            tabs_counts = get_detailed_page_tabs_counts(self.recid)
            top = webstyle_templates.detailed_record_container_top(
                self.recid,
                tabs,
                args['ln'],
                citationnum=tabs_counts['Citations'],
                referencenum=tabs_counts['References'],
                discussionnum=tabs_counts['Discussions'])
            bottom = webstyle_templates.detailed_record_container_bottom(
                self.recid, tabs, args['ln'])
            title, description, keywords = websearch_templates.tmpl_record_page_header_content(
                req, self.recid, args['ln'])
            return pageheaderonly(title=title,
                        navtrail=create_navtrail_links(cc=cc, aas=0, ln=ln) + \
                                        ''' &gt; <a class="navtrail" href="%s/%s/%s">%s</a>
                                        &gt; %s''' % \
                        (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, title, _("Access to Fulltext")),

                        description=description,
                        keywords=keywords,
                        uid=uid,
                        language=ln,
                        req=req,
                        navmenuid='search',
                        navtrail_append_title_p=0) + \
                        websearch_templates.tmpl_search_pagestart(ln) + \
                        top + t + bottom + \
                        websearch_templates.tmpl_search_pageend(ln) + \
                        pagefooteronly(language=ln, req=req)
Exemplo n.º 35
0
    def __call__(self, req, form):
        """RSS 2.0 feed service."""

        # Keep only interesting parameters for the search
        default_params = websearch_templates.rss_default_urlargd
        # We need to keep 'jrec' and 'rg' here in order to have
        # 'multi-page' RSS. These parameters are not kept be default
        # as we don't want to consider them when building RSS links
        # from search and browse pages.
        default_params.update({'jrec':(int, 1),
                               'rg': (int, CFG_WEBSEARCH_INSTANT_BROWSE_RSS)})
        argd = wash_urlargd(form, default_params)
        user_info = collect_user_info(req)

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

        # Create a standard filename with these parameters
        current_url = websearch_templates.build_rss_url(argd)
        cache_filename = current_url.split('/')[-1]

        # In the same way as previously, add 'jrec' & 'rg'

        req.content_type = "application/rss+xml"
        req.send_http_header()
        try:
            # Try to read from cache
            path = "%s/rss/%s.xml" % (CFG_CACHEDIR, cache_filename)
            # Check if cache needs refresh
            filedesc = open(path, "r")
            last_update_time = datetime.datetime.fromtimestamp(os.stat(os.path.abspath(path)).st_mtime)
            assert(datetime.datetime.now() < last_update_time + datetime.timedelta(minutes=CFG_WEBSEARCH_RSS_TTL))
            c_rss = filedesc.read()
            filedesc.close()
            req.write(c_rss)
            return
        except Exception as e:
            # do it live and cache

            previous_url = None
            if argd['jrec'] > 1:
                prev_jrec = argd['jrec'] - argd['rg']
                if prev_jrec < 1:
                    prev_jrec = 1
                previous_url = websearch_templates.build_rss_url(argd,
                                                                 jrec=prev_jrec)

            #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

            req.argd = argd
            recIDs = perform_request_search(req, of="id",
                                                          c=argd['c'], cc=argd['cc'],
                                                          p=argd['p'], f=argd['f'],
                                                          p1=argd['p1'], f1=argd['f1'],
                                                          m1=argd['m1'], op1=argd['op1'],
                                                          p2=argd['p2'], f2=argd['f2'],
                                                          m2=argd['m2'], op2=argd['op2'],
                                                          p3=argd['p3'], f3=argd['f3'],
                                                          m3=argd['m3'], wl=argd['wl'])
            nb_found = len(recIDs)
            next_url = None
            if len(recIDs) >= argd['jrec'] + argd['rg']:
                next_url = websearch_templates.build_rss_url(argd,
                                                             jrec=(argd['jrec'] + argd['rg']))

            first_url = websearch_templates.build_rss_url(argd, jrec=1)
            last_url = websearch_templates.build_rss_url(argd, jrec=nb_found - argd['rg'] + 1)

            recIDs = recIDs[-argd['jrec']:(-argd['rg'] - argd['jrec']):-1]

            rss_prologue = '<?xml version="1.0" encoding="UTF-8"?>\n' + \
            websearch_templates.tmpl_xml_rss_prologue(current_url=current_url,
                                                      previous_url=previous_url,
                                                      next_url=next_url,
                                                      first_url=first_url, last_url=last_url,
                                                      nb_found=nb_found,
                                                      jrec=argd['jrec'], rg=argd['rg'],
                                                      cc=argd['cc']) + '\n'
            req.write(rss_prologue)
            rss_body = format_records(recIDs,
                                      of='xr',
                                      ln=argd['ln'],
                                      user_info=user_info,
                                      record_separator="\n",
                                      req=req, epilogue="\n")
            rss_epilogue = websearch_templates.tmpl_xml_rss_epilogue() + '\n'
            req.write(rss_epilogue)

            # update cache
            dirname = "%s/rss" % (CFG_CACHEDIR)
            mymkdir(dirname)
            fullfilename = "%s/rss/%s.xml" % (CFG_CACHEDIR, cache_filename)
            try:
                # Remove the file just in case it already existed
                # so that a bit of space is created
                os.remove(fullfilename)
            except OSError:
                pass

            # Check if there's enough space to cache the request.
            if len(os.listdir(dirname)) < CFG_WEBSEARCH_RSS_MAX_CACHED_REQUESTS:
                try:
                    os.umask(0o022)
                    f = open(fullfilename, "w")
                    f.write(rss_prologue + rss_body + rss_epilogue)
                    f.close()
                except IOError as v:
                    if v[0] == 36:
                        # URL was too long. Never mind, don't cache
                        pass
                    else:
                        raise repr(v)
Exemplo n.º 36
0
        def _index(req, c, ln, doctype, act, startPg, access, mainmenu,
                   fromdir, nextPg, nbPg, curpage, step, mode):
            auth_args = {}
            if doctype:
                auth_args['doctype'] = doctype
            if act:
                auth_args['act'] = act
            uid = getUid(req)

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

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

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

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

                        return page_not_authorized(req,
                                                   "../submit",
                                                   uid=uid,
                                                   navmenuid='submit')
                return home(req, catalogues_text, c, ln)
            elif act == "":
                return action(req, c, ln, doctype)
            elif int(step) == 0:
                return interface(req, c, ln, doctype, act, startPg, access,
                                 mainmenu, fromdir, nextPg, nbPg, curpage)
            else:
                return endaction(req, c, ln, doctype, act, startPg, access,
                                 mainmenu, fromdir, nextPg, nbPg, curpage,
                                 step, mode)
Exemplo n.º 37
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 = 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)

        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 iteritems(unordered_tabs)]
        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 += cgi.escape(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/vendors/jquery-multifile/jquery.MultiFile.pack.js" type="text/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')
Exemplo n.º 38
0
    def direct(self, req, form):
        """Directly redirected to an initialized submission."""
        args = wash_urlargd(form, {'sub': (str, ''), 'access': (str, '')})

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

        _ = gettext_set_language(ln)

        uid = getUid(req)

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req,
                                       "direct",
                                       navmenuid='submit',
                                       text=_("Submissions are not available"))

        myQuery = req.args
        if not sub:
            return warning_page(_("Sorry, 'sub' parameter missing..."),
                                req,
                                ln=ln)
        res = run_sql(
            "SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s",
            (sub, ))
        if not res:
            return warning_page(_("Sorry. Cannot analyse parameter"),
                                req,
                                ln=ln)
        else:
            # get document type
            doctype = res[0][0]
            # get action name
            action = res[0][1]
            # get category
            categ = req.form.get('combo%s' % doctype, '*')
        # retrieve other parameter values
        params = dict(form)

        # Check if user is authorized, based on doctype/action/categ,
        # in order to give guest users a chance to log in if needed:
        (auth_code, auth_message) = acc_authorize_action(
            req,
            'submit',
            authorized_if_no_roles=not isGuestUser(uid),
            verbose=0,
            doctype=doctype,
            act=action,
            categ=categ)
        if not auth_code == 0 and isGuestUser(uid):
            # Propose to login
            redirection_params = params
            redirection_params[
                'referer'] = CFG_SITE_SECURE_URL + req.unparsed_uri
            return redirect_to_url(
                req,
                "%s/youraccount/login%s" %
                (CFG_SITE_SECURE_URL,
                 make_canonical_urlargd(redirection_params, {})),
                norobot=True)
        # else: continue, and let main interface control the access

        # find existing access number
        if not access:
            # create 'unique' access number
            pid = os.getpid()
            now = time.time()
            access = "%i_%s" % (now, pid)
        # retrieve 'dir' value
        res = run_sql("SELECT dir FROM sbmACTION WHERE sactname=%s",
                      (action, ))
        dir = res[0][0]

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

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

        url = "%s/submit?%s" % (CFG_SITE_SECURE_URL, urlencode(params))
        redirect_to_url(req, url)
Exemplo n.º 39
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)
            })
        _ = 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 isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        # 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 report a deleted comment"),
                                       ln=argd['ln'])

        success = perform_request_report(argd['comid'], client_ip_address, uid)
        if argd['referer']:
            argd['referer'] += "?ln=%s&do=%s&ds=%s&nb=%s&p=%s&reported=%s&" % (
                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&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)
Exemplo n.º 40
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 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        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.legacy.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
Exemplo n.º 41
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 = 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)

        # 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 = 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)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        # Check that comment is not currently deleted
        if is_comment_deleted(argd['comid']):
            return page_not_authorized(req, "../", \
                                       text = _("You cannot access files of a deleted comment"),
                                       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'])
Exemplo n.º 42
0
    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)
Exemplo n.º 43
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 = (
                CFG_SITE_SECURE_URL
                + "/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)

        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 = []  # 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_TMPSHAREDDIR, "webcomment", str(uid))
                    try:
                        assert dir_to_open.startswith(CFG_TMPSHAREDDIR)
                    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
                        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 \\"%(x_file)s\\" (%(x_size)s) is larger than maximum allowed file size (%(x_max)s). Select files again.',
                                        x_file=cgi.escape(filename),
                                        x_size=str(file_size / 1024) + "KB",
                                        x_max=str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE / 1024) + "KB",
                                    )
                                )
                            except InvenioWebCommentWarning as 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 += cgi.escape(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:
                    return redirect_to_url(
                        req,
                        CFG_SITE_SECURE_URL
                        + "/"
                        + CFG_SITE_RECORD
                        + "/"
                        + str(self.recid)
                        + (self.discussion == 1 and "/reviews" or "/comments"),
                    )
                except InvenioWebAccessMailCookieError:
                    # Invalid or empty cookie: continue
                    pass

            subscribe = False
            if argd["subscribe"] and get_user_subscription_to_discussion(self.recid, uid) == 0:
                # User is not already subscribed, and asked to subscribe
                subscribe = True

            body = perform_request_add_comment_or_remark(
                recID=self.recid,
                ln=argd["ln"],
                uid=uid,
                action=argd["action"],
                msg=argd["msg"],
                note=argd["note"],
                score=argd["score"],
                reviews=self.discussion,
                comID=argd["comid"],
                client_ip_address=client_ip_address,
                editor_type=argd["editor_type"],
                can_attach_files=can_attach_files,
                subscribe=subscribe,
                req=req,
                attached_files=added_files,
                warnings=warning_msgs,
            )

            if self.discussion:
                title = _("Add Review")
            else:
                title = _("Add Comment")

            jqueryheader = """
            <script src="%(CFG_SITE_URL)s/vendors/jquery-multifile/jquery.MultiFile.pack.js" type="text/javascript"></script>
            """ % {
                "CFG_SITE_URL": CFG_SITE_URL
            }

            return page(
                title=title,
                body=body,
                navtrail=navtrail,
                uid=uid,
                language=CFG_SITE_LANG,
                verbose=1,
                req=req,
                navmenuid="search",
                metaheaderadd=jqueryheader,
            )
        # id not in range
        else:
            return page(title=_("Record Not Found"), body=problem, uid=uid, verbose=1, req=req, navmenuid="search")
Exemplo n.º 44
0
    def remove(self, req, form):

        argd = wash_urlargd(form, {'name': (str, None),
                                   'idq': (int, None),
                                   'idb': (int, None),
                                   })

        uid = getUid(req)

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

        # load the right language
        _ = gettext_set_language(argd['ln'])
        user_info = collect_user_info(req)
        if not user_info['precached_usealerts']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use alerts."))

        try:
            html = webalert.perform_remove_alert(argd['name'], argd['idq'],
                                                 argd['idb'], uid, ln=argd['ln'])
        except webalert.AlertError as msg:
            return page(title=_("Error"),
                        body=webalert_templates.tmpl_errorMsg(ln=argd['ln'], error_msg=msg),
                        navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                     'sitesecureurl' : CFG_SITE_SECURE_URL,
                                     'ln': argd['ln'],
                                     'account' : _("Your Account"),
                                  },
                        description=_("%(x_name)s Personalize, Set a new alert", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                        keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                        uid=uid,
                        language=argd['ln'],
                        req=req,
                        lastupdated=__lastupdated__,
                        navmenuid='youralerts')


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

        # display success
        return page(title=_("Display alerts"),
                    body=html,
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s Personalize, Display alerts", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts')
Exemplo n.º 45
0
    def managedocfiles(self, req, form):
        """
        Display admin interface to manage files of a record
        """
        argd = wash_urlargd(form, {
            'ln': (str, ''),
            'access': (str, ''),
            'recid': (int, None),
            'do': (int, 0),
            'cancel': (str, None),
            })

        _ = gettext_set_language(argd['ln'])
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check authorization
        (auth_code, auth_msg) = acc_authorize_action(req,
                                                     'runbibdocfile')
        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_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, referer="/%s/managedocfiles" % CFG_SITE_RECORD,
                                       uid=uid, text=auth_msg,
                                       ln=argd['ln'],
                                       navmenuid="admin")

        # Prepare navtrail
        navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> &gt; %(manage_files)s''' \
        % {'CFG_SITE_URL': CFG_SITE_URL,
           'manage_files': _("Manage Document Files")}

        body = ''
        if argd['do'] != 0 and not argd['cancel']:
            # Apply modifications
            working_dir = os.path.join(CFG_TMPSHAREDDIR,
                                       'websubmit_upload_interface_config_' + str(uid),
                                       argd['access'])
            if not os.path.isdir(working_dir):
                # We accessed the url without preliminary steps
                # (we did not upload a file)
                # Our working dir does not exist
                # Display the file manager
                argd['do'] = 0
            else:
                move_uploaded_files_to_storage(working_dir=working_dir,
                                               recid=argd['recid'],
                                               icon_sizes=['180>', '700>'],
                                               create_icon_doctypes=['*'],
                                               force_file_revision=False)
                # Clean temporary directory
                shutil.rmtree(working_dir)

                # Confirm modifications
                body += '<p style="color:#0f0">%s</p>' % \
                        (_('Your modifications to record #%(x_redid)i have been submitted', x_redid=argd['recid']))
        elif argd['cancel']:
            # Clean temporary directory
            working_dir = os.path.join(CFG_TMPSHAREDDIR,
                                       'websubmit_upload_interface_config_' + str(uid),
                                       argd['access'])
            shutil.rmtree(working_dir)
            body += '<p style="color:#c00">%s</p>' % \
                    (_('Your modifications to record #%(x_num)i have been cancelled', x_num=argd['recid']))

        if not argd['recid'] or argd['do'] != 0:
            body += '''
        <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">
        <label for="recid">%(edit_record)s:</label>
        <input type="text" name="recid" id="recid" />
        <input type="submit" value="%(edit)s" class="adminbutton" />
        </form>
        ''' % {'edit': _('Edit'),
               'edit_record': _('Edit record'),
               'CFG_SITE_URL': CFG_SITE_URL,
               'CFG_SITE_RECORD': CFG_SITE_RECORD}

        access = time.strftime('%Y%m%d_%H%M%S')
        if argd['recid'] and argd['do'] == 0:
            # Displaying interface to manage files
            # Prepare navtrail
            title, dummy_description, dummy_keywords = websearch_templates.tmpl_record_page_header_content(req, argd['recid'],
                                                                                               argd['ln'])
            navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> &gt;
        <a class="navtrail" href="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">%(manage_files)s</a> &gt;
        %(record)s: %(title)s
        ''' \
            % {'CFG_SITE_URL': CFG_SITE_URL,
               'title': title,
               'manage_files': _("Document File Manager"),
               'record': _("Record #%(x_rec)i", x_rec=argd['recid']),
               'CFG_SITE_RECORD': CFG_SITE_RECORD}

            body += create_file_upload_interface(\
                recid=argd['recid'],
                ln=argd['ln'],
                uid=uid,
                sbm_access=access,
                display_hidden_files=True,
                restrictions_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_RESTRICTIONS,
                doctypes_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_DOCTYPES,
                **CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_MISC)[1]

            body += '''<br />
            <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">
            <input type="hidden" name="recid" value="%(recid)s" />
            <input type="hidden" name="do" value="1" />
            <input type="hidden" name="access" value="%(access)s" />
            <input type="hidden" name="ln" value="%(ln)s" />
            <div style="font-size:small">
    <input type="submit" name="cancel" value="%(cancel_changes)s" />
    <input type="submit" onclick="user_must_confirm_before_leaving_page=false;return true;" class="adminbutton" name="submit" id="applyChanges" value="%(apply_changes)s" />
    </div></form>''' % \
    {'apply_changes': _("Apply changes"),
     'cancel_changes': _("Cancel all changes"),
     'recid': argd['recid'],
     'access': access,
     'ln': argd['ln'],
     'CFG_SITE_URL': CFG_SITE_URL,
     'CFG_SITE_RECORD': CFG_SITE_RECORD}

        return page(title = _("Document File Manager") + (argd['recid'] and (': ' + _("Record #%(x_rec)i", x_rec=argd['recid'])) or ''),
                    navtrail=navtrail,
                    navtrail_append_title_p=0,
                    metaheaderadd = get_upload_file_interface_javascript(form_url_params='?access='+access) + \
                                    get_upload_file_interface_css(),
                    body = body,
                    uid = uid,
                    language=argd['ln'],
                    req=req,
                    navmenuid='admin')
Exemplo n.º 46
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(get_record(self.recid).legacy_create_recstruct()):
                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':
                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:
                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 as 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 %(x_form)s does not exist for the given version: %(x_vers)s",
                                            x_form=cgi.escape(docformat), x_vers=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 as 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 as msg:
                            register_exception(req=req, alert_admin=True)

            if docname and docformat and not warn:
                req.status = apache.HTTP_NOT_FOUND
                warn += write_warning(_("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)
            cc_id = Collection.query.filter_by(name=cc).value('id')
            unordered_tabs = None  # get_detailed_page_tabs(cc_id, self.recid, ln)
            ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in iteritems(unordered_tabs)]
            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]

            tabs_counts = {}  # get_detailed_page_tabs_counts(self.recid)
            top = webstyle_templates.detailed_record_container_top(self.recid,
                                                                   tabs,
                                                                   args['ln'],
                                                                   citationnum=tabs_counts['Citations'],
                                                                   referencenum=tabs_counts['References'],
                                                                   discussionnum=tabs_counts['Discussions'])
            bottom = webstyle_templates.detailed_record_container_bottom(self.recid,
                                                                         tabs,
                                                                         args['ln'])
            title, description, keywords = websearch_templates.tmpl_record_page_header_content(req, self.recid, args['ln'])
            return pageheaderonly(title=title,
                        navtrail=create_navtrail_links(cc=cc, aas=0, ln=ln) + \
                                        ''' &gt; <a class="navtrail" href="%s/%s/%s">%s</a>
                                        &gt; %s''' % \
                        (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, title, _("Access to Fulltext")),

                        description=description,
                        keywords=keywords,
                        uid=uid,
                        language=ln,
                        req=req,
                        navmenuid='search',
                        navtrail_append_title_p=0) + \
                        websearch_templates.tmpl_search_pagestart(ln) + \
                        top + t + bottom + \
                        websearch_templates.tmpl_search_pageend(ln) + \
                        pagefooteronly(language=ln, req=req)
Exemplo n.º 47
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 = (
                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)

        # 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 = (
                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)
        elif auth_code:
            return page_not_authorized(req, "../", text=auth_msg, ln=argd["ln"])

        # Check that comment is not currently deleted
        if is_comment_deleted(argd["comid"]):
            return page_not_authorized(
                req, "../", text=_("You cannot access files of a deleted comment"), 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"]
        )
Exemplo n.º 48
0
    def send(self, req, form):
        """
        Sends the message.

        Possible form keys:
        @param msg_to_user: comma separated usernames.
        @type msg_to_user: string
        @param msg_to_group: comma separated groupnames.
        @type msg_to_group: string
        @param msg_subject: message subject.
        @type msg_subject: string
        @param msg_body: message body.
        @type msg_body: string
        @param msg_send_year: year to send this message on.
        @type msg_send_year: int
        @param_msg_send_month: month to send this message on
        @type msg_send_month: year
        @param_msg_send_day: day to send this message on
        @type msg_send_day: int
        @param results_field: value determining which results field to display.
                              See CFG_WEBMESSAGE_RESULTS_FIELD in
                              webmessage_config.py.
        @param names_to_add: list of usernames to add to
                             msg_to_user / group.
        @type names_to_add: list of strings
        @param search_pattern: will search for users/groups with this pattern.
        @type search_pattern: string
        @param add_values: if 1 users_to_add will be added to msg_to_user
                           field.
        @type add_values: int
        @param *button: which button was pressed.
        @param ln: language.
        @type ln: string
        @return: body.
        """
        argd = wash_urlargd(form, {'msg_to_user': (str, ""),
                                   'msg_to_group': (str, ""),
                                   'msg_subject': (str, ""),
                                   'msg_body': (str, ""),
                                   'msg_send_year': (int, 0),
                                   'msg_send_month': (int, 0),
                                   'msg_send_day': (int, 0),
                                   'results_field': (str,
                                        CFG_WEBMESSAGE_RESULTS_FIELD['NONE']),
                                   'names_selected': (list, []),
                                   'search_pattern': (str, ""),
                                   'send_button': (str, ""),
                                   'search_user': (str, ""),
                                   'search_group': (str, ""),
                                   'add_user': (str, ""),
                                   'add_group': (str, ""),
                                   })
        # Check if user is logged
        uid = getUid(req)
        _ = gettext_set_language(argd['ln'])
        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourmessages/send" % \
                                             (CFG_SITE_URL,),
                                       navmenuid="yourmessages")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/yourmessages/send%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

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

        if argd['send_button']:
            (body, title, navtrail) = perform_request_send(
                            uid=uid,
                            msg_to_user=argd['msg_to_user'],
                            msg_to_group=argd['msg_to_group'],
                            msg_subject=escape_html(argd['msg_subject']),
                            msg_body=escape_email_quoted_text(argd['msg_body']),
                            msg_send_year=argd['msg_send_year'],
                            msg_send_month=argd['msg_send_month'],
                            msg_send_day=argd['msg_send_day'],
                            ln=argd['ln'])
        else:
            title = _('Write a message')
            navtrail = get_navtrail(argd['ln'], title)
            if argd['search_user']:
                argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['USER']
            elif argd['search_group']:
                argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['GROUP']
            add_values = 0
            if argd['add_group'] or argd['add_user']:
                add_values = 1
            body = perform_request_write_with_search(
                            uid=uid,
                            msg_to_user=argd['msg_to_user'],
                            msg_to_group=argd['msg_to_group'],
                            msg_subject=escape_html(argd['msg_subject']),
                            msg_body=escape_email_quoted_text(argd['msg_body']),
                            msg_send_year=argd['msg_send_year'],
                            msg_send_month=argd['msg_send_month'],
                            msg_send_day=argd['msg_send_day'],
                            names_selected=argd['names_selected'],
                            search_pattern=argd['search_pattern'],
                            results_field=argd['results_field'],
                            add_values=add_values,
                            ln=argd['ln'])
        return page(title       = title,
                    body        = body,
                    navtrail    = navtrail,
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)