def print_timeout(req, lang, engine, name, url): """Print info line for timeout.""" _ = gettext_set_language(lang) req.write('<a name="%s"></a>' % get_link_name(engine.name)) print_info_line(req, create_html_link(url, {}, name, {}, False, False), "", _("Search timed out.")) message = _("The external search engine has not responded in time. You can check its results here:") req.write(message + " " + create_html_link(url, {}, name, {}, False, False) + "<br />")
def tmpl_output_month_selection_bar(self, oai_src_id, ln, current_year=None, current_month=None): """constructs the month selection bar""" _ = gettext_set_language(ln) if current_month == None or current_year == None: current_month = datetime.datetime.today().month current_year = datetime.datetime.today().year prev_year = current_year prev_month = current_month prev_month -= 1 if prev_month == 0: prev_year -= 1 prev_month = 12 next_year = current_year next_month = current_month next_month += 1 if next_month == 13: next_year += 1 next_month = 1 current_date = datetime.datetime(current_year, current_month, 1) prevurl = create_html_link( urlbase=oai_harvest_admin_url + "/viewhistory", urlargd={"ln": ln, "oai_src_id": str(oai_src_id), "year": str(prev_year), "month": str(prev_month)}, link_label="<< " + _("previous month"), ) nexturl = create_html_link( urlbase=oai_harvest_admin_url + "/viewhistory", urlargd={"ln": ln, "oai_src_id": str(oai_src_id), "year": str(next_year), "month": str(next_month)}, link_label=_("next month") + " >>", ) result = prevurl + """ """ result += "<b>Current month: " + self.format_ym(current_date) + "</b>" result += """ """ + nexturl return result
def tmpl_papers_box(self, req, pubs, bibauthorid_data, num_downloads, ln, add_box=True, loading=False): _ = gettext_set_language(ln) if not loading and pubs: ib_pubs = intbitset(pubs) if bibauthorid_data["cid"]: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"]) elif bibauthorid_data["pid"] > -1: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"]) baid_query = baid_query + " " rec_query = baid_query searchstr = create_html_link(websearch_templates.build_search_url(p=rec_query), {}, "<strong>" + "All papers (" + str(len(pubs)) + ")" + "</strong>",) line2 = searchstr if CFG_BIBRANK_SHOW_DOWNLOAD_STATS and num_downloads: line2 += " (" + _("downloaded") + " " line2 += str(num_downloads) + " " + _("times") + ")" if CFG_INSPIRE_SITE: CFG_COLLS = ['Book', 'ConferencePaper', 'Introductory', 'Lectures', 'Preprint', 'Published', 'Review', 'Thesis'] else: CFG_COLLS = ['Article', 'Book', 'Preprint', ] collsd = {} for coll in CFG_COLLS: coll_papers = list(ib_pubs & intbitset(perform_request_search(rg=0, f="collection", p=coll))) if coll_papers: collsd[coll] = coll_papers colls = collsd.keys() colls.sort(lambda x, y: cmp(len(collsd[y]), len(collsd[x]))) # sort by number of papers for coll in colls: rec_query = baid_query + 'collection:' + wrap_author_name_in_quotes_if_needed(coll) line2 += "<br />" + create_html_link(websearch_templates.build_search_url(p=rec_query), {}, coll + " (" + str(len(collsd[coll])) + ")",) elif not pubs and not loading: line2 = _("No Papers") elif loading: line2 = self.loading_html() else: line2 = 'This is a bug and should be corrected' if not add_box: return line2 line1 = "<strong>" + _("Papers") + "</strong>" papers_box = self.tmpl_print_searchresultbox("papers", line1, line2) return papers_box
def print_timeout(req, lang, engine, name, url): """Print info line for timeout.""" _ = gettext_set_language(lang) req.write('<a name="%s"></a>' % get_link_name(engine.name)) print_info_line(req, create_html_link(url, {}, name, {}, False, False), '', _('Search timed out.')) message = _("The external search engine has not responded in time. You can check its results here:") req.write(message + ' ' + create_html_link(url, {}, name, {}, False, False) + '<br />')
def format_element(bfo, style): """ Offers link to search similar records @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" try: recid = bfo.control_field('001') except: raise Exception("Record not found") linkattrd = {} if style != '': linkattrd['style'] = style label = _("Similar records") out += create_html_link(CFG_SITE_URL + "/search", { 'ln': bfo.lang, 'rm': 'wrd', 'p': 'recid:%s' % bfo.control_field('001') }, link_label=label, linkattrd=linkattrd) return out
def format_element(bfo, style): """ Prints a link to simple file management interface (BibDocFile), if authorization is granted. @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibdocfile') if auth_code == 0: linkattrd = {} if style != '': linkattrd['style'] = style out += create_html_link(CFG_BASE_URL + '/%s/managedocfiles' % CFG_SITE_RECORD, urlargd={ 'ln': bfo.lang, 'recid': str(bfo.recID) }, link_label=_("Manage Files of This Record"), linkattrd=linkattrd) return out
def format_element(bfo, style): """ Prints a link to BibEdit, if authorization is granted @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info collection = guess_primary_collection_of_a_record(bfo.recID) (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibedit', collection=collection) if auth_code == 0: linkattrd = {} if style != '': linkattrd['style'] = style out += create_html_link(CFG_SITE_URL + '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)), {}, link_label=_("Edit This Record"), linkattrd=linkattrd) return out
def format_element(bfo, style, css_class): """ Prints a link to simple file management interface (BibDocFile), if authorization is granted. @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibdocfile') if auth_code == 0: linkattrd = {} if style != '': linkattrd['style'] = style if css_class != '': linkattrd['class'] = css_class out += create_html_link(CFG_SITE_URL + '/%s/managedocfiles' % CFG_SITE_RECORD, urlargd={'ln': bfo.lang, 'recid': str(bfo.recID)}, link_label= """<i class="icon-file"></i> %s""" % _("Manage Files"), linkattrd=linkattrd) return out
def format_element(bfo, style): """ Prints a link to simple file management interface (BibDocFile), if authorization is granted. @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibdocfile') if auth_code == 0: linkattrd = {} if style != '': linkattrd['style'] = style out += create_html_link(CFG_SITE_URL + '/submit/managedocfiles', urlargd={'ln': bfo.lang, 'recid': str(bfo.recID)}, link_label=_("Manage Files of This Record"), linkattrd=linkattrd) return out
def format_element(bfo, style, css_class): """ Prints a link to BibEdit, if authorization is granted @param style: the CSS style to be applied to the link. @param css_class: the CSS class to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info if user_can_edit_record_collection(user_info, bfo.recID): linkattrd = {} if style != '': linkattrd['style'] = style if css_class != '': linkattrd['class'] = css_class out += create_html_link( CFG_SITE_URL + '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)), {}, link_label="<i class=\"icon-pencil\"></i> %s" % _("Edit"), linkattrd=linkattrd) return out
def format_element(bfo, style, css_class): """ Prints a link to BibEdit, if authorization is granted @param style: the CSS style to be applied to the link. @param css_class: the CSS class to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info if user_can_edit_record_collection(user_info, bfo.recID): linkattrd = {} if style != '': linkattrd['style'] = style if css_class != '': linkattrd['class'] = css_class out += create_html_link(CFG_SITE_URL + '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)), {}, link_label="<i class=\"icon-pencil\"></i> %s" % _("Edit"), linkattrd=linkattrd) return out
def tmpl_bibdocfile_filelist(self, ln, recid, name, version, md, superformat, subformat, nice_size_f, description): """ Displays a file in the file list. Parameters: - 'ln' *string* - The language to display the interface in - 'recid' *int* - The id of the record - 'name' *string* - The name of the file - 'version' *string* - The version - 'md' *datetime* - the modification date - 'superformat' *string* - The display superformat - 'subformat' *string* - The display subformat - 'nice_size_f' *string* - The nice_size of the file - 'description' *string* - The description that might have been associated to the particular file """ # load the right message language _ = gettext_set_language(ln) urlbase = '%s/%s/%s/files/%s' % (CFG_SITE_URL, CFG_SITE_RECORD, recid, '%s%s' % (cgi.escape(name, True), superformat)) urlargd = {'version': version} if subformat: urlargd['subformat'] = subformat link_label = '%s%s' % (name, superformat) if subformat: link_label += ' (%s)' % subformat link = create_html_link(urlbase, urlargd, cgi.escape(link_label)) return """<tr> <td valign="top"> <small>%(link)s</small> </td> <td valign="top"> <font size="-2" color="green">[%(nice_size)s]</font> <font size="-2"><em>%(md)s</em> </td> <td valign="top"><em>%(description)s</em></td> </tr>""" % { 'link': link, 'nice_size': nice_size_f, 'md': convert_datestruct_to_dategui(md.timetuple(), ln), 'description': cgi.escape(description), }
def format(bfo, style): """ Prints a link to BibEdit, if authorization is granted @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info collection = guess_primary_collection_of_a_record(bfo.recID) (auth_code, auth_message) = acc_authorize_action(user_info, "runbibedit", collection=collection) if auth_code == 0: linkattrd = {} if style != "": linkattrd["style"] = style out += create_html_link( CFG_SITE_URL + "/record/" + str(bfo.recID) + "/edit/", urlargd={"ln": bfo.lang, "recid": str(bfo.recID)}, link_label=_("Edit This Record"), linkattrd=linkattrd, ) return out
def format_element(bfo, style): """ Prints a link to BibEdit, if authorization is granted @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" user_info = bfo.user_info collection = guess_primary_collection_of_a_record(bfo.recID) (auth_code, auth_message) = acc_authorize_action(user_info, 'runbibedit', collection=collection) if auth_code == 0: linkattrd = {} if style != '': linkattrd['style'] = style out += create_html_link(CFG_SITE_URL + '/record/edit/?ln=%s#state=edit&recid=%s' % (bfo.lang, str(bfo.recID)), {}, link_label=_("Edit This Record"), linkattrd=linkattrd) return out
def format_element(bfo, width="", caption="yes", max="3"): """ Display image of the plot if we are in selected plots collections @param width: the width of the returned image (Eg: '100px') @param caption: display the captions or not? @param max: the maximum number of plots to display (-1 is all plots) """ ## To achieve this, we take the pngs associated with this document img_files = [] max = int(max) link = "" bibarchive = BibRecDocs(bfo.recID) if width != "": width = 'width="%s"' % width for doc in bibarchive.list_bibdocs(): for _file in doc.list_latest_files(): if _file.get_type() == "Plot": try: caption_text = _file.get_description()[5:] index = int(_file.get_description()[:5]) img_location = _file.get_url() except: # FIXME: we have hit probably a plot context file, # so ignore this document; but it would be safer # to check subformat type, so that we don't mask # other eventual errors here. continue img = '<img style="vertical-align:middle;" src="%s" title="%s" %s/>' % \ (img_location, caption_text, width) plotlink = create_html_link(urlbase='%s/%s/%s/plots#%d' % (CFG_BASE_URL, CFG_SITE_RECORD, bfo.recID,\ index), urlargd={}, link_label=img) img_files.append((index, plotlink)) img_files = sorted(img_files, key=lambda x: x[0]) if max > 0: img_files = img_files[:max] if len(img_files) >= max: link = "<a href='/record/" + bfo.control_field('001') + "/plots'>Show more plots</a>" for index in range(len(img_files)): img_files[index] = img_files[index][1] if len(img_files) == 0: return '' return '<div style="overflow-x:auto;display:inline;width:100%;">' +\ " ".join(img_files) + ' ' + link + '</div>'
def tmpl_bibdocfile_filelist(self, ln, recid, name, version, md, superformat, subformat, nice_size_f, description): """ Displays a file in the file list. Parameters: - 'ln' *string* - The language to display the interface in - 'recid' *int* - The id of the record - 'name' *string* - The name of the file - 'version' *string* - The version - 'md' *datetime* - the modification date - 'superformat' *string* - The display superformat - 'subformat' *string* - The display subformat - 'nice_size_f' *string* - The nice_size of the file - 'description' *string* - The description that might have been associated to the particular file """ # load the right message language _ = gettext_set_language(ln) urlbase = '%s/%s/%s/files/%s' % ( CFG_SITE_URL, CFG_SITE_RECORD, recid, '%s%s' % (cgi.escape(name, True), superformat)) urlargd = {'version' : version} if subformat: urlargd['subformat'] = subformat link_label = '%s%s' % (name, superformat) if subformat: link_label += ' (%s)' % subformat link = create_html_link(urlbase, urlargd, cgi.escape(link_label)) return """<tr> <td valign="top"> <small>%(link)s</small> </td> <td valign="top"> <font size="-2" color="green">[%(nice_size)s]</font> <font size="-2"><em>%(md)s</em> </td> <td valign="top"><em>%(description)s</em></td> </tr>""" % { 'link' : link, 'nice_size' : nice_size_f, 'md' : convert_datestruct_to_dategui(md.timetuple(), ln), 'description' : cgi.escape(description), }
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",): """ Print link to push an entry to a remote server through SWORD @param remote_server_id: ID of the remove server to link to. When not specified, link to BibSword page allowing to select server. """ user_info = bfo.user_info auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient') if auth_code != 0: return "" sword_arguments = {'ln': bfo.lang, 'recid': bfo.recID} if remote_server_id: sword_arguments['id_remote_server'] = remote_server_id else: sword_arguments['status'] = 'select_server' linkattrd = {} if style != '': linkattrd['style'] = style if css_class != '': linkattrd['class'] = css_class return create_html_link(CFG_SITE_URL + '/bibsword', sword_arguments, link_label, linkattrd=linkattrd)
def detailed_record_container_bottom(self, recid, tabs, ln=CFG_SITE_LANG, show_similar_rec_p=True, creationdate=None, modificationdate=None, earliestdate=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 - earliestdate *string* - the earliest 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) similar = "" if show_similar_rec_p and not CFG_INSPIRE_SITE: similar = create_html_link( websearch_templates.build_search_url(p='recid:%d' % \ recid, rm='wrd', ln=ln), {}, _("Similar records"),{'class': "moreinfo"}) out = """ <div class="bottom-left-folded">%(dates)s</div> <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;"> <span class="moreinfo" style="margin-right:10px;">%(similar)s</span></div> </div> </div> </div> <br/> """ % {'similar' : similar, 'dates' : creationdate and '<div class="recordlastmodifiedbox" style="position:relative;margin-left:1px"> %(dates)s</div>' % { 'dates': _("Record added %(x_date_creation)s, last modified %(x_date_modification)s") % \ {'x_date_creation': creationdate, 'x_date_modification': modificationdate}, } or '' } return out
def tmpl_author_name_variants_box(self, names_dict, bibauthorid_data, ln, add_box=True, loading=False): """ Returns a dict consisting of: name -> frequency. """ _ = gettext_set_language(ln) header = "<strong>" + _("Name variants") + "</strong>" content = [] if loading: content = self.loading_html() else: if bibauthorid_data["cid"]: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"]) elif bibauthorid_data["pid"] > -1: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"]) else: baid_query = '' # perform_request_search function is not case sensitive, so we should agglomerate names which differ only in case new_names_dict = {} for name, papers_num in names_dict.iteritems(): ln = name.lower() caps = len(findall("[A-Z]", name)) try: prev_papers_num = new_names_dict[ln][1][1] new_papers_num = prev_papers_num + papers_num new_caps = new_names_dict[ln][0] new_name = new_names_dict[ln][1][0] if new_names_dict[ln][0] < caps: new_name = name new_caps = caps new_names_dict[ln] = [new_caps, (new_name, new_papers_num)] except KeyError: new_names_dict[ln] = [caps, (name, papers_num)] filtered_list = [name[1] for name in new_names_dict.values()] sorted_names_list = sorted(filtered_list, key=itemgetter(0), reverse=True) for name, frequency in sorted_names_list: if not name: name = '' prquery = baid_query + ' exactauthor:"' + name + '"' name_lnk = create_html_link(websearch_templates.build_search_url(p=prquery), {}, str(frequency),) content.append("%s (%s)" % (name, name_lnk)) content = "<br />\n".join(content) if not content: content = [_("No Name Variants")] if not add_box: return content names_box = self.tmpl_print_searchresultbox("name_variants", header, content) return names_box
def format_element(bfo, width="", caption="yes", max="3"): """ Display image of the plot if we are in selected plots collections @param width: the width of the returned image (Eg: '100px') @param caption: display the captions or not? @param max: the maximum number of plots to display (-1 is all plots) """ ## To achieve this, we take the pngs associated with this document img_files = [] max = int(max) link = "" bibarchive = BibRecDocs(bfo.recID) if width != "": width = 'width="%s"' % width for doc in bibarchive.list_bibdocs(): for _file in doc.list_latest_files(): if _file.get_type() == "Plot": try: caption_text = _file.get_description()[5:] index = int(_file.get_description()[:5]) img_location = _file.get_url() except: # FIXME: we have hit probably a plot context file, # so ignore this document; but it would be safer # to check subformat type, so that we don't mask # other eventual errors here. continue img = '<img style="vertical-align:middle;" src="%s" title="%s" %s/>' % \ (img_location, caption_text, width) link = create_html_link(urlbase='%s/%s/%s/plots#%d' % (CFG_SITE_URL, CFG_SITE_RECORD, bfo.recID,\ index), urlargd={}, link_label=img) img_files.append((index, link)) img_files = sorted(img_files, key=lambda x: x[0]) if max > 0: img_files = img_files[:max] link = "<a href='/record/" + bfo.control_field( '001') + "/plots'>Show more plots</a>" for index in range(len(img_files)): img_files[index] = img_files[index][1] if len(img_files) == 0: return '' return '<div style="overflow-x:auto;display:inline;width:100%;">' +\ " ".join(img_files) + ' ' + link + '</div>'
def tmpl_numpaperstitle(self, bibauthorid_data, pubs): if bibauthorid_data["cid"]: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"]) else: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"]) pubs_to_papers_link = create_html_link(websearch_templates.build_search_url(p=baid_query), {}, str(len(pubs))) return '(%s papers)' % pubs_to_papers_link
def format(bfo, width="", caption="yes", max="-1"): """ Display image of the plot if we are in selected plots collections @param width: the width of the returned image (Eg: '100px') @param separator: a separator between images @param caption: display the captions or not? @param max: the maximum number of plots to display (-1 is all plots) """ ## To achieve this, we take the pngs associated with this document img_files = [] max = int(max) bibarchive = BibRecDocs(bfo.recID) if width != "": width = 'width="%s"' % width for doc in bibarchive.list_bibdocs(): for _file in doc.list_latest_files(): if _file.get_type() == "Plot": try: caption_text = _file.get_description()[5:] index = int(_file.get_description()[:5]) img_location = _file.get_url() except: # FIXME: we have hit probably a plot context file, # so ignore this document; but it would be safer # to check subformat type, so that we don't mask # other eventual errors here. continue img = '<img src="%s" title="%s" %s/>' % \ (img_location, caption_text, width) link = create_html_link(urlbase='%s/record/%s/plots#%d' % (CFG_SITE_URL, bfo.recID,\ index), urlargd={}, link_label=img) img_files.append((index, link)) img_files = sorted(img_files, key=lambda x: x[0]) if max > 0: img_files = img_files[:max] for index in range(len(img_files)): img_files[index] = img_files[index][1] if len(img_files) == 0: return '' return '<div style="overflow-x:scroll;width=100%;white-space:nowrap">' +\ " ".join(img_files) + '</div>'
def print_fieldcode(fieldtuples): fieldstr = "" for (field, freq) in fieldtuples: if fieldstr: fieldstr += '<br>' rec_query = baid_query + ' ' + CFG_WEBAUTHORPROFILE_FIELDCODE_TAG + ':"' + field + '"' searchstr = field + ' (' + create_html_link(websearch_templates.build_search_url(p=rec_query), {}, str(freq),) + ')' fieldstr = fieldstr + " " + searchstr return fieldstr
def print_kw(kwtuples): keywstr = "" for (kw, freq) in kwtuples: if keywstr: keywstr += '<br>' rec_query = baid_query + ' keyword:"' + kw + '" ' searchstr = kw + ' (' + create_html_link(websearch_templates.build_search_url(p=rec_query), {}, str(freq),) + ')' keywstr = keywstr + " " + searchstr return keywstr
def print_collabs(collabs): collabstr = "" for (cl, freq) in collabs: if collabstr: collabstr += '<br>' rec_query = baid_query + ' collaboration:"' + cl + '"' searchstr = cl + ' (' + create_html_link(websearch_templates.build_search_url(p=rec_query), {}, str(freq),) + ')' collabstr = collabstr + " " + searchstr return collabstr
def tmpl_navtrail(self, ln=CFG_SITE_LANG, title=""): """ display the navtrail, e.g.: Your account > Your messages > title @param title: the last part of the navtrail. Is not a link @param ln: language return html formatted navtrail """ _ = gettext_set_language(ln) nav_h1 = create_html_link(CFG_SITE_URL + '/youraccount/display', {'ln': ln}, _("Your Account"), {'class': 'navtrail'}) nav_h2 = "" if (title != ""): nav_h2 += create_html_link(CFG_SITE_URL + '/yourmessages/display', {'ln': ln}, _("Your Messages"), {'class': 'navtrail'}) return nav_h1 + ' > ' + nav_h2 return nav_h1
def format_element(bfo, category_prefix, category_suffix, separator=" | ", display_all_categories='no'): """ Creates the main navigation menu of the journal @param category_prefix: value printed before each category @param category_suffix: value printed after each category @param separator: value printed between each category @param display_all_categories: if 'yes', show categories even when there is no corresponding article """ # Retrieve context (journal, issue and category) from URI args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] selected_category = args["category"] this_issue_number = args["issue"] ln = args["ln"] _ = gettext_set_language(ln) # Retrieve categories for this journal and issue journal_categories = get_journal_categories(journal_name, display_all_categories.lower() != 'yes' and \ this_issue_number or None) # Build the links to categories categories_links = [] for category in journal_categories: # Create URL category_url = make_journal_url(bfo.user_info['uri'], { 'category': category, 'recid': '', 'ln': bfo.lang }) # Create HTML link linkattrd = {} if category.lower() == selected_category.lower(): linkattrd = {'class': 'selectedNavigationPage'} if journal_name == 'CERNBulletin' and \ category == 'Training and Development': category = 'Training' category_link = create_html_link(category_url, {}, _(category), linkattrd=linkattrd) # Append to list of links categories_links.append(category_link) navigation = '<div id="navigationMenu">' navigation += separator.join([category_prefix + \ category_link + \ category_suffix for category_link \ in categories_links]) navigation += '</div>' return navigation
def hold_request_mail(recid, borrower_id): """ Create the mail who will be sent for each hold requests. @param recid: identify the record. Primary key of bibrec. @type recid: int @param borrower_id: identify the borrower. Primary key of crcBORROWER. @type borrower_id: int @return email(body) """ (book_title, book_year, book_author, book_isbn, book_editor) = book_information_from_MARC(recid) ############## need some code refactoring ############### more_holdings_infos = db.get_holdings_details(recid) borrower_infos = db.get_borrower_details(borrower_id) ######################################################### title_link = create_html_link( CFG_SITE_URL + "/admin/bibcirculation/bibcirculationadmin.py/get_item_details", {"recid": recid}, (book_title) ) out = """ This is an automatic email for confirming the hold request for a book on behalf of: %s (email: %s) title: %s author: %s location: %s library: %s publisher: %s year: %s isbn: %s """ % ( borrower_infos[1], borrower_infos[2], title_link, book_author, more_holdings_infos[0][1], more_holdings_infos[0][2], book_editor, book_year, book_isbn, ) return out
def build_report_number_link(report_number, link_p=True): """ Build HTML link out of given report number when it make sense (or is possible) and/or escape report number. @param report_number: the report number to consider @param link_p: if True, build link, otherwise just escape """ if link_p and report_number.lower().startswith("arxiv:"): return create_html_link("http://arxiv.org/abs/" + report_number, urlargd={}, link_label=report_number) else: return cgi.escape(report_number)
def perform_request_touchset(oai_set_id=None, ln=CFG_SITE_LANG, func=0): """creates html form to touch an OAI set""" _ = gettext_set_language(ln) out = "" if oai_set_id: oai_set = get_oai_set(oai_set_id) if not oai_set: return "ERROR: oai_set_id %s seems invalid" % oai_set_id oai_set = get_oai_set(oai_set_id) oai_set_spec = oai_set[0][1] oai_set_name = oai_set[0][2] oai_set_collection = oai_set[0][3] oai_set_p1 = oai_set[0][5] oai_set_f1 = oai_set[0][6] oai_set_m1 = oai_set[0][7] oai_set_p2 = oai_set[0][8] oai_set_f2 = oai_set[0][9] oai_set_m2 = oai_set[0][10] oai_set_p3 = oai_set[0][11] oai_set_f3 = oai_set[0][12] oai_set_m3 = oai_set[0][13] oai_set_op1 = oai_set[0][14] oai_set_op2 = oai_set[0][15] if func in ["0", 0]: if oai_set: question = _( """Do you want to touch the OAI set %s? Note that this will force all clients to re-harvest the whole set.""" ) % cgi.escape(oai_set_spec) text = oaiharvest_templates.tmpl_print_info(ln, question) out += createform(action="touchset", text=text, button="Touch", oai_set_id=oai_set_id, func=1) else: return oaiharvest_templates.tmpl_print_info( ln, _("OAI set does not exist.")) elif func in ["1", 1]: touch_oai_set(oai_set_spec) out += oaiharvest_templates.tmpl_print_info( ln, _("OAI set %s touched.") % cgi.escape(oai_set_spec)) out += "<br />" out += "<br /><br />" out += create_html_link(urlbase=oai_rep_admin_url + \ "/index", urlargd={'ln': ln}, link_label=_("Return to main selection")) return nice_box("", out)
def tmpl_output_month_selection_bar(self, oai_src_id, ln, current_year=None, current_month=None): """constructs the month selection bar""" _ = gettext_set_language(ln) if current_month == None or current_year == None: current_month = datetime.datetime.today().month current_year = datetime.datetime.today().year prev_year = current_year prev_month = current_month prev_month -= 1 if prev_month == 0: prev_year -= 1 prev_month = 12 next_year = current_year next_month = current_month next_month += 1 if next_month == 13: next_year += 1 next_month = 1 current_date = datetime.datetime(current_year, current_month, 1) prevurl = create_html_link(urlbase=oai_harvest_admin_url + \ "/viewhistory", urlargd={'ln':ln, 'oai_src_id': str(oai_src_id), 'year': str(prev_year), 'month': str(prev_month)}, link_label="<< " + _("previous month")) nexturl = create_html_link(urlbase=oai_harvest_admin_url + \ "/viewhistory", urlargd={'ln':ln, 'oai_src_id': str(oai_src_id), 'year': str(next_year), 'month': str(next_month)}, link_label=_("next month") + " >>") result = prevurl + """ """ result += "<b>Current month: " + self.format_ym(current_date) + "</b>" result += """ """ + nexturl return result
def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """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 """ _ = gettext_set_language(ln) previous_links = previous_links.strip() title = title.strip() if title == CFG_SITE_NAME: # Homepage return """ <ul id="breadcrumbs"> <li>%s</li> <li class="last">Infoscience</li> </ul>""" % create_html_link('http://www.epfl.ch', {}, 'EPFL', {'title': _("EPFL Homepage")}) if previous_links and not previous_links.startswith('<li'): previous_links = '<li>%s</li>' % previous_links if title and not title.startswith('<li'): title = '<li class="last">%s</li>' % saxutils.unescape(title) out = """ <ul id="breadcrumbs"> <li>%s</li> <li>%s</li> %s %s </ul>""" return out % (create_html_link('http://www.epfl.ch', {}, 'EPFL', {'title': _("EPFL Homepage")}), create_html_link('/', {'ln': ln}, 'Infoscience', {'title': _("Infoscience Homepage")}), previous_links, title)
def test_html_link_creation(self): """urlutils - test creation of HTML links""" # Check with various encoding and escaping traps self.assertEqual(create_html_link('http://www.a.com', {'a' : 1, 'b' : '2', 'b&': '2=', ':' : '?'}, 'my label > & better than yours', {'style': 'color:#f00', 'target': "_blank"}), '<a href="http://www.a.com?a=1&%3A=%3F&b%26=2%3D&b=2" style="color:#f00" target="_blank">my label > & better than yours</a>')
def tmpl_history_day_details_link(self, ln, date, oai_src_id): """Return link to detailed history for the day""" _ = gettext_set_language(ln) return create_html_link(urlbase=oai_harvest_admin_url + \ "/viewhistoryday", urlargd={'ln':ln, 'oai_src_id': str(oai_src_id), 'year': str(date.year), 'month': str(date.month), 'day': str(date.day), 'start': str(10)}, link_label=_("View next entries..."))
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) similar = "" if show_similar_rec_p and not CFG_INSPIRE_SITE: similar = create_html_link( websearch_templates.build_search_url(p='recid:%d' % \ recid, rm='wrd', ln=ln), {}, _("Similar records"),{'class': "moreinfo"}) out = """ <div class="bottom-left-folded">%(dates)s</div> <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;"> <span class="moreinfo" style="margin-right:10px;">%(similar)s</span></div> </div> </div> </div> <br/> """ % {'similar' : similar, '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 format_element(bfo, category_prefix, category_suffix, separator=" | ", display_all_categories='no'): """ Creates the main navigation menu of the journal @param category_prefix: value printed before each category @param category_suffix: value printed after each category @param separator: value printed between each category @param display_all_categories: if 'yes', show categories even when there is no corresponding article """ # Retrieve context (journal, issue and category) from URI args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] selected_category = args["category"] this_issue_number = args["issue"] ln = bfo.lang _ = gettext_set_language(ln) # Retrieve categories for this journal and issue journal_categories = get_journal_categories(journal_name, display_all_categories.lower() != 'yes' and \ this_issue_number or None) # Build the links to categories categories_links = [] for category in journal_categories: # Create URL category_url = make_journal_url(bfo.user_info['uri'], {'category': category, 'recid': '', 'ln': bfo.lang}) # Create HTML link linkattrd = {} if category.lower() == selected_category.lower(): linkattrd = {'class':'selectedNavigationPage'} if journal_name == 'CERNBulletin' and \ category == 'Training and Development': category = 'Training' if ln == 'fr': category = 'Formations' category_link = create_html_link(category_url, {}, _(category), linkattrd=linkattrd) # Append to list of links categories_links.append(category_link) navigation = '<div id="navigationMenu">' navigation += separator.join([category_prefix + \ category_link + \ category_suffix for category_link \ in categories_links]) navigation += '</div>' return navigation
def perform_request_addset(oai_set_name='', oai_set_spec='', oai_set_collection='', oai_set_description='', oai_set_p1='', oai_set_f1='', oai_set_m1='', oai_set_p2='', oai_set_f2='', oai_set_m2='', oai_set_p3='', oai_set_f3='', oai_set_m3='', oai_set_op1='a', oai_set_op2='a', ln=CFG_SITE_LANG, func=0): """add a new OAI set""" _ = gettext_set_language(ln) out = "" if func in ["0", 0]: text = input_form(oai_set_name, oai_set_spec, oai_set_collection, oai_set_p1, oai_set_f1, oai_set_m1, oai_set_p2, oai_set_f2, oai_set_m2, oai_set_p3, oai_set_f3, oai_set_m3, oai_set_op1, oai_set_op2) out = createform(action="addset", text=text, ln=ln, button="Add new OAI set definition line", func=1) if func in ["1", 1]: out += "<br />" res = add_oai_set(oai_set_name, oai_set_spec, oai_set_collection, oai_set_description, oai_set_p1, oai_set_f1, oai_set_m1, oai_set_p2, oai_set_f2, oai_set_m2, oai_set_p3, oai_set_f3, oai_set_m3, oai_set_op1, oai_set_op2) if res[0] == 1: out += oaiharvest_templates.tmpl_print_info(ln, "OAI set definition %s added." % \ cgi.escape(oai_set_name)) out += "<br />" out += "<br /><br />" out += create_html_link(urlbase=oai_rep_admin_url + \ "/index", urlargd={'ln': ln}, link_label=_("Return to main selection")) return nice_box("", out)
def test_html_link_creation_no_attribute_escaping(self): """urlutils - test creation of HTML links, without attributes escaping""" self.assertEqual(create_html_link('http://www.a.com', {'a' : 1, 'b' : '2', 'b&': '2=', ':' : '?'}, 'my label > & better than yours', {'style': 'color:#f00', 'target': "_blank"}, escape_linkattrd=False), '<a href="http://www.a.com?a=1&%3A=%3F&b%26=2%3D&b=2" style="color:#f00" target="_blank">my label > & better than yours</a>')
def perform_request_addset(oai_set_name='', oai_set_spec='', oai_set_collection='', oai_set_description='', oai_set_definition='', oai_set_reclist='', oai_set_p1='', oai_set_f1='',oai_set_m1='', oai_set_p2='', oai_set_f2='', oai_set_m2='', oai_set_p3='', oai_set_f3='', oai_set_m3='', oai_set_op1='a', oai_set_op2='a', ln=CFG_SITE_LANG, func=0): """add a new OAI set""" _ = gettext_set_language(ln) out = "" if func in ["0", 0]: text = input_form(oai_set_name, oai_set_spec, oai_set_collection, oai_set_description, oai_set_definition, oai_set_reclist, oai_set_p1, oai_set_f1,oai_set_m1, oai_set_p2, oai_set_f2,oai_set_m2, oai_set_p3, oai_set_f3, oai_set_m3, oai_set_op1, oai_set_op2, ln=ln) out = createform(action="addset", text=text, ln=ln, button="Add new OAI set definition line", func=1) lnargs = [["ln", ln]] if func in ["1", 1]: out += "<br />" res = add_oai_set(oai_set_name, oai_set_spec, oai_set_collection, oai_set_description, oai_set_definition, oai_set_reclist, oai_set_p1, oai_set_f1, oai_set_m1, oai_set_p2, oai_set_f2, oai_set_m2, oai_set_p3, oai_set_f3, oai_set_m3, oai_set_op1, oai_set_op2) if res[0] == 1: out += bibharvest_templates.tmpl_print_info(ln, "OAI set definition %s added." % \ cgi.escape(oai_set_name)) out += "<br />" out += "<br /><br />" out += create_html_link(urlbase=oai_rep_admin_url + \ "/index", urlargd={'ln': ln}, link_label=_("Return to main selection")) return nice_box("", out)
def tmpl_author_name_variants_box(self, req, names_dict, bibauthorid_data, ln, add_box=True, loading=False): ''' names_dict - a dict of {name: frequency} ''' _ = gettext_set_language(ln) if bibauthorid_data["cid"]: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed( bibauthorid_data["cid"]) elif bibauthorid_data["pid"] > -1: baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed( bibauthorid_data["pid"]) else: baid_query = '' sorted_names_list = sorted(names_dict.iteritems(), key=itemgetter(1), reverse=True) header = "<strong>" + _("Name variants") + "</strong>" content = [] for name, frequency in sorted_names_list: if not name: name = '' prquery = baid_query + ' exactauthor:"' + name + '"' name_lnk = create_html_link( websearch_templates.build_search_url(p=prquery), {}, str(frequency), ) content.append("%s (%s)" % (name, name_lnk)) if not content: content = [_("No Name Variants")] if loading: content = self.loading_html() else: content = "<br />\n".join(content) if not add_box: return content names_box = self.tmpl_print_searchresultbox("name_variants", header, content) return names_box
def build_report_number_link(report_number, link_p=True): """ Build HTML link out of given report number when it make sense (or is possible) and/or escape report number. @param report_number: the report number to consider @param link_p: if True, build link, otherwise just escape """ if link_p and report_number.lower().startswith('arxiv:'): return create_html_link('http://arxiv.org/abs/' + report_number, urlargd={}, link_label=report_number) else: return cgi.escape(report_number)
def print_aff(aff_pubdict): authoraff = "" for a in aff_pubdict: print_a = a[0] if (print_a == ' '): print_a = _("unknown affiliation") if authoraff: authoraff += '<br>' authoraff += (print_a + ' (' + create_html_link( websearch_templates.build_search_url(p=' or '.join( ["%s" % x for x in a[1]]), f='recid'), {}, str(len(a[1])),) + ')') return authoraff
def format_element(bfo, style): """ Offers action to delete a blog or a post @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" if bfo.user_info['email'] not in ["guest"]: coll = bfo.fields("980__a")[0] if coll in ['BLOG', 'BLOGPOST']: linkattrd = {} if style != '': linkattrd['style'] = style try: recid = bfo.control_field('001')[0] except: raise Exception("Record not found") if coll == 'BLOG': act = 'DBI' if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)): doctype = 'BSI' sub = 'DBIBSI' else: doctype = 'BSIREF' sub = 'DBIBSIREF' elif coll == 'BLOGPOST': act = 'DPI' if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)): doctype = 'BSI' sub = 'DPIBSI' else: doctype = 'BSIREF' sub = 'DPIBSIREF' out += create_html_link(CFG_SITE_URL + "/submit", {'ln': bfo.lang, 'doctype': doctype, 'indir': 'delete', 'act': act, 'sub': sub, 'BSI_RN': recid}, link_label = _("Ask for Deletion"), linkattrd = linkattrd) return out
def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """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) out = "" if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME): # return empty string for the Home page return out else: out += create_html_link(CFG_SITE_URL, {'ln': ln}, _("Home"), {'class': 'navtrail'}) if previous_links: if out: out += separator out += previous_links if title: if out: out += separator if title == CFG_SITE_NAME_INTL.get( ln, CFG_SITE_NAME): # hide site name, print Home instead out += cgi.escape(_("Home")) else: out += cgi.escape(title) return cgi.escape(prolog) + out + cgi.escape(epilog)
def format_element(bfo, fvalue, tag, item="Record", printtag="", default="", number_only=False, collection='', plural="Records"): """ uses tag to fetch a tag from the given bfo, searches that value in fvalue, and outputs the number of records found, linked to a search for those recs. @param fvalue field to search @param tag tag from record to use to search @param item string for X ITEM found - default ="Record" (see plural) @param printtag if non-null string will print X ITEMS <printtag> <tagvalue> so printtag=from would give: 23 Papers from SLAC @param default returned if there are no result [0 items] @param number_only return only the number of items with no formatting @param collection: which collection to search in [default=Home] @param plural string for X ITEMS (default = "Records") """ text = "" reccnt = 0 tagvalue = bfo.field(tag) if tagvalue: if printtag: text = " " + printtag + " " + tagvalue tagvalue = '"' + tagvalue + '"' reccnt = len( perform_request_search(p=tagvalue, f=fvalue, cc=collection)) if number_only: return reccnt if reccnt > 0: if reccnt == 1: text = item + text else: text = plural + text return create_html_link(urlbase='%s/search' % (CFG_BASE_URL, ), urlargd={ 'p': tagvalue, 'f': fvalue }, link_label=str(reccnt) + " " + text) if not default: default = "0 " + text return default
def tmpl_navtrailbox_body(self, ln, title, previous_links, separator, prolog, epilog): """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) out = "" if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME): # return empty string for the Home page return out else: out += create_html_link(CFG_SITE_URL, {'ln': ln}, _("Home"), {'class': 'navtrail'}) if previous_links: if out: out += separator out += previous_links if title: if out: out += separator if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME): # hide site name, print Home instead out += cgi.escape(_("Home")) else: out += cgi.escape(title) return cgi.escape(prolog) + out + cgi.escape(epilog)
def hold_request_mail(recid, borrower_id): """ Create the mail who will be sent for each hold requests. @param recid: identify the record. Primary key of bibrec. @type recid: int @param borrower_id: identify the borrower. Primary key of crcBORROWER. @type borrower_id: int @return email(body) """ (book_title, book_year, book_author, book_isbn, book_editor) = book_information_from_MARC(recid) ############## need some code refactoring ############### more_holdings_infos = db.get_holdings_details(recid) borrower_infos = db.get_borrower_details(borrower_id) ######################################################### title_link = create_html_link(CFG_SITE_URL + '/admin/bibcirculation/bibcirculationadmin.py/get_item_details', {'recid': recid}, (book_title)) out = """ This is an automatic email for confirming the hold request for a book on behalf of: %s (email: %s) title: %s author: %s location: %s library: %s publisher: %s year: %s isbn: %s """ % (borrower_infos[1], borrower_infos[2], title_link, book_author, more_holdings_infos[0][1], more_holdings_infos[0][2], book_editor, book_year, book_isbn) return out
def perform_request_touchset(oai_set_id=None, ln=CFG_SITE_LANG, func=0): """creates html form to touch an OAI set""" _ = gettext_set_language(ln) out = "" if oai_set_id: oai_set = get_oai_set(oai_set_id) if not oai_set: return "ERROR: oai_set_id %s seems invalid" % oai_set_id oai_set = get_oai_set(oai_set_id) oai_set_spec = oai_set[0][1] oai_set_name = oai_set[0][2] oai_set_collection = oai_set[0][3] oai_set_p1 = oai_set[0][5] oai_set_f1 = oai_set[0][6] oai_set_m1 = oai_set[0][7] oai_set_p2 = oai_set[0][8] oai_set_f2 = oai_set[0][9] oai_set_m2 = oai_set[0][10] oai_set_p3 = oai_set[0][11] oai_set_f3 = oai_set[0][12] oai_set_m3 = oai_set[0][13] oai_set_op1 = oai_set[0][14] oai_set_op2 = oai_set[0][15] if func in ["0", 0]: if oai_set: question = _("""Do you want to touch the OAI set %s? Note that this will force all clients to re-harvest the whole set.""") % cgi.escape(oai_set_spec) text = oaiharvest_templates.tmpl_print_info(ln, question) out += createform(action="touchset", text=text, button="Touch", oai_set_id=oai_set_id, func=1) else: return oaiharvest_templates.tmpl_print_info(ln, _("OAI set does not exist.")) elif func in ["1", 1]: touch_oai_set(oai_set_spec) out += oaiharvest_templates.tmpl_print_info(ln, _("OAI set %s touched.") % cgi.escape(oai_set_spec)) out += "<br />" out += "<br /><br />" out += create_html_link(urlbase=oai_rep_admin_url + \ "/index", urlargd={'ln': ln}, link_label=_("Return to main selection")) return nice_box("", out)
def tmpl_account_new_mail(self, nb_new_mail=0, total_mail=0, ln=CFG_SITE_LANG): """ display infos about inbox (used by myaccount.py) @param nb_new_mail: number of new mails @param ln: language return: html output. """ _ = gettext_set_language(ln) out = _("You have %(x_nb_new)s new messages out of %(x_nb_total)s messages") % \ {'x_nb_new': '<b>' + str(nb_new_mail) + '</b>', 'x_nb_total': create_html_link(CFG_SITE_URL + '/yourmessages/', {'ln': ln}, str(total_mail), {}, False, False)} return out + '.'