def issue_control(self, req, form): """ page that allows full control over creating, backtracing, adding to, removing from issues. """ argd = wash_urlargd( form, { "name": (str, ""), "add": (str, ""), "action_publish": (str, "cfg"), "issue_number": (list, []), "ln": (str, ""), }, ) redirect_to_url( req, CFG_SITE_SECURE_URL + "/admin/webjournal/webjournaladmin.py/issue_control?journal_name=" + argd["name"] + "&ln=" + argd["ln"] + "&issue=" + argd["issue_number"] + "&action=" + argd["action_publish"], )
def sub(self, req, form): """DEPRECATED: /submit/sub is deprecated now, so raise email to the admin (but allow submission to continue anyway)""" args = wash_urlargd(form, {"password": (str, "")}) uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "../sub/", navmenuid="submit") try: raise DeprecationWarning, 'submit/sub handler has been used. Please use submit/direct. e.g. "submit/sub?RN=123@SBIFOO" -> "submit/direct?RN=123&sub=SBIFOO"' except DeprecationWarning: register_exception(req=req, alert_admin=True) ln = args["ln"] _ = gettext_set_language(ln) # DEMOBOO_RN=DEMO-BOOK-2008-001&ln=en&password=1223993532.26572%40APPDEMOBOO params = dict(form) password = args["password"] if password: del params["password"] if "@" in password: params["access"], params["sub"] = password.split("@", 1) else: params["sub"] = password else: args = str(req.args).split("@") if len(args) > 1: params = {"sub": args[-1]} args = "@".join(args[:-1]) params.update(cgi.parse_qs(args)) else: return warningMsg(_("Sorry, invalid URL..."), req, ln=ln) url = "%s/submit/direct?%s" % (CFG_SITE_URL, urlencode(params, doseq=True)) redirect_to_url(req, url)
def perform_request_article(req, journal_name, issue_number, ln, category, recid, editor=False, verbose=0): """ Central logic function for article pages. Loads the format template for article display and displays the requested article using BibFormat. 'Editor' mode generates edit links on the article view page and disables caching. """ current_issue = get_current_issue(ln, journal_name) if not get_release_datetime(issue_number, journal_name): # Unreleased issue. Display latest released issue? unreleased_issues_mode = get_unreleased_issue_hiding_mode(journal_name) if not editor and ( unreleased_issues_mode == "all" or (unreleased_issues_mode == "future" and issue_is_later_than(issue_number, current_issue)) ): redirect_to_url( req, "%s/journal/%s/%s/%s?ln=%s" % (CFG_SITE_URL, journal_name, current_issue.split("/")[1], current_issue.split("/")[0], ln), ) try: index_page_template = get_journal_template("detailed", journal_name, ln) except InvenioWebJournalTemplateNotFoundError, e: register_exception(req=req) return e.user_box(req)
def new_dataset(req, title=None, paper=None, authors=None, description=None, dataset_file=None, doi="", submitter_name=None, submitter_email=None, comments=None): """Form handler for dataset submissions.""" import uuid title = wash_url_argument(title, "str") paper = wash_url_argument(paper, "str") authors = wash_url_argument(authors, "str") description = wash_url_argument(description, "str") submitter_name = wash_url_argument(submitter_name, "str") submitter_email = wash_url_argument(submitter_email, "str") comments = wash_url_argument(comments, "str") dataset_file = wash_url_argument(dataset_file, "str") tmp_id = str(uuid.uuid1()) if dataset_file: f = open(CFG_TMPSHAREDDIR + 'dataset-submission-' + tmp_id, 'wb') f.write(req.form["dataset_file"].file.read()) f.close() res = submit_email_ticket(title, paper, authors, description, tmp_id, req.form["dataset_file"].filename, doi, submitter_name, submitter_email, comments) if res: return redirect_to_url( req, "%s/data_submission.py/data_submission_success?title=%s" % (CFG_SITE_URL, title) ) else: return redirect_to_url( req, "%s/data_submission.py/data_submission_fail?title=%s" % (CFG_SITE_URL, title) )
def __call__(self, req, form): """Redirect calls without final slash.""" if self.recid: redirect_to_url(req, '%s/record/%s/edit/' % (CFG_SITE_URL, self.recid)) else: redirect_to_url(req, '%s/record/edit/' % CFG_SITE_URL)
def _getfile_py(req, recid=0, docid=0, version="", name="", docformat="", ln=CFG_SITE_LANG): if not recid: ## Let's obtain the recid from the docid if docid: try: bibdoc = BibDoc(docid=docid) recid = bibdoc.bibrec_links[0]["recid"] except InvenioBibDocFileError: return warning_page(_("An error has happened in trying to retrieve the requested file."), req, ln) else: return warning_page(_("Not enough information to retrieve the document"), req, ln) else: brd = BibRecDocs(recid) if not name and docid: ## Let's obtain the name from the docid try: name = brd.get_docname(docid) except InvenioBibDocFileError: return warning_page(_("An error has happened in trying to retrieving the requested file."), req, ln) docformat = normalize_format(docformat) redirect_to_url( req, "%s/%s/%s/files/%s%s?ln=%s%s" % (CFG_SITE_URL, CFG_SITE_RECORD, recid, name, docformat, ln, version and "version=%s" % version or ""), apache.HTTP_MOVED_PERMANENTLY, )
def subscribe(self, req, form): """ Subscribe current user to receive email notification when new comments are added to current discussion. """ argd = wash_urlargd(form, {'referer': (str, None)}) uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)}) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) success = subscribe_user_to_discussion(self.recid, uid) display_url = "%s/record/%s/comments/display?subscribed=%s&ln=%s" % \ (CFG_SITE_URL, self.recid, str(success), argd['ln']) redirect_to_url(req, display_url)
def kb_add(req, ln=CFG_SITE_LANG, sortby="to", kbtype=""): """ Adds a new kb @param req the request @param ln language @param sortby to or from @param kbtype type of knowledge base. one of: "", taxonomy, dynamic """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = ''' > <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases")) try: dummy = getUid(req) except: return error_page('Error', req) (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge') if not auth_code: name = "Untitled" if kbtype == "taxonomy": name = "Untitled Taxonomy" if kbtype == "dynamic": name = "Untitled dynamic" kb_id = bibknowledge.add_kb(kb_name=name, kb_type=kbtype) redirect_to_url(req, "kb?ln=%(ln)s&action=attributes&kb=%(kb)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby}) else: navtrail_previous_links = ''' > <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases")) return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
def unsubscribe(self, req, form): """ Unsubscribe current user from current discussion. """ argd = wash_urlargd(form, {"referer": (str, None)}) user_info = collect_user_info(req) uid = getUid(req) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)} ) target = "/youraccount/login" + make_canonical_urlargd( {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_URL + user_info["uri"]}, {} ) return redirect_to_url(req, target, norobot=True) success = unsubscribe_user_from_discussion(self.recid, uid) display_url = "%s/record/%s/comments/display?subscribed=%s&ln=%s" % ( CFG_SITE_URL, self.recid, str(-success), argd["ln"], ) redirect_to_url(req, display_url)
def output_format_add(req, ln=CFG_SITE_LANG): """ Adds a new output format @param req: the request object @param ln: language @return: a web page (or redirection to a web page) """ ln = wash_language(ln) _ = gettext_set_language(ln) try: uid = getUid(req) except: return error_page('Error', req) (auth_code, auth_msg) = check_user(req, 'cfgbibformat') if not auth_code: bfo = bibformatadminlib.add_output_format() if bfo == None: return page(title=_("Cannot create output format"), body = """BibFormat cannot add an output format. Check output formats directory permissions.""", language=ln, lastupdated=__lastupdated__, req=req) redirect_to_url(req, "output_format_show_attributes?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln, 'bfo':bfo}) else: return page_not_authorized(req=req, text=auth_msg)
def __call__(self, req, form): argd = wash_urlargd(form, { 'id' : (int, 0), 'format' : (str, '')}) formats_dict = get_output_formats(True) formats = {} for f in formats_dict.values(): if f['attrs']['visibility']: formats[f['attrs']['code'].lower()] = f['attrs']['content_type'] del formats_dict if argd['id'] and argd['format']: ## Translate back common format names f = { 'nlm' : 'xn', 'marcxml' : 'xm', 'dc' : 'xd', 'endnote' : 'xe', 'mods' : 'xo' }.get(argd['format'], argd['format']) if f in formats: redirect_to_url(req, '%s/%s/%s/export/%s' % (CFG_SITE_URL, CFG_SITE_RECORD, argd['id'], f)) else: raise apache.SERVER_RETURN, apache.HTTP_NOT_ACCEPTABLE elif argd['id']: return websearch_templates.tmpl_unapi(formats, identifier=argd['id']) else: return websearch_templates.tmpl_unapi(formats)
def perform_request_index(req, journal_name, issue_number, ln, category, editor=False, verbose=0): """ Central logic function for index pages. Brings together format templates and MARC rules from the config, with the requested index page, given by the url parameters. From config: - page template for index pages -> formatting - MARC rule list -> Category Navigation - MARC tag used for issue numbers -> search (later in the format elements) Uses BibFormatObject and format_with_format_template to produce the required HTML. """ current_issue = get_current_issue(ln, journal_name) if not get_release_datetime(issue_number, journal_name): # Unreleased issue. Display latest released issue? unreleased_issues_mode = get_unreleased_issue_hiding_mode(journal_name) if not editor and ( unreleased_issues_mode == "all" or (unreleased_issues_mode == "future" and issue_is_later_than(issue_number, current_issue)) ): redirect_to_url( req, "%s/journal/%s/%s/%s?ln=%s" % (CFG_SITE_URL, journal_name, current_issue.split("/")[1], current_issue.split("/")[0], ln), ) try: index_page_template = get_journal_template("index", journal_name, ln) except InvenioWebJournalTemplateNotFoundError, e: register_exception(req=req) return e.user_box(req)
def new_ticket(self, req, form): """handle a edit/new_ticket request""" argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG), 'recid': (int, 0)}) ln = argd['ln'] _ = gettext_set_language(ln) auth_code, auth_message = acc_authorize_action(req, 'runbibedit') if auth_code != 0: return page_not_authorized(req=req, referer="/edit", text=auth_message, navtrail=navtrail) uid = getUid(req) if argd['recid']: (errmsg, url) = perform_request_newticket(argd['recid'], uid) if errmsg: return page(title = _("Failed to create a ticket"), body = _("Error")+": "+errmsg, errors = [], warnings = [], uid = uid, language = ln, navtrail = navtrail, lastupdated = __lastupdated__, req = req) else: #redirect.. redirect_to_url(req, url)
def openurl(self, req, form): """ OpenURL Handler.""" argd = wash_urlargd(form, websearch_templates.tmpl_openurl_accepted_args) ret_url = websearch_templates.tmpl_openurl2invenio(argd) if ret_url: return redirect_to_url(req, ret_url) else: return redirect_to_url(req, CFG_SITE_URL)
def __call__(self, req, form): """Redirect calls without final slash.""" if self.recid: redirect_to_url(req, '%s/%s/%s/edit/' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid)) else: redirect_to_url(req, '%s/%s/edit/' % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD))
def report(self, req, form): """ Report a comment/review for inappropriate content @param comid: comment/review id @param recid: the id of the record the comment/review is associated with @param ln: language @param do: display order hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param ds: display since all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param nb: number of results per page @param p: results page @param referer: http address of the calling function to redirect to (refresh) @param reviews: boolean, enabled for reviews, disabled for comments """ argd = wash_urlargd(form, {'comid': (int, -1), 'recid': (int, -1), 'do': (str, "od"), 'ds': (str, "all"), 'nb': (int, 100), 'p': (int, 1), 'referer': (str, None) }) client_ip_address = req.remote_ip uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if (auth_code and not user_info['apache_user']) or user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)}) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) success = perform_request_report(argd['comid'], client_ip_address, uid) if argd['referer']: argd['referer'] += "?ln=%s&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/record/%s/%s/display?ln=%s&voted=1" referer %= (CFG_SITE_URL, self.recid, self.discussion==1 and 'reviews' or 'comments', argd['ln']) redirect_to_url(req, referer)
def _index(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode): auth_args = {} if doctype: auth_args['doctype'] = doctype if act: auth_args['act'] = act uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "direct", navmenuid='submit') if CFG_CERN_SITE: ## HACK BEGIN: this is a hack for CMS and ATLAS draft user_info = collect_user_info(req) if doctype == 'CMSPUB' and act == "" and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**': if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) if 'cms-publication-committee-chair [CERN]' not in user_info['group']: return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of the CMS Publication Committee Chair.", navmenuid='submit') elif doctype == 'ATLPUB' and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**': if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) if 'atlas-gen [CERN]' not in user_info['group']: return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of ATLAS.", navmenuid='submit') ## HACK END if doctype == "": catalogues_text, at_least_one_submission_authorized, submission_exists = makeCataloguesTable(req, ln=CFG_SITE_LANG) if not at_least_one_submission_authorized and submission_exists: if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) else: return page_not_authorized(req, "../submit", uid=uid, navmenuid='submit') return home(req, catalogues_text, c, ln) elif act == "": return action(req, c, ln, doctype) elif int(step)==0: return interface(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage) else: return endaction(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode)
def _export(mime, content, req): """ Helper function to pass on the export call. Create a temporary file in which the content is stored, then let redirect to the export web interface. """ filename = CFG_TMPDIR + "/webstat_export_" + str(time.time()).replace(".", "") open(filename, "w").write(content) redirect_to_url(req, "%s/stats/export?filename=%s&mime=%s" % (CFG_SITE_URL, os.path.basename(filename), mime))
def __call__(self, req, form): ''' Serves the main person page. Will use the object's person id to get a person's information. @param req: apache request object @type req: apache request object @param form: POST/GET variables of the request @type form: dict @return: a full page formatted in HTML @rtype: str ''' if not CFG_WEBAUTHORPROFILE_USE_BIBAUTHORID: self.person_id = self.original_search_parameter return self.index(req, form) argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG), 'recid': (int, -1), 'verbose': (int, 0)}) ln = argd['ln'] verbose = argd['verbose'] url_args = dict() if ln != CFG_SITE_LANG: url_args['ln'] = ln if verbose: url_args['verbose'] = str(verbose) encoded = urlencode(url_args) if encoded: encoded = '?' + encoded if self.cid is not None and self.original_search_parameter != self.cid: return redirect_to_url(req, '%s/author/profile/%s%s' % (CFG_SITE_URL, self.cid, encoded)) # author may have only author identifier and not a canonical id if self.person_id > -1: return self.index(req, form) recid = argd['recid'] if recid > -1: possible_authors = search_person_ids_by_name(self.original_search_parameter, limit_to_recid = recid) if len(possible_authors) == 1: self.person_id = possible_authors[0][0] self.cid = get_person_redirect_link(self.person_id) redirect_to_url(req, '%s/author/profile/%s%s' % (CFG_SITE_URL, self.cid, encoded)) encoded = urlencode(url_args) if encoded: encoded = '&' + encoded return redirect_to_url(req, '%s/author/search?q=%s%s' % (CFG_SITE_URL, self.original_search_parameter, encoded))
def confirm(self, req, form): """ Function called after submitting the metadata upload form. Shows a summary of actions to be performed and possible errors """ argd = wash_urlargd(form, {'metafile': (Field, None), 'filetype': (str, None), 'mode': (str, None), 'submit_date': (str, None), 'submit_time': (str, None), 'filename': (str, None), 'priority': (str, None), 'skip_simulation': (str, None), 'email_logs_to': (str, None)}) _ = gettext_set_language(argd['ln']) # Check if the page is directly accessed or no file selected if not argd['metafile']: redirect_to_url(req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL)) metafile = argd['metafile'].value if argd['filetype'] != 'marcxml': metafile = _transform_input_to_marcxml(file_input=metafile) date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \ and argd['submit_date'] or '' time = argd['submit_time'] not in ['hh:mm:ss', ''] \ and argd['submit_time'] or '' errors_upload = '' skip_simulation = argd['skip_simulation'] == "skip" if not skip_simulation: errors_upload = perform_upload_check(metafile, argd['mode']) body = batchuploader_templates.tmpl_display_confirm_page(argd['ln'], metafile, argd['filetype'], argd['mode'], date, time, argd['filename'], argd['priority'], errors_upload, skip_simulation, argd['email_logs_to']) uid = getUid(req) navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \ (CFG_SITE_SECURE_URL, _("Metadata batch upload")) title = 'Confirm your actions' return page(title = title, body = body, metaheaderadd = batchuploader_templates.tmpl_styles(), uid = uid, navtrail = navtrail, lastupdated = __lastupdated__, req = req, language = argd['ln'], navmenuid = "batchuploader")
def regenerate(self, req, form): """ Clears the cache for the issue given. """ argd = wash_urlargd(form, {'name': (str, ""), 'issue': (str, ""), 'ln': (str, "")}) redirect_to_url(req, CFG_SITE_SECURE_URL + \ '/admin/webjournal/webjournaladmin.py/regenerate?journal_name=' + \ argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue'])
def del_com(req, ln=CFG_SITE_LANG, action="delete", **hidden): """ private function Delete a comment @param req: request object to obtain user information @param ln: language @param **hidden: ids of comments to delete sent as individual variables comidX=on, where X is id """ ln = wash_language(ln) action = wash_url_argument(action, 'str') _ = gettext_set_language(ln) navtrail_previous_links = getnavtrail() navtrail_previous_links += ' > <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL navtrail_previous_links += _("WebComment Admin") + '</a>' try: uid = getUid(req) except Error: return page(title=_("Internal Error"), body = create_error_box(req, verbose=0, ln=ln), description="%s - Internal Error" % CFG_SITE_NAME, keywords="%s, Internal Error" % CFG_SITE_NAME, language=ln, req=req) (auth_code, auth_msg) = check_user(req,'cfgwebcomment') if (auth_code != 'false'): comIDs = [] args = hidden.keys() for var in args: try: comIDs.append(int(var.split('comid')[1])) except: pass if action == 'delete': body = perform_request_del_com(ln=ln, comIDs=comIDs) title = _("Delete comments") elif action == 'unreport': body = suppress_abuse_report(ln=ln, comIDs=comIDs) title = _("Suppress abuse reports") elif action == 'undelete': body = perform_request_undel_com(ln=ln, comIDs=comIDs) title = _("Undelete comments") else: redirect_to_url(req, CFG_SITE_URL + '/admin/webcomment/webcommentadmin.py') return page(title=title, body=body, uid=uid, language=ln, navtrail = navtrail_previous_links, lastupdated=__lastupdated__, req=req) else: return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
def metasubmit(self, req, form): """ Function called after submitting the metadata upload form. Checks if input fields are correct before uploading. """ argd = wash_urlargd(form, {'metafile': (str, None), 'filetype': (str, None), 'mode': (str, None), 'submit_date': (str, None), 'submit_time': (str, None), 'filename': (str, None), 'priority': (str, None), 'email_logs_to': (str, None)}) _ = gettext_set_language(argd['ln']) # Check if the page is directly accessed if argd['metafile'] == None: redirect_to_url(req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL)) not_authorized = user_authorization(req, argd['ln']) if not_authorized: return not_authorized date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \ and argd['submit_date'] or '' time = argd['submit_time'] not in ['hh:mm:ss', ''] \ and argd['submit_time'] or '' auth_code, auth_message = metadata_upload(req, argd['metafile'], argd['filetype'], argd['mode'].split()[0], date, time, argd['filename'], argd['ln'], argd['priority'], argd['email_logs_to']) if auth_code == 1: # not authorized referer = '/batchuploader/' return page_not_authorized(req=req, referer=referer, text=auth_message, navmenuid="batchuploader") else: uid = getUid(req) body = batchuploader_templates.tmpl_display_menu(argd['ln']) body += batchuploader_templates.tmpl_upload_successful(argd['ln']) title = _("Upload successful") navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \ (CFG_SITE_SECURE_URL, _("Metadata batch upload")) return page(title = title, body = body, uid = uid, navtrail = navtrail, lastupdated = __lastupdated__, req = req, language = argd['ln'], navmenuid = "batchuploader")
def feature_record(self, req, form): """ Interface to feature a record. Will be saved in a flat file. """ argd = wash_urlargd(form, {'name': (str, ""), 'recid': (str, "init"), 'url': (str, "init"), 'ln': (str, "")}) redirect_to_url(req, CFG_SITE_SECURE_URL + \ '/admin/webjournal/webjournaladmin.py/feature_record?journal_name=' + \ argd['name'] + '&ln=' + argd['ln'] + '&recid='+ argd['recid'] + '&url='+ argd['url'])
def kb_edit_mapping(req, kb, key, mapFrom, mapTo, update="", delete="", sortby="to", ln=CFG_SITE_LANG): """ Edit a mapping to in kb. Edit can be "update old value" or "delete existing value" @param kb the knowledge base id to edit @param key the key of the mapping that will be modified @param mapFrom the new key of the mapping @param mapTo the new value of the mapping @param update contains a value if the mapping is to be updated @param delete contains a value if the mapping is to be deleted @param sortby the sorting criteria ('from' or 'to') """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = ''' > <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases")) try: dummy = getUid(req) except: return error_page('Error', req) (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge') if not auth_code: kb_id = wash_url_argument(kb, 'int') kb_name = bibknowledge.get_kb_name(kb_id) if kb_name is None: return page(title=_("Unknown Knowledge Base"), body = "", language=ln, navtrail = navtrail_previous_links, errors = [("ERR_KB_ID_UNKNOWN", kb)], lastupdated=__lastupdated__, req=req) key = wash_url_argument(key, 'str') if delete != "": #Delete bibknowledge.remove_kb_mapping(kb_name, key) if update != "": #Update new_key = wash_url_argument(mapFrom, 'str') new_value = wash_url_argument(mapTo, 'str') bibknowledge.update_kb_mapping(kb_name, key, new_key, new_value) redirect_to_url(req, "kb?ln=%(ln)s&kb=%(kb)s&sortby=%(sortby)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby}) else: return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
def direct(self, req, form): """Directly redirected to an initialized submission.""" args = wash_urlargd(form, {'sub': (str, ''), 'access' : (str, '')}) sub = args['sub'] access = args['access'] ln = args['ln'] _ = gettext_set_language(ln) uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "direct", navmenuid='submit') myQuery = req.args if not sub: return warning_page(_("Sorry, 'sub' parameter missing..."), req, ln=ln) res = run_sql("SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s", (sub,)) if not res: return warning_page(_("Sorry. Cannot analyse parameter"), req, ln=ln) else: # get document type doctype = res[0][0] # get action name action = res[0][1] # retrieve other parameter values params = dict(form) # find existing access number if not access: # create 'unique' access number pid = os.getpid() now = time.time() access = "%i_%s" % (now, pid) # retrieve 'dir' value res = run_sql ("SELECT dir FROM sbmACTION WHERE sactname=%s", (action,)) dir = res[0][0] mainmenu = req.headers_in.get('referer') params['access'] = access params['act'] = action params['doctype'] = doctype params['startPg'] = '1' params['mainmenu'] = mainmenu params['ln'] = ln params['indir'] = dir url = "%s/submit?%s" % (CFG_SITE_SECURE_URL, urlencode(params)) redirect_to_url(req, url)
def issue_control(self, req, form): """ page that allows full control over creating, backtracing, adding to, removing from issues. """ argd = wash_urlargd(form, {'name': (str, ""), 'add': (str, ""), 'action_publish': (str, "cfg"), 'issue_number': (list, []), 'ln': (str, "")}) redirect_to_url(req, CFG_SITE_SECURE_URL + \ '/admin/webjournal/webjournaladmin.py/issue_control?journal_name=' + \ argd['name'] + '&ln=' + argd['ln'] + '&issue=' + argd['issue_number'] + \ '&action=' + argd['action_publish'])
def docsubmit(self, req, form): """ Function called after submitting the document upload form. Performs the appropiate action depending on the input parameters """ argd = wash_urlargd(form, {'docfolder': (str, ""), 'matching': (str, ""), 'mode': (str, ""), 'submit_date': (str, ""), 'submit_time': (str, ""), 'priority': (str, "")}) _ = gettext_set_language(argd['ln']) not_authorized = user_authorization(req, argd['ln']) if not_authorized: return not_authorized #Check if input fields are correct, if not, redirect to upload form correct_date = check_date(argd['submit_date']) correct_time = check_time(argd['submit_time']) if correct_time != 0: redirect_to_url(req, "%s/batchuploader/documents?error=1&mode=%s&docfolder=%s&matching=%s&submit_date=%s" % (CFG_SITE_SECURE_URL, argd['mode'], argd['docfolder'], argd['matching'], argd['submit_date'])) if correct_date != 0: redirect_to_url(req, "%s/batchuploader/documents?error=%s&mode=%s&docfolder=%s&matching=%s&submit_time=%s" % (CFG_SITE_SECURE_URL, correct_date, argd['mode'], argd['docfolder'], argd['matching'], argd['submit_time'])) date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \ and argd['submit_date'] or '' time = argd['submit_time'] not in ['hh:mm:ss', ''] \ and argd['submit_time'] or '' if date != '' and time == '': redirect_to_url(req, "%s/batchuploader/documents?error=1&mode=%s&docfolder=%s&matching=%s&submit_date=%s" % (CFG_SITE_SECURE_URL, argd['mode'], argd['docfolder'], argd['matching'], argd['submit_date'])) elif date == '' and time != '': redirect_to_url(req, "%s/batchuploader/documents?error=4&mode=%s&docfolder=%s&matching=%s&submit_time=%s" % (CFG_SITE_SECURE_URL, argd['mode'], argd['docfolder'], argd['matching'], argd['submit_time'])) errors, info = document_upload(req, argd['docfolder'], argd['matching'], argd['mode'], date, time, argd['ln'], argd['priority']) body = batchuploader_templates.tmpl_display_menu(argd['ln']) uid = getUid(req) navtrail = '''<a class="navtrail" href="%s/batchuploader/documents">%s</a>''' % \ (CFG_SITE_SECURE_URL, _("Document batch upload")) body += batchuploader_templates.tmpl_display_web_docupload_result(argd['ln'], errors, info) title = _("Document batch upload result") return page(title = title, body = body, metaheaderadd = batchuploader_templates.tmpl_styles(), uid = uid, navtrail = navtrail, lastupdated = __lastupdated__, req = req, language = argd['ln'], navmenuid = "batchuploader")
def output_format_update_attributes(req, bfo, ln=CFG_SITE_LANG, name = "", description="", code="", content_type="", names_trans=[], visibility="0"): """ Update the name, description and code of given output format @param req: the request object @param ln: language @param description: the new description @param name: the new name @param code: the new short code (== new bfo) of the output format @param content_type: the new content_type of the output format @param bfo: the filename of the output format to update @param names_trans: the translations in the same order as the languages from get_languages() @param visibility: the visibility of the output format in the output formats list (public pages) @return: a web page (or redirection to a web page) """ ln = wash_language(ln) _ = gettext_set_language(ln) try: uid = getUid(req) except: return error_page('Error', req) (auth_code, auth_msg) = check_user(req, 'cfgbibformat') if not auth_code: name = wash_url_argument(name, 'str') description = wash_url_argument(description, 'str') bfo = wash_url_argument(bfo, 'str') code = wash_url_argument(code, 'str') visibility = wash_url_argument(visibility, 'int') bfo = bibformatadminlib.update_output_format_attributes(bfo, name, description, code, content_type, names_trans, visibility) redirect_to_url(req, "output_format_show?ln=%(ln)s&bfo=%(bfo)s" % {'ln':ln, 'bfo':bfo, 'names_trans':names_trans}) else: return page_not_authorized(req=req, text=auth_msg)
def kb_delete(req, kb, ln=CFG_SITE_LANG, chosen_option=""): """ Deletes an existing kb @param kb the kb id to delete """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = ''' > <a class="navtrail" href="%s/kb?ln=%s">%s</a> > %s''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"), _("Delete Knowledge Base")) try: dummy = getUid(req) except: return error_page('Error', req) (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge') if not auth_code: kb_id = wash_url_argument(kb, 'int') kb_name = bibknowledge.get_kb_name(kb_id) if kb_name is None: return page(title=_("Unknown Knowledge Base"), body = "", language=ln, navtrail = navtrail_previous_links, errors = [("ERR_KB_ID_UNKNOWN", kb)], lastupdated=__lastupdated__, req=req) #Ask confirmation to user if not already done chosen_option = wash_url_argument(chosen_option, 'str') if chosen_option == "": return dialog_box(req=req, ln=ln, title="Delete %s" % kb_name, message="""Are you sure you want to delete knowledge base <i>%s</i>?""" % kb_name, navtrail=navtrail_previous_links, options=[_("Cancel"), _("Delete")]) elif chosen_option==_("Delete"): bibknowledge.delete_kb(kb_name) redirect_to_url(req, "kb?ln=%(ln)s" % {'ln':ln}) else: navtrail_previous_links = ''' > <a class="navtrail" href="%s/kb">%s</a>''' % (CFG_SITE_SECURE_URL, _("Manage Knowledge Bases")) return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
def delete(self, req, form): """ Suppress a message @param msgid: id of message @param ln: language @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/delete" % \ (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%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_msg(uid, argd['msgid'], 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)
def loanshistoricaloverview(self, req, form): """ Show loans historical overview. """ argd = wash_urlargd(form, {}) # Check if user is logged uid = getUid(req) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourloans/loanshistoricaloverview" % \ (CFG_SITE_URL,), navmenuid="yourloans") elif uid == -1 or isGuestUser(uid): return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( { 'referer': "%s/yourloans/loanshistoricaloverview%s" % (CFG_SITE_URL, make_canonical_urlargd(argd, {})), "ln": argd['ln'] }, {})), norobot=True) _ = gettext_set_language(argd['ln']) user_info = collect_user_info(req) if not user_info['precached_useloans']: return page_not_authorized(req, "../", \ text = _("You are not authorized to use loans.")) body = perform_loanshistoricaloverview(uid=uid, ln=argd['ln']) return page(title=_("Loans - historical overview"), body=body, uid=uid, lastupdated=__lastupdated__, req=req, language=argd['ln'], navmenuid="yourloans", secure_page_p=1)
def display(self, req, form): """ Displays the Inbox of a given user @param ln: language @return: the page for inbox """ argd = wash_urlargd(form, {}) # Check if user is logged uid = getUid(req) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourmessages/display" % \ (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%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.")) body = perform_request_display(uid=uid, ln=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)
def reference_add(req, record_id, references, url, email, comments): """ Form handler for requests coming from HRA format Used when the record has no references """ record_id = wash_url_argument(record_id, "int") references = wash_url_argument(references, "str") url = wash_url_argument(url, "str") email = wash_url_argument(email, "str") comments = wash_url_argument(comments, "str") submit_reference_add_ticket(record_id, references, url, email, comments) return redirect_to_url( req, "%s/reference_update.py/reference_add_success?record_id=%s" % (CFG_SITE_URL, record_id))
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 argd.has_key('as'): argd['aas'] = argd['as'] del argd['as'] if argd.get('aas', CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE) not in (0, 1): 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 not form.has_key('c'): 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 argd.has_key('aas'): argd['as'] = argd['aas'] del argd['aas'] target += make_canonical_urlargd(argd, legacy_collection_default_urlargd) return redirect_to_url(req, target)
def toggle(self, req, form): """ Store the visibility of a comment for current user """ argd = wash_urlargd(form, { 'comid': (int, -1), 'referer': (str, None), 'collapse': (int, 1) }) uid = getUid(req) if isGuestUser(uid): # We do not store information for guests return '' toggle_comment_visibility(uid, argd['comid'], argd['collapse'], self.recid) if argd['referer']: return redirect_to_url(req, CFG_SITE_SECURE_URL + \ (not argd['referer'].startswith('/') and '/' or '') + \ argd['referer'] + '#' + str(argd['comid']))
def check_authorization_moderatelinkbacks(self, req, argd): """ Check if user has authorization moderate linkbacks @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized """ # Check authorization uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(req, 'moderatelinkbacks', collection = guess_primary_collection_of_a_record(self.recid)) if auth_code and user_info['email'] == 'guest': # Ask to login target = CFG_SITE_SECURE_URL + '/youraccount/login' + \ make_canonical_urlargd({'ln': argd['ln'], 'referer': CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target) elif auth_code: return page_not_authorized(req, referer="../", uid=uid, text=auth_msg, ln=argd['ln'])
def __call__(self, req, form): """Redirect calls without final slash.""" redirect_to_url(req, '%s/admin2/bibsched/' % CFG_SITE_SECURE_URL)
def display(self, req, form): """ Display the linkbacks of a record and admin approve/reject features """ argd = wash_urlargd(form, {}) _ = gettext_set_language(argd['ln']) # Check authorization uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_linkbacks(user_info, self.recid) if auth_code and user_info['email'] == 'guest': # Ask to login target = '/youraccount/login' + \ make_canonical_urlargd({'ln': argd['ln'], 'referer': CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target) elif auth_code: return page_not_authorized(req, referer="../", uid=uid, text=auth_msg, ln=argd['ln']) show_admin = False (auth_code, auth_msg) = acc_authorize_action( req, 'moderatelinkbacks', collection=guess_primary_collection_of_a_record(self.recid)) if not auth_code: show_admin = True body = perform_request_display_record_linbacks( req, self.recid, show_admin, weblinkback_templates=weblinkback_templates, ln=argd['ln']) title = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln'])[0] # navigation, tabs, top and bottom part navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln']) if navtrail: navtrail += ' > ' 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 += ' > <a class="navtrail">Linkbacks</a>' mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader( ) unordered_tabs = get_detailed_page_tabs(get_colID( guess_primary_collection_of_a_record(self.recid)), self.recid, ln=argd['ln']) ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()] ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1])) link_ln = '' if argd['ln'] != CFG_SITE_LANG: link_ln = '?ln=%s' % argd['ln'] tabs = [(unordered_tabs[tab_id]['label'], \ '%s/%s/%s/%s%s' % (CFG_SITE_URL, CFG_SITE_RECORD, self.recid, tab_id, link_ln), \ tab_id in ['linkbacks'], unordered_tabs[tab_id]['enabled']) \ for (tab_id, values) in ordered_tabs_id if unordered_tabs[tab_id]['visible'] == True] top = webstyle_templates.detailed_record_container_top( self.recid, tabs, argd['ln']) bottom = webstyle_templates.detailed_record_container_bottom( self.recid, tabs, argd['ln']) return pageheaderonly(title=title, navtrail=navtrail, uid=uid, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(argd['ln']) + \ top + body + bottom + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(language=argd['ln'], req=req)
def display(self, req, form): """ Display comments (reviews if enabled) associated with record having id recid where recid>0. This function can also be used to display remarks associated with basket having id recid where recid<-99. @param ln: language @param recid: record id, integer @param do: display order hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param ds: display since all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param nb: number of results per page @param p: results page @param voted: boolean, active if user voted for a review, see vote function @param reported: int, active if user reported a certain comment/review, see report function @param reviews: boolean, enabled for reviews, disabled for comments @param subscribed: int, 1 if user just subscribed to discussion, -1 if unsubscribed @return the full html page. """ argd = wash_urlargd( form, { 'do': (str, "od"), 'ds': (str, "all"), 'nb': (int, 100), 'p': (int, 1), 'voted': (int, -1), 'reported': (int, -1), 'subscribed': (int, 0), 'cmtgrp': (list, ["latest"] ) # 'latest' is now a reserved group/round name }) _ = gettext_set_language(argd['ln']) uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) can_send_comments = False (auth_code, auth_msg) = check_user_can_send_comments(user_info, self.recid) if not auth_code: can_send_comments = True can_attach_files = False (auth_code, auth_msg) = check_user_can_attach_file_to_comments( user_info, self.recid) if not auth_code and (user_info['email'] != 'guest'): can_attach_files = True subscription = get_user_subscription_to_discussion(self.recid, uid) if subscription == 1: user_is_subscribed_to_discussion = True user_can_unsubscribe_from_discussion = True elif subscription == 2: user_is_subscribed_to_discussion = True user_can_unsubscribe_from_discussion = False else: user_is_subscribed_to_discussion = False user_can_unsubscribe_from_discussion = False unordered_tabs = get_detailed_page_tabs(get_colID( guess_primary_collection_of_a_record(self.recid)), self.recid, ln=argd['ln']) ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()] ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1])) link_ln = '' if argd['ln'] != CFG_SITE_LANG: link_ln = '?ln=%s' % argd['ln'] tabs = [(unordered_tabs[tab_id]['label'], \ '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \ tab_id in ['comments', 'reviews'], unordered_tabs[tab_id]['enabled']) \ for (tab_id, order) in ordered_tabs_id if unordered_tabs[tab_id]['visible'] == True] tabs_counts = get_detailed_page_tabs_counts(self.recid) citedbynum = tabs_counts['Citations'] references = tabs_counts['References'] discussions = tabs_counts['Discussions'] top = webstyle_templates.detailed_record_container_top( self.recid, tabs, argd['ln'], citationnum=citedbynum, referencenum=references, discussionnum=discussions) bottom = webstyle_templates.detailed_record_container_bottom( self.recid, tabs, argd['ln']) #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"] display_comment_rounds = argd['cmtgrp'] check_warnings = [] (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln']) if ok: body = perform_request_display_comments_or_remarks( req=req, recID=self.recid, display_order=argd['do'], display_since=argd['ds'], nb_per_page=argd['nb'], page=argd['p'], ln=argd['ln'], voted=argd['voted'], reported=argd['reported'], subscribed=argd['subscribed'], reviews=self.discussion, uid=uid, can_send_comments=can_send_comments, can_attach_files=can_attach_files, user_is_subscribed_to_discussion= user_is_subscribed_to_discussion, user_can_unsubscribe_from_discussion= user_can_unsubscribe_from_discussion, display_comment_rounds=display_comment_rounds) title, description, keywords = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln']) navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln']) if navtrail: navtrail += ' > ' 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 += ' > <a class="navtrail">%s</a>' % ( self.discussion == 1 and _("Reviews") or _("Comments")) mathjaxheader = '' if CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS: mathjaxheader = get_mathjax_header(req.is_https()) jqueryheader = ''' <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script> ''' % { 'CFG_SITE_URL': CFG_SITE_URL } return pageheaderonly(title=title, navtrail=navtrail, uid=uid, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(argd['ln']) + \ top + body + bottom + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req) else: return page(title=_("Record Not Found"), body=problem, uid=uid, verbose=1, req=req, language=argd['ln'], navmenuid='search')
def index(self, req, form): ''' Serve the main person page. Will use the object's person id to get a person's information. @param req: apache request object @type req: apache request object @param form: POST/GET variables of the request @type form: dict @return: a full page formatted in HTML @return: str ''' webapi.session_bareinit(req) session = webapi.get_session(req) pinfo = session['personinfo'] ulevel = pinfo['ulevel'] argd = wash_urlargd( form, { 'ln': (str, CFG_SITE_LANG), 'recompute': (int, 0), 'verbose': (int, 0), 'trial': (str, None) }) ln = argd['ln'] debug = "verbose" in argd and argd["verbose"] > 0 # Create Page Markup and Menu try: int(self.person_id) except ValueError: cname = self.person_id else: cname = webapi.get_canonical_id_from_person_id(self.person_id) menu = WebProfileMenu(str(cname), "profile", ln, self._is_profile_owner(pinfo['pid']), self._is_admin(pinfo)) profile_page = WebProfilePage( "profile", webapi.get_longest_name_from_pid(self.person_id)) profile_page.add_profile_menu(menu) if 'form_email' in pinfo: gFormEmail = pinfo['form_email'] else: gFormEmail = "" profile_page.add_bootstrapped_data( json.dumps({ "backbone": """ (function(ticketbox) { var app = ticketbox.app; app.userops.set(%s); app.bodyModel.set({userLevel: "%s"}); })(ticketbox);""" % (WebInterfaceAuthorTicketHandling.bootstrap_status( pinfo, "user"), ulevel), "other": "var gUserLevel = '%s'; var gFormEmail = '%s';" % (ulevel, gFormEmail) })) if debug: profile_page.add_debug_info(pinfo) last_computed = str(self.last_computed()) context = { 'person_id': self.person_id, 'last_computed': last_computed, 'citation_fine_print_link': "%s/help/citation-metrics" % CFG_BASE_URL, 'search_form_url': "%s/author/search" % CFG_BASE_URL, 'possible_to_recompute': self._possible_to_recompute(pinfo) } verbose = argd['verbose'] url_args = dict() if ln != CFG_SITE_LANG: url_args['ln'] = ln if verbose: url_args['verbose'] = str(verbose) encoded = urlencode(url_args) if encoded: encoded = '&' + encoded if CFG_BIBAUTHORID_ENABLED: if self.person_id < 0: return redirect_to_url( req, '%s/author/search?q=%s%s' % (CFG_SITE_URL, self.original_search_parameter, encoded)) else: self.person_id = self.original_search_parameter profile_page.menu = None assert not form.has_key( 'jsondata'), "Content type should be only text/html." full_name = webapi.get_longest_name_from_pid(self.person_id) page_title = '%s - Profile' % full_name if argd['recompute'] and req.get_method() == 'POST': expire_all_cache_for_person(self.person_id) context['last_computed'] = str( datetime.now().replace(microsecond=0)) history_log_visit(req, 'profile', pid=self.person_id) meta = profile_page.get_head() context["visible"] = AID_VISIBILITY context["element_width"] = self.render_width_dict body = profile_page.get_wrapped_body("profile_page", context) return page(title=page_title, metaheaderadd=meta.encode('utf-8'), body=body.encode('utf-8'), req=req, language=ln, show_title_p=False)
def redirecter(req, form): real_url = "http://" + '/'.join(path) redirect_to_url(req, real_url)
def __call__(self, req, form): argd = wash_search_urlargd(form) argd['recid'] = self.recid argd['tab'] = self.tab if self.format is not None: argd['of'] = self.format req.argd = argd uid = getUid(req) if uid == -1: return page_not_authorized(req, "../", text="You are not authorized to view this record.", navmenuid='search') elif uid > 0: pref = get_user_preferences(uid) try: if not form.has_key('rg'): # fetch user rg preference only if not overridden via URL argd['rg'] = int(pref['websearch_group_records']) except (KeyError, ValueError): pass user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid) if argd['rg'] > CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS and acc_authorize_action(req, 'runbibedit')[0] != 0: argd['rg'] = CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS #check if the user has rights to set a high wildcard limit #if not, reduce the limit set by user, with the default one if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0): if acc_authorize_action(req, 'runbibedit')[0] != 0: argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT # only superadmins can use verbose parameter for obtaining debug information if not isUserSuperAdmin(user_info): argd['verbose'] = 0 if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)}) target = CFG_SITE_SECURE_URL + '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text=auth_msg, \ navmenuid='search') from invenio.search_engine import record_exists, get_merged_recid # check if the current record has been deleted # and has been merged, case in which the deleted record # will be redirect to the new one record_status = record_exists(argd['recid']) merged_recid = get_merged_recid(argd['recid']) if record_status == -1 and merged_recid: url = CFG_SITE_URL + '/' + CFG_SITE_RECORD + '/%s?ln=%s' url %= (str(merged_recid), argd['ln']) redirect_to_url(req, url) # mod_python does not like to return [] in case when of=id: out = perform_request_search(req, **argd) if out == []: return str(out) else: return out
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=_("%s Personalize, Display searches") % CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME), keywords=_("%s, personalize") % 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)
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: a (body, errors, warnings) formed tuple. @rtype: tuple """ 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_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, errors, warnings, 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, errors, warnings) = 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'], errors=errors, warnings=warnings, navmenuid="yourmessages", secure_page_p=1)
class WebInterfaceCommentsPages(WebInterfaceDirectory): """Defines the set of /comments pages.""" _exports = [ '', 'display', 'add', 'vote', 'report', 'index', 'attachments', 'subscribe', 'unsubscribe' ] def __init__(self, recid=-1, reviews=0): self.recid = recid self.discussion = reviews # 0:comments, 1:reviews self.attachments = WebInterfaceCommentsFiles(recid, reviews) def index(self, req, form): """ Redirects to display function """ return self.display(req, form) def display(self, req, form): """ Display comments (reviews if enabled) associated with record having id recid where recid>0. This function can also be used to display remarks associated with basket having id recid where recid<-99. @param ln: language @param recid: record id, integer @param do: display order hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param ds: display since all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param nb: number of results per page @param p: results page @param voted: boolean, active if user voted for a review, see vote function @param reported: int, active if user reported a certain comment/review, see report function @param reviews: boolean, enabled for reviews, disabled for comments @param subscribed: int, 1 if user just subscribed to discussion, -1 if unsubscribed @return the full html page. """ argd = wash_urlargd( form, { 'do': (str, "od"), 'ds': (str, "all"), 'nb': (int, 100), 'p': (int, 1), 'voted': (int, -1), 'reported': (int, -1), 'subscribed': (int, 0), 'cmtgrp': (list, ["latest"] ) # 'latest' is now a reserved group/round name }) _ = gettext_set_language(argd['ln']) uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) can_send_comments = False (auth_code, auth_msg) = check_user_can_send_comments(user_info, self.recid) if not auth_code: can_send_comments = True can_attach_files = False (auth_code, auth_msg) = check_user_can_attach_file_to_comments( user_info, self.recid) if not auth_code and (user_info['email'] != 'guest'): can_attach_files = True subscription = get_user_subscription_to_discussion(self.recid, uid) if subscription == 1: user_is_subscribed_to_discussion = True user_can_unsubscribe_from_discussion = True elif subscription == 2: user_is_subscribed_to_discussion = True user_can_unsubscribe_from_discussion = False else: user_is_subscribed_to_discussion = False user_can_unsubscribe_from_discussion = False unordered_tabs = get_detailed_page_tabs(get_colID( guess_primary_collection_of_a_record(self.recid)), self.recid, ln=argd['ln']) ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()] ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1])) link_ln = '' if argd['ln'] != CFG_SITE_LANG: link_ln = '?ln=%s' % argd['ln'] tabs = [(unordered_tabs[tab_id]['label'], \ '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \ tab_id in ['comments', 'reviews'], unordered_tabs[tab_id]['enabled']) \ for (tab_id, order) in ordered_tabs_id if unordered_tabs[tab_id]['visible'] == True] tabs_counts = get_detailed_page_tabs_counts(self.recid) citedbynum = tabs_counts['Citations'] references = tabs_counts['References'] discussions = tabs_counts['Discussions'] top = webstyle_templates.detailed_record_container_top( self.recid, tabs, argd['ln'], citationnum=citedbynum, referencenum=references, discussionnum=discussions) bottom = webstyle_templates.detailed_record_container_bottom( self.recid, tabs, argd['ln']) #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"] display_comment_rounds = argd['cmtgrp'] check_warnings = [] (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln']) if ok: body = perform_request_display_comments_or_remarks( req=req, recID=self.recid, display_order=argd['do'], display_since=argd['ds'], nb_per_page=argd['nb'], page=argd['p'], ln=argd['ln'], voted=argd['voted'], reported=argd['reported'], subscribed=argd['subscribed'], reviews=self.discussion, uid=uid, can_send_comments=can_send_comments, can_attach_files=can_attach_files, user_is_subscribed_to_discussion= user_is_subscribed_to_discussion, user_can_unsubscribe_from_discussion= user_can_unsubscribe_from_discussion, display_comment_rounds=display_comment_rounds) title, description, keywords = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln']) navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln']) if navtrail: navtrail += ' > ' 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 += ' > <a class="navtrail">%s</a>' % ( self.discussion == 1 and _("Reviews") or _("Comments")) mathjaxheader = '' if CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS: mathjaxheader = get_mathjax_header(req.is_https()) jqueryheader = ''' <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script> ''' % { 'CFG_SITE_URL': CFG_SITE_URL } return pageheaderonly(title=title, navtrail=navtrail, uid=uid, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(argd['ln']) + \ top + body + bottom + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req) else: return page(title=_("Record Not Found"), body=problem, uid=uid, verbose=1, req=req, language=argd['ln'], navmenuid='search') # Return the same page wether we ask for /CFG_SITE_RECORD/123 or /CFG_SITE_RECORD/123/ __call__ = index def add(self, req, form): """ Add a comment (review) to record with id recid where recid>0 Also works for adding a remark to basket with id recid where recid<-99 @param ln: languange @param recid: record id @param action: 'DISPLAY' to display add form 'SUBMIT' to submit comment once form is filled 'REPLY' to reply to an already existing comment @param msg: the body of the comment/review or remark @param score: star score of the review @param note: title of the review @param comid: comment id, needed for replying @param editor_type: the type of editor used for submitting the comment: 'textarea', 'ckeditor'. @param subscribe: if set, subscribe user to receive email notifications when new comment are added to this discussion @return the full html page. """ argd = wash_urlargd( form, { 'action': (str, "DISPLAY"), 'msg': (str, ""), 'note': (str, ''), 'score': (int, 0), 'comid': (int, 0), 'editor_type': (str, ""), 'subscribe': (str, ""), 'cookie': (str, "") }) _ = gettext_set_language(argd['ln']) actions = ['DISPLAY', 'REPLY', 'SUBMIT'] uid = getUid(req) # Is site ready to accept comments? if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS and not CFG_WEBCOMMENT_ALLOW_REVIEWS): return page_not_authorized(req, "../comments/add", navmenuid='search') # Is user allowed to post comment? user_info = collect_user_info(req) (auth_code_1, auth_msg_1) = check_user_can_view_comments(user_info, self.recid) (auth_code_2, auth_msg_2) = check_user_can_send_comments(user_info, self.recid) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) # Save user's value in cookie, so that these "POST" # parameters are not lost during login process msg_cookie = mail_cookie_create_common( 'comment_msg', { 'msg': argd['msg'], 'note': argd['note'], 'score': argd['score'], 'editor_type': argd['editor_type'], 'subscribe': argd['subscribe'] }, onetime=True) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {}) return redirect_to_url(req, target, norobot=True) elif (auth_code_1 or auth_code_2): return page_not_authorized(req, "../", \ text = auth_msg_1 + auth_msg_2) user_info = collect_user_info(req) can_attach_files = False (auth_code, auth_msg) = check_user_can_attach_file_to_comments( user_info, self.recid) if not auth_code and (user_info['email'] != 'guest'): can_attach_files = True warning_msgs = [ ] # list of warning tuples (warning_text, warning_color) added_files = {} if can_attach_files: # User is allowed to attach files. Process the files file_too_big = False formfields = form.get('commentattachment[]', []) if not hasattr(formfields, "__getitem__"): # A single file was uploaded formfields = [formfields] for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]: if hasattr(formfield, "filename") and formfield.filename: filename = formfield.filename dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment', str(uid)) try: assert (dir_to_open.startswith(CFG_TMPDIR)) except AssertionError: register_exception(req=req, prefix='User #%s tried to upload file to forbidden location: %s' \ % (uid, dir_to_open)) if not os.path.exists(dir_to_open): try: os.makedirs(dir_to_open) except: register_exception(req=req, alert_admin=True) ## Before saving the file to disc, wash the filename (in particular ## washing away UNIX and Windows (e.g. DFS) paths): filename = os.path.basename(filename.split('\\')[-1]) filename = filename.strip() if filename != "": # Check that file does not already exist n = 1 while os.path.exists( os.path.join(dir_to_open, filename)): basedir, name, extension = decompose_file(filename) new_name = propose_next_docname(name) filename = new_name + extension fp = open(os.path.join(dir_to_open, filename), "w") # FIXME: temporary, waiting for wsgi handler to be # fixed. Once done, read chunk by chunk ## while formfield.file: ## fp.write(formfield.file.read(10240)) fp.write(formfield.file.read()) fp.close() # Isn't this file too big? file_size = os.path.getsize( os.path.join(dir_to_open, filename)) if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \ file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE: os.remove(os.path.join(dir_to_open, filename)) # One file is too big: record that, # dismiss all uploaded files and re-ask to # upload again file_too_big = True try: raise InvenioWebCommentWarning( _('The size of file \\"%s\\" (%s) is larger than maximum allowed file size (%s). Select files again.' ) % (cgi.escape(filename), str(file_size / 1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE / 1024) + 'KB')) except InvenioWebCommentWarning, exc: register_exception(stream='warning') warning_msgs.append((exc.message, '')) #warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB')) else: added_files[filename] = os.path.join( dir_to_open, filename) if file_too_big: # One file was too big. Removed all uploaded filed for filepath in added_files.items(): try: os.remove(filepath) except: # File was already removed or does not exist? pass client_ip_address = req.remote_ip check_warnings = [] (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln']) if ok: title, description, keywords = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln']) navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid)) if navtrail: navtrail += ' > ' 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 += '> <a class="navtrail" href="%s/%s/%s/%s/?ln=%s">%s</a>' % ( CFG_SITE_URL, CFG_SITE_RECORD, self.recid, self.discussion == 1 and 'reviews' or 'comments', argd['ln'], self.discussion == 1 and _('Reviews') or _('Comments')) if argd['action'] not in actions: argd['action'] = 'DISPLAY' if not argd['msg']: # User had to login in-between, so retrieve msg # from cookie try: (kind, cookie_argd) = mail_cookie_check_common(argd['cookie'], delete=True) argd.update(cookie_argd) except InvenioWebAccessMailCookieDeletedError, e: return redirect_to_url(req, CFG_SITE_SECURE_URL + '/'+ CFG_SITE_RECORD +'/' + \ str(self.recid) + (self.discussion==1 and \ '/reviews' or '/comments')) except InvenioWebAccessMailCookieError, e: # Invalid or empty cookie: continue pass
def index(self, req, dummy): """Index page.""" redirect_to_url(req, '%s/youralerts/list' % CFG_SITE_SECURE_URL)
def _get(self, req, form): """ Returns a file attached to a comment. Example: CFG_SITE_URL/CFG_SITE_RECORD/5953/comments/attachments/get/652/myfile.pdf where 652 is the comment ID """ argd = wash_urlargd(form, {'file': (str, None), 'comid': (int, 0)}) _ = gettext_set_language(argd['ln']) # Can user view this record, i.e. can user access its # attachments? uid = getUid(req) user_info = collect_user_info(req) # Check that user can view record, and its comments (protected # with action "viewcomment") (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) # Does comment exist? if not query_get_comment(argd['comid']): req.status = apache.HTTP_NOT_FOUND return page(title=_("Page Not Found"), body=_('The requested comment could not be found'), req=req) # Check that user can view this particular comment, protected # using its own restriction (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid']) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg, ln=argd['ln']) if not argd['file'] is None: # Prepare path to file on disk. Normalize the path so that # ../ and other dangerous components are removed. path = os.path.abspath(CFG_PREFIX + '/var/data/comments/' + \ str(self.recid) + '/' + str(argd['comid']) + \ '/' + argd['file']) # Check that we are really accessing attachements # directory, for the declared record. if path.startswith(CFG_PREFIX + '/var/data/comments/' + \ str(self.recid)) and \ os.path.exists(path): return stream_file(req, path) # Send error 404 in all other cases req.status = apache.HTTP_NOT_FOUND return page(title=_("Page Not Found"), body=_('The requested file could not be found'), req=req, language=argd['ln'])
def report(self, req, form): """ Report a comment/review for inappropriate content @param comid: comment/review id @param recid: the id of the record the comment/review is associated with @param ln: language @param do: display order hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param ds: display since all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param nb: number of results per page @param p: results page @param referer: http address of the calling function to redirect to (refresh) @param reviews: boolean, enabled for reviews, disabled for comments """ argd = wash_urlargd( form, { 'comid': (int, -1), 'recid': (int, -1), 'do': (str, "od"), 'ds': (str, "all"), 'nb': (int, 100), 'p': (int, 1), 'referer': (str, None) }) client_ip_address = req.remote_ip uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if auth_code or user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) success = perform_request_report(argd['comid'], client_ip_address, uid) if argd['referer']: argd[ 'referer'] += "?ln=%s&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)
def add(self, req, form): """ Add a comment (review) to record with id recid where recid>0 Also works for adding a remark to basket with id recid where recid<-99 @param ln: languange @param recid: record id @param action: 'DISPLAY' to display add form 'SUBMIT' to submit comment once form is filled 'REPLY' to reply to an already existing comment @param msg: the body of the comment/review or remark @param score: star score of the review @param note: title of the review @param comid: comment id, needed for replying @param editor_type: the type of editor used for submitting the comment: 'textarea', 'ckeditor'. @param subscribe: if set, subscribe user to receive email notifications when new comment are added to this discussion @return the full html page. """ argd = wash_urlargd( form, { 'action': (str, "DISPLAY"), 'msg': (str, ""), 'note': (str, ''), 'score': (int, 0), 'comid': (int, 0), 'editor_type': (str, ""), 'subscribe': (str, ""), 'cookie': (str, "") }) _ = gettext_set_language(argd['ln']) actions = ['DISPLAY', 'REPLY', 'SUBMIT'] uid = getUid(req) # Is site ready to accept comments? if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS and not CFG_WEBCOMMENT_ALLOW_REVIEWS): return page_not_authorized(req, "../comments/add", navmenuid='search') # Is user allowed to post comment? user_info = collect_user_info(req) (auth_code_1, auth_msg_1) = check_user_can_view_comments(user_info, self.recid) (auth_code_2, auth_msg_2) = check_user_can_send_comments(user_info, self.recid) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) # Save user's value in cookie, so that these "POST" # parameters are not lost during login process msg_cookie = mail_cookie_create_common( 'comment_msg', { 'msg': argd['msg'], 'note': argd['note'], 'score': argd['score'], 'editor_type': argd['editor_type'], 'subscribe': argd['subscribe'] }, onetime=True) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_SECURE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {}) return redirect_to_url(req, target, norobot=True) elif (auth_code_1 or auth_code_2): return page_not_authorized(req, "../", \ text = auth_msg_1 + auth_msg_2) user_info = collect_user_info(req) can_attach_files = False (auth_code, auth_msg) = check_user_can_attach_file_to_comments( user_info, self.recid) if not auth_code and (user_info['email'] != 'guest'): can_attach_files = True warning_msgs = [ ] # list of warning tuples (warning_text, warning_color) added_files = {} if can_attach_files: # User is allowed to attach files. Process the files file_too_big = False formfields = form.get('commentattachment[]', []) if not hasattr(formfields, "__getitem__"): # A single file was uploaded formfields = [formfields] for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]: if hasattr(formfield, "filename") and formfield.filename: filename = formfield.filename dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment', str(uid)) try: assert (dir_to_open.startswith(CFG_TMPDIR)) except AssertionError: register_exception(req=req, prefix='User #%s tried to upload file to forbidden location: %s' \ % (uid, dir_to_open)) if not os.path.exists(dir_to_open): try: os.makedirs(dir_to_open) except: register_exception(req=req, alert_admin=True) ## Before saving the file to disc, wash the filename (in particular ## washing away UNIX and Windows (e.g. DFS) paths): filename = os.path.basename(filename.split('\\')[-1]) filename = filename.strip() if filename != "": # Check that file does not already exist n = 1 while os.path.exists( os.path.join(dir_to_open, filename)): basedir, name, extension = decompose_file(filename) new_name = propose_next_docname(name) filename = new_name + extension fp = open(os.path.join(dir_to_open, filename), "w") # FIXME: temporary, waiting for wsgi handler to be # fixed. Once done, read chunk by chunk ## while formfield.file: ## fp.write(formfield.file.read(10240)) fp.write(formfield.file.read()) fp.close() # Isn't this file too big? file_size = os.path.getsize( os.path.join(dir_to_open, filename)) if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \ file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE: os.remove(os.path.join(dir_to_open, filename)) # One file is too big: record that, # dismiss all uploaded files and re-ask to # upload again file_too_big = True try: raise InvenioWebCommentWarning( _('The size of file \\"%s\\" (%s) is larger than maximum allowed file size (%s). Select files again.' ) % (cgi.escape(filename), str(file_size / 1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE / 1024) + 'KB')) except InvenioWebCommentWarning, exc: register_exception(stream='warning') warning_msgs.append((exc.message, '')) #warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB')) else: added_files[filename] = os.path.join( dir_to_open, filename) if file_too_big: # One file was too big. Removed all uploaded filed for filepath in added_files.items(): try: os.remove(filepath) except: # File was already removed or does not exist? pass
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, 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(022) f = open(fullfilename, "w") f.write(rss_prologue + rss_body + rss_epilogue) f.close() except IOError, v: if v[0] == 36: # URL was too long. Never mind, don't cache pass else: raise repr(v)
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, 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=_("%s Personalize, Set a new alert") % CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME), keywords=_("%s, personalize") % CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME), uid=uid, language=argd['ln'], req=req, lastupdated=__lastupdated__, navmenuid='youralerts')
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_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, errors, warnings) = 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'], errors=errors, warnings=warnings, navmenuid="yourmessages", secure_page_p=1)
def index(self, req, form): """Handle all BibMerge requests. The responsibilities of this functions are: * JSON decoding and encoding. * Redirection, if necessary. * Authorization. * Calling the appropriate function from the engine. """ # If it is an Ajax request, extract any JSON data. ajax_request, recid1, recid2 = False, None, None argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)}) if form.has_key('jsondata'): json_data = json.loads(str(form['jsondata'])) # Deunicode all strings (Invenio doesn't have unicode # support). json_data = json_unicode_to_utf8(json_data) ajax_request = True json_response = {} if json_data.has_key('recID1'): recid1 = json_data['recID1'] if json_data.has_key('recID2'): recid2 = json_data['recID2'] # Authorization. user_info = collect_user_info(req) if user_info['email'] == 'guest': # User is not logged in. if not ajax_request: # Do not display the introductory recID selection box to guest # users (as it used to be with v0.99.0): auth_code, auth_message = acc_authorize_action( req, 'runbibmerge') referer = '/merge/' return page_not_authorized(req=req, referer=referer, text=auth_message, navtrail=navtrail) else: # Session has most likely timed out. json_response.update({ 'resultCode': 1, 'resultText': 'Error: Not logged in' }) return json.dumps(json_response) elif self.recid: # Handle RESTful call by storing recid and redirecting to # generic URL. redirect_to_url(req, '%s/%s/merge/' % (CFG_SITE_URL, CFG_SITE_RECORD)) if recid1 is not None: # Authorize access to record 1. auth_code, auth_message = acc_authorize_action( req, 'runbibmerge', collection=guess_primary_collection_of_a_record(recid1)) if auth_code != 0: json_response.update({ 'resultCode': 1, 'resultText': 'No access to record %s' % recid1 }) return json.dumps(json_response) if recid2 is not None: # Authorize access to record 2. auth_code, auth_message = acc_authorize_action( req, 'runbibmerge', collection=guess_primary_collection_of_a_record(recid2)) if auth_code != 0: json_response.update({ 'resultCode': 1, 'resultText': 'No access to record %s' % recid2 }) return json.dumps(json_response) # Handle request. uid = getUid(req) if not ajax_request: # Show BibEdit start page. body, errors, warnings = perform_request_init() metaheaderadd = """<script type="text/javascript" src="%(site)s/js/jquery.min.js"></script> <script type="text/javascript" src="%(site)s/js/json2.js"></script> <script type="text/javascript" src="%(site)s/js/bibmerge_engine.js"></script>""" % { 'site': CFG_SITE_URL } title = 'Record Merger' return page(title=title, metaheaderadd=metaheaderadd, body=body, errors=errors, warnings=warnings, uid=uid, language=argd['ln'], navtrail=navtrail, lastupdated=__lastupdated__, req=req) else: # Handle AJAX request. json_response = perform_request_ajax(req, uid, json_data) return json.dumps(json_response)
def index(self, req, form): """ The function called by default """ redirect_to_url( req, "%s/yourmessages/display?%s" % (CFG_SITE_URL, req.args))
def __call__(self, req, form): """Redirect calls without final slash.""" redirect_to_url(req, '%s/%s/merge/' % (CFG_SITE_URL, CFG_SITE_RECORD))
def __call__(self, req, form): """ Perform a search. """ argd = wash_search_urlargd(form) _ = gettext_set_language(argd['ln']) if req.method == 'POST': raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED uid = getUid(req) user_info = collect_user_info(req) if uid == -1: return page_not_authorized(req, "../", text=_("You are not authorized to view this area."), navmenuid='search') elif uid > 0: pref = get_user_preferences(uid) try: if not form.has_key('rg'): # fetch user rg preference only if not overridden via URL argd['rg'] = int(pref['websearch_group_records']) except (KeyError, ValueError): pass if argd['rg'] > CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS and acc_authorize_action(req, 'runbibedit')[0] != 0: argd['rg'] = CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS involved_collections = set() involved_collections.update(argd['c']) involved_collections.add(argd['cc']) if argd['id'] > 0: argd['recid'] = argd['id'] if argd['idb'] > 0: argd['recidb'] = argd['idb'] if argd['sysno']: tmp_recid = find_record_from_sysno(argd['sysno']) if tmp_recid: argd['recid'] = tmp_recid if argd['sysnb']: tmp_recid = find_record_from_sysno(argd['sysnb']) if tmp_recid: argd['recidb'] = tmp_recid if argd['recid'] > 0: if argd['recidb'] > argd['recid']: # Hack to check if among the restricted collections # at least a record of the range is there and # then if the user is not authorized for that # collection. recids = intbitset(xrange(argd['recid'], argd['recidb'])) restricted_collection_cache.recreate_cache_if_needed() for collname in restricted_collection_cache.cache: (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=collname) if auth_code and user_info['email'] == 'guest': coll_recids = get_collection(collname).reclist if coll_recids & recids: cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : collname}) target = CFG_SITE_SECURE_URL + '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text=auth_msg, \ navmenuid='search') else: involved_collections.add(guess_primary_collection_of_a_record(argd['recid'])) # If any of the collection requires authentication, redirect # to the authentication form. for coll in involved_collections: if collection_restricted_p(coll): (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=coll) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : coll}) target = CFG_SITE_SECURE_URL + '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text=auth_msg, \ navmenuid='search') #check if the user has rights to set a high wildcard limit #if not, reduce the limit set by user, with the default one if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0): auth_code, auth_message = acc_authorize_action(req, 'runbibedit') if auth_code != 0: argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT # only superadmins can use verbose parameter for obtaining debug information if not isUserSuperAdmin(user_info): argd['verbose'] = 0 # Keep all the arguments, they might be reused in the # search_engine itself to derivate other queries req.argd = argd # mod_python does not like to return [] in case when of=id: out = perform_request_search(req, **argd) if out == []: return str(out) else: return out
def _traverse(self, req, path, do_head=False, guest_p=True): """ Locate the handler of an URI by traversing the elements of the path.""" _debug(req, 'traversing %r' % path) component, path = path[0], path[1:] name = self._translate(component) if name is None: obj, path = self._lookup(component, path) else: obj = getattr(self, name) if obj is None: _debug(req, 'could not resolve %s' % repr((component, path))) raise TraversalError() # We have found the next segment. If we know that from this # point our subpages are over HTTPS, do the switch. if (CFG_FULL_HTTPS or CFG_HAS_HTTPS_SUPPORT and (self._force_https or session.need_https())) and not req.is_https(): # We need to isolate the part of the URI that is after # CFG_SITE_URL, and append that to our CFG_SITE_SECURE_URL. original_parts = urlparse.urlparse(req.unparsed_uri) plain_prefix_parts = urlparse.urlparse(CFG_SITE_URL) secure_prefix_parts = urlparse.urlparse(CFG_SITE_SECURE_URL) # Compute the new path plain_path = original_parts[2] plain_path = secure_prefix_parts[2] + \ plain_path[len(plain_prefix_parts[2]):] # ...and recompose the complete URL final_parts = list(secure_prefix_parts) final_parts[2] = plain_path final_parts[-3:] = original_parts[-3:] target = urlparse.urlunparse(final_parts) ## The following condition used to allow certain URLs to ## by-pass the forced SSL redirect. Since SSL certificates ## are deployed on INSPIRE, this is no longer needed ## Will be left here for reference. #from invenio.config import CFG_INSPIRE_SITE #if not CFG_INSPIRE_SITE or plain_path.startswith('/youraccount/login'): redirect_to_url(req, target) # Continue the traversal. If there is a path, continue # resolving, otherwise call the method as it is our final # renderer. We even pass it the parsed form arguments. if path: if hasattr(obj, '_traverse'): return obj._traverse(req, path, do_head, guest_p) else: raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND if do_head: req.content_type = "text/html; charset=UTF-8" raise apache.SERVER_RETURN, apache.DONE form = req.form #if 'ln' not in form and \ # req.uri not in CFG_NO_LANG_RECOGNITION_URIS: # ln = get_preferred_user_language(req) # form.add_field('ln', ln) result = _check_result(req, obj(req, form)) return result
def __call__(self, req, form): ''' Serves the main person page. Will use the object's person id to get a person's information. @param req: apache request object @type req: apache request object @param form: POST/GET variables of the request @type form: dict @return: a full page formatted in HTML @rtype: str ''' if not CFG_BIBAUTHORID_ENABLED: self.person_id = self.original_search_parameter return self.index(req, form) argd = wash_urlargd(form, { 'ln': (str, CFG_SITE_LANG), 'recid': (int, -1), 'verbose': (int, 0) }) ln = argd['ln'] verbose = argd['verbose'] url_args = dict() if ln != CFG_SITE_LANG: url_args['ln'] = ln if verbose: url_args['verbose'] = str(verbose) encoded = urlencode(url_args) if encoded: encoded = '?' + encoded if self.cid is not None and self.original_search_parameter != self.cid: return redirect_to_url( req, '%s/author/profile/%s%s' % (CFG_SITE_URL, self.cid, encoded)) # author may have only author identifier and not a canonical id if self.person_id > -1: return self.index(req, form) recid = argd['recid'] if recid > -1: possible_authors = get_authors_by_name( self.original_search_parameter, limit_to_recid=recid) if len(possible_authors) == 1: self.person_id = possible_authors.pop() self.cid = get_person_redirect_link(self.person_id) redirect_to_url( req, '%s/author/profile/%s%s' % (CFG_SITE_URL, self.cid, encoded)) encoded = urlencode(url_args) if encoded: encoded = '&' + encoded return redirect_to_url( req, '%s/author/search?q=%s%s' % (CFG_SITE_URL, self.original_search_parameter, encoded))
def index(self, req, form): """Handle all BibEdit requests. The responsibilities of this functions is: * JSON decoding and encoding. * Redirection, if necessary. * Authorization. * Calling the appropriate function from the engine. """ uid = getUid(req) argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)}) # Abort if the simplejson module isn't available if not simplejson_available: title = 'Record Editor' body = '''Sorry, the record editor cannot operate when the `simplejson' module is not installed. Please see the INSTALL file.''' return page(title = title, body = body, errors = [], warnings = [], uid = uid, language = argd['ln'], navtrail = navtrail, lastupdated = __lastupdated__, req = req) # If it is an Ajax request, extract any JSON data. ajax_request, recid = False, None if form.has_key('jsondata'): json_data = json.loads(str(form['jsondata'])) # Deunicode all strings (Invenio doesn't have unicode # support). json_data = json_unicode_to_utf8(json_data) ajax_request = True if json_data.has_key('recID'): recid = json_data['recID'] json_response = {'resultCode': 0, 'ID': json_data['ID']} # Authorization. user_info = collect_user_info(req) if user_info['email'] == 'guest': # User is not logged in. if not ajax_request: # Do not display the introductory recID selection box to guest # users (as it used to be with v0.99.0): auth_code, auth_message = acc_authorize_action(req, 'runbibedit') referer = '/edit/' if self.recid: referer = '/record/%s/edit/' % self.recid return page_not_authorized(req=req, referer=referer, text=auth_message, navtrail=navtrail) else: # Session has most likely timed out. json_response.update({'resultCode': 100}) return json.dumps(json_response) elif self.recid: # Handle RESTful calls from logged in users by redirecting to # generic URL. redirect_to_url(req, '%s/record/edit/#state=edit&recid=%s&recrev=%s' % ( CFG_SITE_URL, self.recid, "")) elif recid is not None: json_response.update({'recID': recid}) # Authorize access to record. auth_code, auth_message = acc_authorize_action(req, 'runbibedit', collection=guess_primary_collection_of_a_record(recid)) if auth_code != 0: json_response.update({'resultCode': 101}) return json.dumps(json_response) # Handle request. if not ajax_request: # Show BibEdit start page. body, errors, warnings = perform_request_init(uid, argd['ln'], req, __lastupdated__) title = 'Record Editor' return page(title = title, body = body, errors = errors, warnings = warnings, uid = uid, language = argd['ln'], navtrail = navtrail, lastupdated = __lastupdated__, req = req) else: # Handle AJAX request. json_response.update(perform_request_ajax(req, recid, uid, json_data)) return json.dumps(json_response)