def create_error_box(req, title=None, verbose=1, ln=CFG_SITE_LANG, errors=None): """Analyse the req object and the sys traceback and return a text message box with internal information that would be suitful to display when something bad has happened. """ _ = gettext_set_language(ln) return webstyle_templates.tmpl_error_box(title=title, ln=ln, verbose=verbose, req=req, errors=errors)
def get_i18n_day_name(day_nb, display='short', ln=None): """Get the string representation of a weekday, internationalized @param day_nb: number of weekday UNIX like. => 0=Sunday @param ln: language for output @return: the string representation of the day """ ln = default_ln(ln) _ = gettext_set_language(ln) if display == 'short': days = {0: _("Sun"), 1: _("Mon"), 2: _("Tue"), 3: _("Wed"), 4: _("Thu"), 5: _("Fri"), 6: _("Sat")} else: days = {0: _("Sunday"), 1: _("Monday"), 2: _("Tuesday"), 3: _("Wednesday"), 4: _("Thursday"), 5: _("Friday"), 6: _("Saturday")} return days[day_nb]
def tmpl_error_page(self, ln=CFG_SITE_LANG, status="", admin_was_alerted=True): """ Display an error page. - status *string* - the HTTP status. """ _ = gettext_set_language(ln) out = """ <p>%(message)s</p> <p>%(alerted)s</p> <p>%(doubts)s</p>""" % { 'status': status, 'message': _("The server encountered an error while dealing with your request." ), 'alerted': admin_was_alerted and _("The system administrators have been alerted.") or '', 'doubts': _("In case of doubt, please contact %(x_admin_email)s.", x_admin_email='<a href="mailto:%(admin)s">%(admin)s</a>' % {'admin': CFG_SITE_SUPPORT_EMAIL}) } return out
def create_year_selectbox(name, from_year=-1, length=10, selected_year=0, ln=None): """Creates an HTML menu (dropdownbox) for year selection. @param name: name of control( i.e. name of the variable you'll get) @param from_year: year on which to begin. if <0 assume it is current year @param length: number of items in menu @param selected_year: initial selected year (if in range), else: label is selected @param ln: language @return: html as string """ ln = default_ln(ln) _ = gettext_set_language(ln) if from_year < 0: from_year = time.localtime()[0] out = "<select name=\"%s\">\n" % name out += ' <option value="0"' if selected_year == 0: out += ' selected="selected"' out += ">%s</option>\n" % _("Year") for i in range(from_year, from_year + length): out += "<option value=\"%i\"" % i if (i == selected_year): out += " selected=\"selected\"" out += ">%i</option>\n" % i out += "</select>\n" return out
def test_convert_buggy_datestruct_to_dategui_sk(self): from invenio_base.i18n import gettext_set_language ln = "sk" _ = gettext_set_language(ln) expected = _("N/A") struct = struct_time((-1, 11, 16, 15, 11, 44, 2, 320, 0)) result = dateutils.convert_datestruct_to_dategui(struct) self.assertEqual(expected, result)
def test_convert_bad_to_dategui_sk(self): """dateutils - conversion of bad text date into Slovak GUI date""" from invenio_base.i18n import gettext_set_language ln = "sk" _ = gettext_set_language(ln) datetext = "2006-02-AA 18:36:01" dategui_sk_expected = _("N/A") dategui_sk = dateutils.convert_datetext_to_dategui(datetext) assert dategui_sk == dategui_sk_expected
def test_convert_bad_to_dategui_sk(self): """dateutils - conversion of bad text date into Slovak GUI date""" from invenio_base.i18n import gettext_set_language ln = 'sk' _ = gettext_set_language(ln) datetext = "2006-02-AA 18:36:01" dategui_sk_expected = _('N/A') dategui_sk = dateutils.convert_datetext_to_dategui(datetext, ln=ln) self.assertEqual(dategui_sk, dategui_sk_expected)
def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """Bootstrap friendly-Create navigation trail box body Parameters: - 'ln' *string* - The language to display - 'title' *string* - page title; - 'previous_links' *string* - the trail content from site title until current page (both ends exclusive) - 'prolog' *string* - HTML code to prefix the navtrail item with - 'epilog' *string* - HTML code to suffix the navtrail item with - 'separator' *string* - HTML code that separates two navtrail items Output: - text containing the navtrail Note: returns empty string for Home page. (guessed by title). """ # load the right message language _ = gettext_set_language(ln) if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME): return "" # Breadcrumbs # breadcrumb objects should provide properties 'text' and 'url' # First element breadcrumbs = [ dict(text=_("Home"), url=CFG_SITE_URL), ] # Decode previous elements if previous_links: soup = BeautifulSoup(previous_links) for link in soup.find_all('a'): breadcrumbs.append( dict(text=unicode(' '.join(link.contents)), url=link.get('href'))) # Add head if title: breadcrumbs.append(dict(text=title, url='#')) return render_template_to_string( "breadcrumbs.html", breadcrumbs=breadcrumbs).encode('utf8')
def error_page(title, req, ln=CFG_SITE_LANG): # load the right message language _ = gettext_set_language(ln) site_name = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME) return page(title=_("Error"), body=create_error_box(req, title=str(title), verbose=0, ln=ln), description="%s - Internal Error" % site_name, keywords="%s, Internal Error" % site_name, uid=current_user.get_id(req), language=ln, req=req)
def warning_page(title, req, ln=CFG_SITE_LANG): # load the right message language _ = gettext_set_language(ln) site_name = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME) return page(title=_("Warning"), body=title, description="%s - Internal Error" % site_name, keywords="%s, Internal Error" % site_name, uid=current_user.get_id(req), language=ln, req=req)
def send_new_admin_account_warning(new_account_email, send_to, ln=CFG_SITE_LANG): """Send an email to the address given by send_to about the new account new_account_email.""" _ = gettext_set_language(ln) sub = _("New account on") + " '%s'" % CFG_SITE_NAME if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1: sub += " - " + _("PLEASE ACTIVATE") body = _("A new account has been created on") + " '%s'" % CFG_SITE_NAME if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1: body += _(" and is awaiting activation") body += ":\n\n" body += _(" Username/Email") + ": %s\n\n" % new_account_email body += _("You can approve or reject this account request at") + ": %s/admin/webaccess/webaccessadmin.py/manageaccounts\n" % CFG_SITE_URL return send_email(CFG_SITE_SUPPORT_EMAIL, send_to, subject=sub, content=body)
def error_page(title, req, ln=CFG_SITE_LANG): # load the right message language _ = gettext_set_language(ln) site_name = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME) return page(title = _("Error"), body = create_error_box(req, title=str(title), verbose=0, ln=ln), description="%s - Internal Error" % site_name, keywords="%s, Internal Error" % site_name, uid = current_user.get_id(req), language=ln, req=req)
def warning_page(title, req, ln=CFG_SITE_LANG): # load the right message language _ = gettext_set_language(ln) site_name = CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME) return page(title = _("Warning"), body = title, description="%s - Internal Error" % site_name, keywords="%s, Internal Error" % site_name, uid = current_user.get_id(req), language=ln, req=req)
def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """Bootstrap friendly-Create navigation trail box body Parameters: - 'ln' *string* - The language to display - 'title' *string* - page title; - 'previous_links' *string* - the trail content from site title until current page (both ends exclusive) - 'prolog' *string* - HTML code to prefix the navtrail item with - 'epilog' *string* - HTML code to suffix the navtrail item with - 'separator' *string* - HTML code that separates two navtrail items Output: - text containing the navtrail Note: returns empty string for Home page. (guessed by title). """ # load the right message language _ = gettext_set_language(ln) if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME): return "" # Breadcrumbs # breadcrumb objects should provide properties 'text' and 'url' # First element breadcrumbs = [dict(text=_("Home"), url=CFG_SITE_URL), ] # Decode previous elements if previous_links: soup = BeautifulSoup(previous_links) for link in soup.find_all('a'): breadcrumbs.append(dict( text=unicode(' '.join(link.contents)), url=link.get('href'))) # Add head if title: breadcrumbs.append(dict(text=title, url='#')) return render_template_to_string("breadcrumbs.html", breadcrumbs=breadcrumbs).encode('utf8')
def detailed_record_container_bottom(self, recid, tabs, ln=CFG_SITE_LANG, show_similar_rec_p=True, creationdate=None, modificationdate=None, show_short_rec_p=True): """Prints the box displayed in detailed records pages, with tabs at the top. Returns content as it is if the number of tabs for this record is smaller than 2 Parameters: - recid *int* - the id of the displayed record - tabs ** - the tabs displayed at the top of the box. - ln *string* - the language of the page in which the box is displayed - show_similar_rec_p *bool* print 'similar records' link in the box - creationdate *string* - the creation date of the displayed record - modificationdate *string* - the last modification date of the displayed record - show_short_rec_p *boolean* - prints a very short version of the record as reminder. """ # If no tabs, returns nothing if len(tabs) <= 1: return '' # load the right message language _ = gettext_set_language(ln) out = """ <div class="bottom-left-folded">%(dates)s</div> <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;"> </div> </div> </div> </div> <br/> """ % { 'dates': creationdate and '<div class="recordlastmodifiedbox" style="position:relative;margin-left:1px"> %(dates)s</div>' % { 'dates': _("Record created %(x_date_creation)s, last modified %(x_date_modification)s", x_date_creation=creationdate, x_date_modification=modificationdate), } or '' } return out
def tmpl_error_page(self, ln=CFG_SITE_LANG, status="", admin_was_alerted=True): """ Display an error page. - status *string* - the HTTP status. """ _ = gettext_set_language(ln) out = """ <p>%(message)s</p> <p>%(alerted)s</p> <p>%(doubts)s</p>""" % { 'status' : status, 'message' : _("The server encountered an error while dealing with your request."), 'alerted' : admin_was_alerted and _("The system administrators have been alerted.") or '', 'doubts' : _("In case of doubt, please contact %(x_admin_email)s.", x_admin_email='<a href="mailto:%(admin)s">%(admin)s</a>' % {'admin' : CFG_SITE_SUPPORT_EMAIL}) } return out
def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG): """Take URLARGS and LANGUAGE and return textual language selection box for the given page. Parameters: - 'req' - The mod_python request object - 'language' *string* - The selected language """ # load the right message language _ = gettext_set_language(language) # Work on a copy in order not to bork the arguments of the caller argd = {} if req and req.args: argd.update(cgi.parse_qs(req.args)) parts = [] for (lang, lang_namelong) in language_list_long(): if lang == language: parts.append('<span class="langinfo">%s</span>' % lang_namelong) else: # Update the 'ln' argument in the initial request argd['ln'] = lang if req and req.uri: args = urllib.quote( req.uri, '/:?') + make_canonical_urlargd(argd, {}) else: args = "" parts.append( create_html_link(args, {}, lang_namelong, {'class': "langinfo"})) if len(parts) > 1: return _("This site is also available in the following languages:") + \ "<br />" + ' '.join(parts) else: ## There is only one (or zero?) languages configured, ## so there so need to display language alternatives. return ""
def answer(self, req, user_info, of, cc, colls_to_search, p, f, search_units, ln): """Answer question given by context. Return (relevance, html_string) where relevance is integer from 0 to 100 indicating how relevant to the question the answer is (see C{CFG_WEBSEARCH_SERVICE_MAX_SERVICE_ANSWER_RELEVANCE} for details), and html_string being a formatted answer. """ from invenio.refextract_api import search_from_reference _ = gettext_set_language(ln) if f or not self.seems_a_journal_reference(p): return (0, "") (field, pattern) = search_from_reference(p.decode('utf-8')) if field is not "journal": return (0, "") recids = perform_request_search( req=req, p=pattern, f=field, cc=cc, c=colls_to_search) if not recids: return (0, "") if len(recids) == 1: recid = recids.pop() user_info = collect_user_info(req) return (100, """\ <p><span class="journalhint">%s</span></p> <table style="padding: 5px; border: 2px solid #ccc; margin: 20px"><tr><td> %s </td></tr></table>""" % (escape(_("Were you looking for this paper?")), print_record(recid, ln=ln, user_info=user_info))) query = "find rawref \"" + p + "\"" query_link = CFG_SITE_URL + '/search?' + urlencode({'p': query}) return (80, '<span class="journalhint">%s</span>' % ( _("Were you looking for a journal reference? Try: %(x_href)s") % {"x_href": '<a href="{0}">{1}</a>'.format( escape(query_link, True), escape(query))}, ))
def detailed_record_container_bottom(self, recid, tabs, ln=CFG_SITE_LANG, show_similar_rec_p=True, creationdate=None, modificationdate=None, show_short_rec_p=True): """Prints the box displayed in detailed records pages, with tabs at the top. Returns content as it is if the number of tabs for this record is smaller than 2 Parameters: - recid *int* - the id of the displayed record - tabs ** - the tabs displayed at the top of the box. - ln *string* - the language of the page in which the box is displayed - show_similar_rec_p *bool* print 'similar records' link in the box - creationdate *string* - the creation date of the displayed record - modificationdate *string* - the last modification date of the displayed record - show_short_rec_p *boolean* - prints a very short version of the record as reminder. """ # If no tabs, returns nothing if len(tabs) <= 1: return '' # load the right message language _ = gettext_set_language(ln) out = """ <div class="bottom-left-folded">%(dates)s</div> <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;"> </div> </div> </div> </div> <br/> """ % { 'dates' : creationdate and '<div class="recordlastmodifiedbox" style="position:relative;margin-left:1px"> %(dates)s</div>' % { 'dates': _("Record created %(x_date_creation)s, last modified %(x_date_modification)s", x_date_creation=creationdate, x_date_modification=modificationdate), } or '' } return out
def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG): """Take URLARGS and LANGUAGE and return textual language selection box for the given page. Parameters: - 'req' - The mod_python request object - 'language' *string* - The selected language """ # load the right message language _ = gettext_set_language(language) # Work on a copy in order not to bork the arguments of the caller argd = {} if req and req.args: argd.update(cgi.parse_qs(req.args)) parts = [] for (lang, lang_namelong) in language_list_long(): if lang == language: parts.append('<span class="langinfo">%s</span>' % lang_namelong) else: # Update the 'ln' argument in the initial request argd['ln'] = lang if req and req.uri: args = urllib.quote(req.uri, '/:?') + make_canonical_urlargd(argd, {}) else: args = "" parts.append(create_html_link(args, {}, lang_namelong, {'class': "langinfo"})) if len(parts) > 1: return _("This site is also available in the following languages:") + \ "<br />" + ' '.join(parts) else: ## There is only one (or zero?) languages configured, ## so there so need to display language alternatives. return ""
def get_user_info(uid, ln=CFG_SITE_LANG): """Get infos for a given user. @param uid: user id (int) @return: tuple: (uid, nickname, display_name) """ _ = gettext_set_language(ln) query = """SELECT id, nickname FROM "user" WHERE id=%s""" res = run_sql(query, (uid,)) if res: if res[0]: user = list(res[0]) if user[1]: user.append(user[1]) else: user[1] = str(user[0]) user.append(_("user") + ' #' + str(user[0])) return tuple(user) return (uid, '', _("N/A"))
def create_day_selectbox(name, selected_day=0, ln=None): """Creates an HTML menu for day selection. (0..31 values). @param name: name of the control (i.e. name of the var you'll get) @param selected_day: preselect a day. Use 0 for the label 'Day' @param ln: language of the menu @return: html a string """ ln = default_ln(ln) _ = gettext_set_language(ln) out = "<select name=\"%s\">\n" % name for i in range(0, 32): out += " <option value=\"%i\"" % i if (i == selected_day): out += " selected=\"selected\"" if (i == 0): out += ">%s</option>\n" % _("Day") else: out += ">%i</option>\n" % i out += "</select>\n" return out
def get_i18n_month_name(month_nb, display='short', ln=None): """Get a non-numeric representation of a month, internationalized. @param month_nb: number of month, (1 based!) =>1=jan,..,12=dec @param ln: language for output @return: the string representation of month """ ln = default_ln(ln) _ = gettext_set_language(ln) if display == 'short': months = {0: _("Month"), 1: _("Jan"), 2: _("Feb"), 3: _("Mar"), 4: _("Apr"), 5: _("May"), 6: _("Jun"), 7: _("Jul"), 8: _("Aug"), 9: _("Sep"), 10: _("Oct"), 11: _("Nov"), 12: _("Dec")} else: months = {0: _("Month"), 1: _("January"), 2: _("February"), 3: _("March"), 4: _("April"), 5: _("May "), # trailing space distinguishes short/long form 6: _("June"), 7: _("July"), 8: _("August"), 9: _("September"), 10: _("October"), 11: _("November"), 12: _("December")} return months[month_nb].strip()
def get_collectionbox_name(self, ln=None, box_type="r"): """Return collection-specific labelling subtrees. - 'Focus on': regular collection - 'Narrow by': virtual collection - 'Latest addition': boxes If translation for given language does not exist, use label for CFG_SITE_LANG. If no custom label is defined for CFG_SITE_LANG, return default label for the box. :param ln: the language of the label :param box_type: can be 'r' (=Narrow by), 'v' (=Focus on), 'l' (=Latest additions) """ if ln is None: ln = g.ln collectionboxnamequery = db.object_session(self).query( Collectionboxname).with_parent(self) try: collectionboxname = collectionboxnamequery.filter(db.and_( Collectionboxname.ln == ln, Collectionboxname.type == box_type, )).one() except Exception: try: collectionboxname = collectionboxnamequery.filter(db.and_( Collectionboxname.ln == ln, Collectionboxname.type == box_type, )).one() except Exception: collectionboxname = None if collectionboxname is None: # load the right message language _ = gettext_set_language(ln) return _(Collectionboxname.TYPES.get(box_type, '')) else: return collectionboxname.value
def answer(self, req, user_info, of, cc, colls_to_search, p, f, search_units, ln): """Answer question given by context, using knowledge base. Return (relevance, html_string) where relevance is integer from 0 to 100 indicating how relevant to the question the answer is (see L{CFG_WEBSEARCH_SERVICE_MAX_SERVICE_ANSWER_RELEVANCE} for details), and html_string being a formatted answer. """ _ = gettext_set_language(ln) # words = [stem(unit[1], ln) for unit in search_units if unit[2] == ''] words = [stem(unit[1].lower(), CFG_SITE_LANG) for unit in search_units if unit[2] == ""] cache = self.get_data_cache() matching_values = {} for word in words: res = cache.get(word, []) for keyword in res: if keyword not in matching_values: matching_values[keyword] = 1 else: matching_values[keyword] += 1 # order matching values per score matching_values_sorted = sorted(matching_values.iteritems(), key=lambda (k, v): (v, k), reverse=True) if not matching_values_sorted: return (0, "") best_score = matching_values_sorted[0][1] # Compute relevance. How many words from query did match relevance = min(100, max(0, (100 * float(best_score) / len([word for word in words if len(word) > 3])) - 10)) labels_and_links = [m.split("|", 1) for m in matching_values.keys()] translated_labels_and_links = [(_(label), url) for label, url in labels_and_links] return (relevance, self.display_answer_helper(translated_labels_and_links, ln))
def tmpl_error_box(self, ln, title, verbose, req, errors): """Produces an error box. Parameters: - 'title' *string* - The title of the error box - 'ln' *string* - The selected language - 'verbose' *bool* - If lots of information should be displayed - 'req' *object* - the request object - 'errors' list of tuples (error_code, error_message) """ # load the right message language _ = gettext_set_language(ln) info_not_available = _("N/A") if title is None: if errors: title = _("Error") + ': %s' % errors[0][1] else: title = _("Internal Error") browser_s = _("Browser") if req: try: if 'User-Agent' in req.headers_in: browser_s += ': ' + req.headers_in['User-Agent'] else: browser_s += ': ' + info_not_available host_s = req.hostname page_s = req.unparsed_uri client_s = req.remote_ip except: # FIXME: bad except browser_s += ': ' + info_not_available host_s = page_s = client_s = info_not_available else: browser_s += ': ' + info_not_available host_s = page_s = client_s = info_not_available error_s = '' sys_error_s = '' traceback_s = '' if verbose >= 1: if sys.exc_info()[0]: sys_error_s = '\n' + _("System Error") + ': %s %s\n' % \ (sys.exc_info()[0], sys.exc_info()[1]) if errors: errs = '' for error_tuple in errors: try: errs += "%s%s : %s\n " % (' ' * 6, error_tuple[0], error_tuple[1]) except: errs += "%s%s\n" % (' ' * 6, error_tuple) errs = errs[6:-2] # get rid of trainling ',' error_s = _("Error") + ': %s")' % errs + "\n" else: error_s = _("Error") + ': ' + info_not_available if verbose >= 9: traceback_s = '\n' + _("Traceback") + ': \n%s' % \ string.join(traceback.format_tb(sys.exc_info()[2]), "\n") out = """ <table class="errorbox"> <thead> <tr> <th class="errorboxheader"> <p> %(title)s %(sys1)s %(sys2)s</p> </th> </tr> </thead> <tbody> <tr> <td class="errorboxbody"> <p>%(contact)s</p> <blockquote><pre> URI: http://%(host)s%(page)s %(time_label)s: %(time)s %(browser)s %(client_label)s: %(client)s %(error)s%(sys_error)s%(traceback)s </pre></blockquote> </td> </tr> <tr> <td> </td> </tr> </tbody> </table> """ % { 'title' : cgi.escape(title).replace('"', '"'), 'time_label': _("Time"), 'client_label': _("Client"), 'send_error_label': \ _("Please send an error report to the administrator."), 'send_label': _("Send error report"), 'sys1' : cgi.escape(str((sys.exc_info()[0] or ''))).replace('"', '"'), 'sys2' : cgi.escape(str((sys.exc_info()[1] or ''))).replace('"', '"'), 'contact' : \ _("Please contact %(x_name)s quoting the following information:", x_name=('<a href="mailto:' + urllib.quote(CFG_SITE_SUPPORT_EMAIL) +'">' + CFG_SITE_SUPPORT_EMAIL + '</a>')), 'host' : cgi.escape(host_s), 'page' : cgi.escape(page_s), 'time' : time.strftime("%d/%b/%Y:%H:%M:%S %z"), 'browser' : cgi.escape(browser_s).replace('"', '"'), 'client' : cgi.escape(client_s).replace('"', '"'), 'error' : cgi.escape(error_s).replace('"', '"'), 'traceback' : cgi.escape(traceback_s).replace('"', '"'), 'sys_error' : cgi.escape(sys_error_s).replace('"', '"'), 'siteurl' : CFG_BASE_URL, 'referer' : page_s!=info_not_available and \ ("http://" + host_s + page_s) or \ info_not_available } return out
def tmpl_error_box(self, ln, title, verbose, req, errors): """Produces an error box. Parameters: - 'title' *string* - The title of the error box - 'ln' *string* - The selected language - 'verbose' *bool* - If lots of information should be displayed - 'req' *object* - the request object - 'errors' list of tuples (error_code, error_message) """ # load the right message language _ = gettext_set_language(ln) info_not_available = _("N/A") if title is None: if errors: title = _("Error") + ': %s' % errors[0][1] else: title = _("Internal Error") browser_s = _("Browser") if req: try: if 'User-Agent' in req.headers_in: browser_s += ': ' + req.headers_in['User-Agent'] else: browser_s += ': ' + info_not_available host_s = req.hostname page_s = req.unparsed_uri client_s = req.remote_ip except: # FIXME: bad except browser_s += ': ' + info_not_available host_s = page_s = client_s = info_not_available else: browser_s += ': ' + info_not_available host_s = page_s = client_s = info_not_available error_s = '' sys_error_s = '' traceback_s = '' if verbose >= 1: if sys.exc_info()[0]: sys_error_s = '\n' + _("System Error") + ': %s %s\n' % \ (sys.exc_info()[0], sys.exc_info()[1]) if errors: errs = '' for error_tuple in errors: try: errs += "%s%s : %s\n " % (' '*6, error_tuple[0], error_tuple[1]) except: errs += "%s%s\n" % (' '*6, error_tuple) errs = errs[6:-2] # get rid of trainling ',' error_s = _("Error") + ': %s")' % errs + "\n" else: error_s = _("Error") + ': ' + info_not_available if verbose >= 9: traceback_s = '\n' + _("Traceback") + ': \n%s' % \ string.join(traceback.format_tb(sys.exc_info()[2]), "\n") out = """ <table class="errorbox"> <thead> <tr> <th class="errorboxheader"> <p> %(title)s %(sys1)s %(sys2)s</p> </th> </tr> </thead> <tbody> <tr> <td class="errorboxbody"> <p>%(contact)s</p> <blockquote><pre> URI: http://%(host)s%(page)s %(time_label)s: %(time)s %(browser)s %(client_label)s: %(client)s %(error)s%(sys_error)s%(traceback)s </pre></blockquote> </td> </tr> <tr> <td> </td> </tr> </tbody> </table> """ % { 'title' : cgi.escape(title).replace('"', '"'), 'time_label': _("Time"), 'client_label': _("Client"), 'send_error_label': \ _("Please send an error report to the administrator."), 'send_label': _("Send error report"), 'sys1' : cgi.escape(str((sys.exc_info()[0] or ''))).replace('"', '"'), 'sys2' : cgi.escape(str((sys.exc_info()[1] or ''))).replace('"', '"'), 'contact' : \ _("Please contact %(x_name)s quoting the following information:", x_name=('<a href="mailto:' + urllib.quote(CFG_SITE_SUPPORT_EMAIL) +'">' + CFG_SITE_SUPPORT_EMAIL + '</a>')), 'host' : cgi.escape(host_s), 'page' : cgi.escape(page_s), 'time' : time.strftime("%d/%b/%Y:%H:%M:%S %z"), 'browser' : cgi.escape(browser_s).replace('"', '"'), 'client' : cgi.escape(client_s).replace('"', '"'), 'error' : cgi.escape(error_s).replace('"', '"'), 'traceback' : cgi.escape(traceback_s).replace('"', '"'), 'sys_error' : cgi.escape(sys_error_s).replace('"', '"'), 'siteurl' : CFG_BASE_URL, 'referer' : page_s!=info_not_available and \ ("http://" + host_s + page_s) or \ info_not_available } return out
def page_not_authorized(req, referer='', uid='', text='', navtrail='', ln=CFG_SITE_LANG, navmenuid=""): """Show error message when user is not authorized to do something. @param referer: in case the displayed message propose a login link, this is the url to return to after logging in. If not specified it is guessed from req. @param uid: the uid of the user. If not specified it is guessed from req. @param text: the message to be displayed. If not specified it will be guessed from the context. """ from invenio.legacy.webpage import page _ = gettext_set_language(ln) if not referer: referer = req.unparsed_uri if not CFG_ACCESS_CONTROL_LEVEL_SITE: title = CFG_WEBACCESS_MSGS[5] if not uid: uid = getUid(req) try: res = run_sql("""SELECT email FROM "user" WHERE id=%s AND note=1""", (uid,)) if res and res[0][0]: if text: body = text else: body = "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[9] % cgi.escape(res[0][0]), ("%s %s" % (CFG_WEBACCESS_MSGS[0] % urllib.quote(referer), CFG_WEBACCESS_MSGS[1]))) else: if text: body = text else: if CFG_ACCESS_CONTROL_LEVEL_GUESTS == 1: body = CFG_WEBACCESS_MSGS[3] else: body = CFG_WEBACCESS_WARNING_MSGS[4] + CFG_WEBACCESS_MSGS[2] except OperationalError as e: body = _("Database problem") + ': ' + str(e) elif CFG_ACCESS_CONTROL_LEVEL_SITE == 1: title = CFG_WEBACCESS_MSGS[8] body = "%s %s" % (CFG_WEBACCESS_MSGS[7], CFG_WEBACCESS_MSGS[2]) elif CFG_ACCESS_CONTROL_LEVEL_SITE == 2: title = CFG_WEBACCESS_MSGS[6] body = "%s %s" % (CFG_WEBACCESS_MSGS[4], CFG_WEBACCESS_MSGS[2]) return page(title=title, language=ln, uid=getUid(req), body=body, navtrail=navtrail, req=req, navmenuid=navmenuid)
def registerUser(req, email, passw, nickname, register_without_nickname=False, login_method=None, ln=CFG_SITE_LANG): """Register user with the desired values of NICKNAME, EMAIL and PASSW. If REGISTER_WITHOUT_NICKNAME is set to True, then ignore desired NICKNAME and do not set any. This is suitable for external authentications so that people can login without having to register an internal account first. Return 0 if the registration is successful, 1 if email is not valid, 2 if nickname is not valid, 3 if email is already in the database, 4 if nickname is already in the database, 5 when users cannot register themselves because of the site policy, 6 when the site is having problem contacting the user. If login_method is None or is equal to the key corresponding to local authentication, then CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS is taken in account for deciding the behaviour about registering. """ # is email valid? email = email.lower() if not email_valid_p(email): return 1 _ = gettext_set_language(ln) # is email already taken? res = run_sql("""SELECT email FROM "user" WHERE email=%s""", (email,)) if len(res) > 0: return 3 if register_without_nickname: # ignore desired nick and use default empty string one: nickname = "" else: # is nickname valid? if not nickname_valid_p(nickname): return 2 # is nickname already taken? res = run_sql("""SELECT nickname FROM "user" WHERE nickname=%s""", (nickname,)) if len(res) > 0: return 4 activated = 1 # By default activated if not login_method or not CFG_EXTERNAL_AUTHENTICATION[login_method]: # local login if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2: return 5 elif CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT: activated = 2 # Email confirmation required elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1: activated = 0 # Administrator confirmation required # okay, go on and register the user: FIXME user = User(nickname=nickname, email=email, password=passw, note=activated, last_login=datetime.datetime.now()) if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT: user.verify_email() try: db.session.add(user) db.session.commit() except Exception: current_app.logger.exception("Could not store user.") db.session.rollback() return 7 if activated == 1: # Ok we consider the user as logged in :-) setUid(req, uid) return 0
def prs_wash_arguments( req=None, cc=CFG_SITE_NAME, c=None, p="", f="", rg=CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS, sf="", so="d", sp="", rm="", of="id", ot="", aas=0, p1="", f1="", m1="", op1="", p2="", f2="", m2="", op2="", p3="", f3="", m3="", sc=0, jrec=0, recid=-1, recidb=-1, sysno="", id=-1, idb=-1, sysnb="", action="", d1="", d1y=0, d1m=0, d1d=0, d2="", d2y=0, d2m=0, d2d=0, dt="", verbose=0, ap=0, ln=CFG_SITE_LANG, ec=None, tab="", uid=None, wl=0, em="", **dummy ): """ Sets the (default) values and checks others for the PRS call """ # wash output format: of = wash_output_format(of) # wash all arguments requiring special care p = wash_pattern(p) f = wash_field(f) p1 = wash_pattern(p1) f1 = wash_field(f1) p2 = wash_pattern(p2) f2 = wash_field(f2) p3 = wash_pattern(p3) f3 = wash_field(f3) (d1y, d1m, d1d, d2y, d2m, d2d) = map(int, (d1y, d1m, d1d, d2y, d2m, d2d)) datetext1, datetext2 = wash_dates(d1, d1y, d1m, d1d, d2, d2y, d2m, d2d) # wash ranking method: if not is_method_valid(None, rm): rm = "" if id > 0 and recid == -1: recid = id if idb > 0 and recidb == -1: recidb = idb # deduce collection we are in (if applicable): if recid > 0: referer = None if req: referer = req.headers_in.get("Referer") cc = guess_collection_of_a_record(recid, referer) # deduce user id (if applicable): if uid is None: try: uid = getUid(req) except: uid = 0 _ = gettext_set_language(ln) kwargs = { "req": req, "cc": cc, "c": c, "p": p, "f": f, "rg": rg, "sf": sf, "so": so, "sp": sp, "rm": rm, "of": of, "ot": ot, "aas": aas, "p1": p1, "f1": f1, "m1": m1, "op1": op1, "p2": p2, "f2": f2, "m2": m2, "op2": op2, "p3": p3, "f3": f3, "m3": m3, "sc": sc, "jrec": jrec, "recid": recid, "recidb": recidb, "sysno": sysno, "id": id, "idb": idb, "sysnb": sysnb, "action": action, "d1": d1, "d1y": d1y, "d1m": d1m, "d1d": d1d, "d2": d2, "d2y": d2y, "d2m": d2m, "d2d": d2d, "dt": dt, "verbose": verbose, "ap": ap, "ln": ln, "ec": ec, "tab": tab, "wl": wl, "em": em, "datetext1": datetext1, "datetext2": datetext2, "uid": uid, "_": _, "selected_external_collections_infos": None, } kwargs.update(**dummy) return kwargs
def page( title, body, navtrail="", description="", keywords="", metaheaderadd="", uid=None, cdspageheaderadd="", cdspageboxlefttopadd="", cdspageboxleftbottomadd="", cdspageboxrighttopadd="", cdspageboxrightbottomadd="", cdspagefooteradd="", lastupdated="", language=CFG_SITE_LANG, verbose=1, titleprologue="", titleepilogue="", secure_page_p=0, req=None, errors=None, warnings=None, navmenuid="admin", navtrail_append_title_p=1, of="", rssurl=CFG_SITE_URL + "/rss", show_title_p=True, body_css_classes=None, show_header=True, show_footer=True, ): """page(): display CDS web page input: title of the page body of the page in html format description goes to the metadata in the header of the HTML page keywords goes to the metadata in the header of the html page metaheaderadd goes to further metadata in the header of the html page cdspageheaderadd is a message to be displayed just under the page header cdspageboxlefttopadd is a message to be displayed in the page body on left top cdspageboxleftbottomadd is a message to be displayed in the page body on left bottom cdspageboxrighttopadd is a message to be displayed in the page body on right top cdspageboxrightbottomadd is a message to be displayed in the page body on right bottom cdspagefooteradd is a message to be displayed on the top of the page footer lastupdated is a text containing the info on last update (optional) language is the language version of the page verbose is verbosity of the page (useful for debugging) titleprologue is to be printed right before page title titleepilogue is to be printed right after page title req is the mod_python request object log is the string of data that should be appended to the log file (errors automatically logged) secure_page_p is 0 or 1 and tells whether we are to use HTTPS friendly page elements or not navmenuid the section of the website this page belongs (search, submit, baskets, etc.) navtrail_append_title_p is 0 or 1 and tells whether page title is appended to navtrail of is an output format (use xx for xml output (e.g. AJAX)) rssfeed is the url of the RSS feed for this page show_title_p is 0 or 1 and tells whether page title should be displayed in body of the page show_header is 0 or 1 and tells whether page header should be displayed or not show_footer is 0 or 1 and tells whether page footer should be displayed or not output: the final cds page with header, footer, etc. """ _ = gettext_set_language(language) if req is not None: if uid is None: uid = getUid(req) secure_page_p = req.is_https() and 1 or 0 if uid is None: ## 0 means generic guest user. uid = 0 if of == "xx": # xml output (e.g. AJAX calls) => of=xx req.content_type = "text/xml" impl = getDOMImplementation() output = impl.createDocument(None, "invenio-message", None) root = output.documentElement body_node = output.createElement("body") body_text = output.createCDATASection(unicode(body, "utf_8")) body_node.appendChild(body_text) root.appendChild(body_node) return output.toprettyxml(encoding="utf-8") else: return webstyle_templates.tmpl_page( req, ln=language, description=description, keywords=keywords, metaheaderadd=metaheaderadd, userinfobox=create_userinfobox_body(req, uid, language), navtrailbox=create_navtrailbox_body(navtrail_append_title_p and title or "", navtrail, language=language), uid=uid, secure_page_p=secure_page_p, pageheaderadd=cdspageheaderadd, boxlefttop=CFG_WEBSTYLE_CDSPAGEBOXLEFTTOP, boxlefttopadd=cdspageboxlefttopadd, boxleftbottomadd=cdspageboxleftbottomadd, boxleftbottom=CFG_WEBSTYLE_CDSPAGEBOXLEFTBOTTOM, boxrighttop=CFG_WEBSTYLE_CDSPAGEBOXRIGHTTOP, boxrighttopadd=cdspageboxrighttopadd, boxrightbottomadd=cdspageboxrightbottomadd, boxrightbottom=CFG_WEBSTYLE_CDSPAGEBOXRIGHTBOTTOM, titleprologue=titleprologue, title=title, titleepilogue=titleepilogue, body=body, lastupdated=lastupdated, pagefooteradd=cdspagefooteradd, navmenuid=navmenuid, rssurl=rssurl, show_title_p=show_title_p, body_css_classes=body_css_classes, show_header=show_header, show_footer=show_footer, )
def get_label(self, ln=CFG_SITE_LANG): "Return label for the list of answers" _ = gettext_set_language(ln) return _("You might be interested in:")
def pretty_date(ugly_time=False, ln=None): """Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc. """ ln = default_ln(ln) _ = gettext_set_language(ln) now = real_datetime.now() if isinstance(ugly_time, six.string_types): # try to convert it to epoch timestamp date_format = '%Y-%m-%d %H:%M:%S.%f' try: ugly_time = time.strptime(ugly_time, date_format) ugly_time = int(time.mktime(ugly_time)) except ValueError: # doesn't match format, let's try to guess try: ugly_time = int(guess_datetime(ugly_time)) except ValueError: return ugly_time ugly_time = int(time.mktime(ugly_time)) # Initialize the time period difference if isinstance(ugly_time, int): diff = now - real_datetime.fromtimestamp(ugly_time) elif isinstance(ugly_time, real_datetime): diff = now - ugly_time elif not ugly_time: diff = now - now second_diff = diff.seconds day_diff = diff.days if day_diff < 0: return '' if day_diff == 0: if second_diff < 10: return _("just now") if second_diff < 60: return str(second_diff) + _(" seconds ago") if second_diff < 120: return _("a minute ago") if second_diff < 3600: return str(second_diff / 60) + _(" minutes ago") if second_diff < 7200: return _("an hour ago") if second_diff < 86400: return str(second_diff / 3600) + _(" hours ago") if day_diff == 1: return _("Yesterday") if day_diff < 7: return str(day_diff) + _(" days ago") if day_diff < 31: if day_diff / 7 == 7: return _("Last week") else: return str(day_diff / 7) + _(" weeks ago") if day_diff < 365: if day_diff / 30 == 1: return _("Last month") else: return str(day_diff / 30) + _(" months ago") if day_diff / 365 == 1: return _("Last year") else: return str(day_diff / 365) + _(" years ago")
def prs_wash_arguments(req=None, cc=CFG_SITE_NAME, c=None, p="", f="", rg=CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS, sf="", so="d", sp="", rm="", of="id", ot="", aas=0, p1="", f1="", m1="", op1="", p2="", f2="", m2="", op2="", p3="", f3="", m3="", sc=0, jrec=0, recid=-1, recidb=-1, sysno="", id=-1, idb=-1, sysnb="", action="", d1="", d1y=0, d1m=0, d1d=0, d2="", d2y=0, d2m=0, d2d=0, dt="", verbose=0, ap=0, ln=CFG_SITE_LANG, ec=None, tab="", uid=None, wl=0, em="", **dummy): """ Sets the (default) values and checks others for the PRS call """ # wash output format: of = wash_output_format(of) # wash all arguments requiring special care p = wash_pattern(p) f = wash_field(f) p1 = wash_pattern(p1) f1 = wash_field(f1) p2 = wash_pattern(p2) f2 = wash_field(f2) p3 = wash_pattern(p3) f3 = wash_field(f3) (d1y, d1m, d1d, d2y, d2m, d2d) = map(int, (d1y, d1m, d1d, d2y, d2m, d2d)) datetext1, datetext2 = wash_dates(d1, d1y, d1m, d1d, d2, d2y, d2m, d2d) # wash ranking method: if not is_method_valid(None, rm): rm = "" if id > 0 and recid == -1: recid = id if idb > 0 and recidb == -1: recidb = idb # deduce collection we are in (if applicable): if recid > 0: referer = None if req: referer = req.headers_in.get('Referer') cc = guess_collection_of_a_record(recid, referer) # deduce user id (if applicable): if uid is None: try: uid = getUid(req) except: uid = 0 _ = gettext_set_language(ln) kwargs = {'req': req, 'cc': cc, 'c': c, 'p': p, 'f': f, 'rg': rg, 'sf': sf, 'so': so, 'sp': sp, 'rm': rm, 'of': of, 'ot': ot, 'aas': aas, 'p1': p1, 'f1': f1, 'm1': m1, 'op1': op1, 'p2': p2, 'f2': f2, 'm2': m2, 'op2': op2, 'p3': p3, 'f3': f3, 'm3': m3, 'sc': sc, 'jrec': jrec, 'recid': recid, 'recidb': recidb, 'sysno': sysno, 'id': id, 'idb': idb, 'sysnb': sysnb, 'action': action, 'd1': d1, 'd1y': d1y, 'd1m': d1m, 'd1d': d1d, 'd2': d2, 'd2y': d2y, 'd2m': d2m, 'd2d': d2d, 'dt': dt, 'verbose': verbose, 'ap': ap, 'ln': ln, 'ec': ec, 'tab': tab, 'wl': wl, 'em': em, 'datetext1': datetext1, 'datetext2': datetext2, 'uid': uid, '_': _, 'selected_external_collections_infos': None, } kwargs.update(**dummy) return kwargs