def tmpl_admin_update_issue(self, ln, journal_name, next_issue, current_issue): """ A form that lets a user make an update to an issue number. """ _ = gettext_set_language(ln) current_articles = get_number_of_articles_for_issue(current_issue, journal_name, ln) next_articles = get_number_of_articles_for_issue(next_issue, journal_name, ln) html = """ <p>The Issue that was released on week %(current_issue)s has pending updates scheduled. The next update for this issue is %(next_issue)s.</p> <p><em>Note: If you want to make a new release, please click through all the pending updates first.</em></p> <p>Do you want to release the update from issue: <br/> <em>%(current_issue)s</em> (%(current_articles)s) <br/> to issue: <br/> <em>%(next_issue)s</em> (%(next_articles)s) <br/> now?</p> <form action="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/issue_control" name="publish"> <input type="hidden" name="journal_name" value="%(journal_name)s"/> <input type="hidden" name="issue" value="%(next_issue)s"/> <input class="formbutton" type="submit" value="%(update)s" name="action"/> </form> """ % { "current_issue": current_issue, "next_issue": next_issue, "current_articles": ",".join(["%s : %s" % (item[0], item[1]) for item in current_articles.iteritems()]), "next_articles": ",".join(["%s : %s" % (item[0], item[1]) for item in next_articles.iteritems()]), "CFG_SITE_URL": CFG_SITE_URL, "journal_name": journal_name, "update": _("Update"), } return html
def websubmit_legacy_getfile(req, form): """ Handle legacy /getfile.py URLs """ args = wash_urlargd( form, { "recid": (int, 0), "docid": (int, 0), "version": (str, ""), "name": (str, ""), "format": (str, ""), "ln": (str, CFG_SITE_LANG), }, ) _ = gettext_set_language(args["ln"]) def _getfile_py(req, recid=0, docid=0, version="", name="", format="", ln=CFG_SITE_LANG): if not recid: ## Let's obtain the recid from the docid if docid: try: bibdoc = BibDoc(docid=docid) recid = bibdoc.get_recid() except InvenioWebSubmitFileError, e: return warningMsg( _("An error has happened in trying to retrieve the requested file."), req, CFG_SITE_NAME, ln ) else: return warningMsg(_("Not enough information to retrieve the document"), req, CFG_SITE_NAME, ln) else:
def tmpl_getnavtrail(self, previous="", ln=CFG_SITE_LANG): """Get the navigation trail - 'previous' *string* - The previous navtrail""" _ = gettext_set_language(ln) navtrail = """<a class="navtrail" href="%s/help/admin?ln=%s">Admin Area</a> """ % (CFG_SITE_URL, ln) navtrail = navtrail + previous return navtrail
def tmpl_admin_updated_issue_msg(self, ln, update_issue, journal_name): """ Prints a success message for the Update release of a journal. """ _ = gettext_set_language(ln) title = "<h2>Journal update %s published successfully!</h2>" % update_issue body = """<p>Now you can:</p> <p>Return to your journal here: >> <a href="%s/journal/%s"> %s </a> </p> <p>Go back to the publishing interface: >> <a href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">Issue Interface</a> </p> <p>Send an alert email here: >> <a href="%s/journal/alert?name=%s"> Send an alert</a> </p>""" % ( CFG_SITE_URL, journal_name, journal_name, CFG_SITE_URL, journal_name, CFG_SITE_URL, journal_name, ) return title + body
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 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 tmpl_admin_checkboxes(self, ln, title, name, values, labels, states, message=""): """Draws a list of HTML checkboxes - 'title' *string* - The name of the list of checkboxes - 'name' *string* - The name for this group of checkboxes - 'values' *list* - The values of the checkboxes - 'labels' *list* - The labels for the checkboxes - 'states' *list* - The previous state of each checkbox 1|0 - 'message' *string* - Put a message over the checkboxes. Optional. len(values) == len(labels) == len(states) """ _ = gettext_set_language(ln) text = """<div><div style="float:left;"><span class="adminlabel">%s</span></div>""" % title text += """<table><tr><td>""" if message: text += ' <small><i>(%s)</i></small><br/>' % (message,) for i in range(len(values)): value = values[i] label = labels[i] state = states[i] chk_box_id = value + str(i) text += ' <input type="checkbox"' \ 'name="%s" id="%s" value="%s" ' % (name, chk_box_id, value) if state: text += 'checked="checked "' text += "/>" text += """<label for="%s">%s</label><br/>""" % (chk_box_id, label) text += "</td></tr></table></div>" return text
def create_year_selectbox(name, from_year=-1, length=10, selected_year=0, ln=cdslang): """ 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 """ _ = gettext_set_language(ln) if from_year < 0: from_year = 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 tmpl_account_list_alerts(self, ln, alerts): """ Displays all the alerts in the main "Your account" page Parameters: - 'ln' *string* - The language to display the interface in - 'alerts' *array* - The existing alerts IDs ('id' + 'name' pairs) """ # load the right message language _ = gettext_set_language(ln) out = """<form name="displayalert" action="../youralerts/list" method="post"> %(you_own)s: <select name="id_alert"> <option value="0">- %(alert_name)s -</option>""" % { 'you_own' : _("You own the following alerts:"), 'alert_name' : _("alert name"), } for alert in alerts : out += """<option value="%(id)s">%(name)s</option>""" % \ {'id': alert['id'], 'name': cgi.escape(alert['name'])} out += """</select> <input class="formbutton" type="submit" name="action" value="%(show)s" /> </form>""" % { 'show' : _("SHOW"), } return out
def display(self, req, form): """ Display approved latest added linkbacks of the invenio instance """ argd = wash_urlargd(form, {'rg': (int, CFG_WEBLINKBACK_LATEST_COUNT_DEFAULT)}) # count must be positive if argd['rg'] < 0: argd['rg'] = -argd['rg'] _ = gettext_set_language(argd['ln']) body = perform_request_display_approved_latest_added_linkbacks(argd['rg'], argd['ln'], weblinkback_templates=weblinkback_templates) navtrail = 'Recent Linkbacks' mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader() return pageheaderonly(title=navtrail, navtrail=navtrail, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(argd['ln']) + \ body + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(language=argd['ln'], req=req)
def get_i18n_day_name(day_nb, display='short', ln=cdslang): """ 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 """ _ = 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 get_as_text(record_id=0, xml_record=None, ln=CFG_SITE_LANG): """Return the record in a textual format""" _ = gettext_set_language(ln) out = "" if record_id != 0: rec_in_hb = format_record(record_id, of="hb") elif xml_record: rec_in_hb = format_record(0, of="hb", xml_record=xml_record) rec_in_hb = rec_in_hb.replace("\n", " ") htparser = RecordHTMLParser() try: htparser.feed(rec_in_hb) htparser.close() out = htparser.result except: out = remove_html_markup(rec_in_hb) # Remove trailing whitespace and linefeeds out = out.strip("\n").strip() # Merge consecutive whitespaces. Must be done here, once all HTML # tags have been removed out = whitespaces_pattern.sub(" ", out) # Now consider non-breakable spaces out = out.replace(" ", " ") out = re.sub(r"[\-:]?\s*%s\s*[\-:]?" % _("Detailed record"), "", out) out = re.sub(r"[\-:]?\s*%s\s*[\-:]?" % _("Similar records"), "", out) out = re.sub(r"[\-:]?\s*%s\s*[\-:]?" % _("Cited by"), "", out) return out.strip()
def tmpl_confirm_delete(self, ln=CFG_SITE_LANG): """ display a confirm message @param ln: language @return: html output """ _ = gettext_set_language(ln) out = """ <table class="confirmoperation"> <tr> <td colspan="2" class="confirmmessage"> %(message)s </td> </tr> <tr> <td> <form name="validate" action="delete_all" method="post"> <input type="hidden" name="confirmed" value="1" /> <input type="hidden" name="ln" value="%(ln)s" /> <input type="submit" value="%(yes_label)s" class="formbutton" /> </form> </td> <td> <form name="cancel" action="display" method="post"> <input type="hidden" name="ln" value="%(ln)s" /> <input type="submit" value="%(no_label)s" class="formbutton" /> </form> </td> </tr> </table>"""% {'message': _("Are you sure you want to empty your whole mailbox?"), 'ln':ln, 'yes_label': _("Yes"), 'no_label': _("No")} return out
def test_string_translation(self): """webdoc - string translation""" result = transform('my_string: _(Search)_ (end)', languages=[CFG_SITE_LANG]) _ = gettext_set_language(CFG_SITE_LANG) self.assertEqual(result[0][1], 'my_string: %s (end)' % _("Search"))
def test_parts(self): """webdoc - retrieving parts of webdoc file (title, navtrail, etc)""" _ = gettext_set_language(CFG_SITE_LANG) result = transform(''' <!-- WebDoc-Page-Title: _(Help Central)_ --> <!-- WebDoc-Page-Navtrail: <a class="navtrail" href="<CFG_SITE_URL>/help/hacking">Hacking Invenio</a> > <a class="navtrail" href="webstyle-internals">WebStyle Internals</a> --> <!-- WebDoc-Page-Revision: $Id: help-central.webdoc,v 1.5 2008/05/26 12:52:41 jerome Exp $ --> <!-- WebDoc-Page-Description: A description -->''', languages=[CFG_SITE_LANG]) # Title self.assertEqual(result[0][2], _("Help Central")) # Keywords. None in our sample self.assertEqual(result[0][3], None) # Navtrail self.assertEqual(result[0][4], '<a class="navtrail" href="%s/help/hacking">Hacking Invenio</a> > <a class="navtrail" href="webstyle-internals">WebStyle Internals</a>' % CFG_SITE_URL) # Revision. Keep date & time only self.assertEqual(result[0][5], '2008-05-26 12:52:41') # Description self.assertEqual(result[0][6], 'A description')
def display_job_result(self, req, form): """Displays the results of a job""" argd = wash_urlargd(form, { "result_id": (int, JobResult.ID_MISSING), "output_format" : (int, Job.OUTPUT_FORMAT_MISSING) }) # load the right message language language = argd["ln"] _ = gettext_set_language(language) self._check_user_credentials(req, language) user_id = self._get_user_id(req) job_result_id = argd["result_id"] output_format = argd["output_format"] title = _("Export Job Result") try: body = perform_request_display_job_result(job_result_id = job_result_id, output_format = output_format, user_id = user_id, language = language) except AccessDeniedError: self._redirect_to_not_authorised_page(req, language) return page(title = title, metaheaderadd = get_css(), body = body, req = req, navmenuid = "fieldexporter", titleprologue = get_navigation_menu(language), navtrail = self._NAVTRAIL_EXPORT, language = language)
def download_job_result(self, req, form): """Returns to the browser zip file containing the job result""" argd = wash_urlargd(form, { "result_id" : (int, JobResult.ID_MISSING), "output_format" : (int, Job.OUTPUT_FORMAT_MISSING) }) # load the right message language language = argd["ln"] job_result_id = argd["result_id"] output_format = argd["output_format"] user_id = self._get_user_id(req) _ = gettext_set_language(language) self._check_user_credentials(req, language) title = _("Export Job Result") try: perform_request_download_job_result(req = req, job_result_id = job_result_id, output_format = output_format, user_id = user_id, language = language) except AccessDeniedError: self._redirect_to_not_authorised_page(req, language)
def tmpl_bibrecdoc_filelist(self, ln, types, verbose_files=''): """ Displays the file list for a record. Parameters: - 'ln' *string* - The language to display the interface in - 'types' *array* - The different types to display, each record in the format: - 'name' *string* - The name of the format - 'content' *array of string* - The HTML code produced by tmpl_bibdoc_filelist, for the right files - 'verbose_files' - A string representing in a verbose way the file information. """ # load the right message language _ = gettext_set_language(ln) out = "" for mytype in types: if mytype['name']: if not (CFG_INSPIRE_SITE and mytype['name'] == 'INSPIRE-PUBLIC'): out += "<small><b>%s</b> %s:</small>" % (mytype['name'], _("file(s)")) out += "<ul>" for content in mytype['content']: out += content out += "</ul>" if verbose_files: out += "<pre>%s</pre>" % verbose_files 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 index(self, req, form): """ The function called by default""" argd = wash_urlargd(form, { self._JSON_DATA_KEY: (str, ""), }) # load the right message language language = argd["ln"] _ = gettext_set_language(language) # check user credentials (auth_code, auth_msg) = acc_authorize_action(req, "runbibeditmulti") if 0 != auth_code: return page_not_authorized(req = req, ln = language, text = auth_msg) if argd[self._JSON_DATA_KEY]: return self._process_json_request(form, req) body = multi_edit_engine.perform_request_index(language) title = _("Multi-Record Editor") metaheaderadd = multi_edit_engine.get_scripts() metaheaderadd = metaheaderadd + multi_edit_engine.get_css() return page(title = title, metaheaderadd = metaheaderadd, body = body, req = req, language = language)
def tmpl_filelist(self, ln, filelist=''): """ Displays the file list for a record. Parameters: - 'ln' *string* - The language to display the interface in - 'recid' *int* - The record id - 'docname' *string* - The document name - 'version' *int* - The version of the document - 'filelist' *string* - The HTML string of the filelist (produced by the BibDoc classes) """ # load the right message language _ = gettext_set_language(ln) #title = _("record") + ' #' + '<a href="%s/%s/%s">%s</a>' % (CFG_SITE_URL, CFG_SITE_RECORD, recid, recid) #if docname != "": # title += ' ' + _("document") + ' #' + cgi.escape(str(docname)) #if version != "": # title += ' ' + _("version") + ' #' + str(version) out = """<div style="width:90%%;margin:auto;min-height:100px;margin-top:10px"> <!--start file list--> %s <!--end file list--></div> """ % (filelist) return out
def compare_revisions(self, req, form): """Handle the compare revisions request""" argd = wash_urlargd(form, { \ 'ln': (str, CFG_SITE_LANG), \ 'rev1' : (str, ''), \ 'rev2' : (str, ''), \ 'recid': (int, 0)}) ln = argd['ln'] uid = getUid(req) _ = gettext_set_language(ln) # Checking if currently logged user has permission to perform this request 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) recid = argd['recid'] rev1 = argd['rev1'] rev2 = argd['rev2'] ln = argd['ln'] body, errors, warnings = perform_request_compare(ln, recid, rev1, rev2) return page(title = _("Comparing two record revisions"), body = body, errors = errors, warnings = warnings, uid = uid, language = ln, navtrail = navtrail, lastupdated = __lastupdated__, req = req)
def format_template_show_attributes(req, bft, ln=CFG_SITE_LANG, new=0): """ Page for template name and descrition attributes edition. This is also the first page shown when a format template has just been added. In that case new is different from False and we can offer specific option to user (for ex let him make a duplicate of existing template). @param req: the request object @param ln: language @param bft: the name of the template to show @param new: if "False", the template has not just been added @return: a web page """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = bibformatadminlib.getnavtrail( """ > <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/format_templates_manage?ln=%s">%s</a>""" % (CFG_SITE_URL, ln, _("Manage Format Templates")) ) try: uid = getUid(req) except MySQLdb.Error, e: return error_page(req)
def output_format_show( req, bfo, ln=CFG_SITE_LANG, r_fld=[], r_val=[], r_tpl=[], default="", r_upd="", chosen_option="", **args ): """ Show a single output format. Check for authentication and print output format settings. The page either shows the output format from file, or from user's POST session, as we want to let him edit the rules without saving. Policy is: r_fld, r_val, rules_tpl are list of attributes of the rules. If they are empty, load from file. Else use POST. The i th value of each list is one of the attributes of rule i. Rule i is the i th rule in order of evaluation. All list have the same number of item. r_upd contains an action that has to be performed on rules. It can composed of a number (i, the rule we want to modify) and an operator : "save" to save the rules, "add" or "del". syntax: operator [number] For eg: r_upd = _("Save Changes") saves all rules (no int should be specified). For eg: r_upd = _("Add New Rule") adds a rule (no int should be specified). For eg: r_upd = _("Remove Rule") + " 5" deletes rule at position 5. The number is used only for operation delete. An action can also be in **args. We must look there for string starting with '(+|-) [number]' to increase (+) or decrease (-) a rule given by its index (number). For example "+ 5" increase priority of rule 5 (put it at fourth position). The string in **args can be followed by some garbage that looks like .x or .y, as this is returned as the coordinate of the click on the <input type="image">. We HAVE to use args and reason on its keys, because for <input> of type image, iexplorer does not return the value of the tag, but only the name. Action is executed only if we are working from user's POST session (means we must have loaded the output format first, which is totally normal and expected behaviour) @param req: the request object @param bfo: the filename of the output format to show @param ln: language @param r_fld: the list of 'field' attribute for each rule @param r_val: the list of 'value' attribute for each rule @param r_tpl: the list of 'template' attribute for each rule @param default: the default format template used by this output format @param r_upd: the rule that we want to increase/decrease in order of evaluation @param chosen_option: emptry string when user has not yet confirmed to go on @return: a web page """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = bibformatadminlib.getnavtrail( """ > <a class="navtrail" href="%s/admin/bibformat/bibformatadmin.py/output_formats_manage?ln=%s">%s</a>""" % (CFG_SITE_URL, ln, _("Manage Output Formats")) ) code = wash_url_argument(bfo, "str") try: uid = getUid(req) except MySQLdb.Error, e: return error_page(req)
def index(req, ln=CFG_SITE_LANG): """ Main BibFormat administration page. Displays a warning if we find out that etc/biformat dir is not writable by us (as most opeation of BibFormat must write in this directory). @param req: the request object @param ln: language @return: a web page """ warnings = [] if not bibformatadminlib.can_write_etc_bibformat_dir(): warnings.append(("WRN_BIBFORMAT_CANNOT_WRITE_IN_ETC_BIBFORMAT")) ln = wash_language(ln) _ = gettext_set_language(ln) # Check if user is authorized to administer # If not, still display page but offer to log in try: uid = getUid(req) except MySQLdb.Error, e: return error_page(req)
def create_citation_history_graph_and_box(recid, ln=CFG_SITE_LANG): """Create graph with citation history for record RECID (into a temporary file) and return HTML box refering to that image. Called by Detailed record pages. """ _ = gettext_set_language(ln) html_result = "" if cfg_bibrank_print_citation_history: coordinates = calculate_citation_history_coordinates(recid) if coordinates: html_head = """<br /><table><tr><td class="blocknote">%s</td></tr></table>""" % _("Citation history:") graphe_file_name = 'citation_%s_stats.png' % str(recid) remove_old_img(graphe_file_name) years = calculate_citation_graphe_x_coordinates(recid) years.sort() datas_info = write_coordinates_in_tmp_file([coordinates]) graphe = create_temporary_image(recid, 'citation', datas_info[0], 'Year', 'Times cited', [0,0], datas_info[1], [], ' ', years) graphe_image = graphe[0] graphe_source_file = graphe[1] if graphe_image and graphe_source_file: if os.path.exists(graphe_source_file): os.unlink(datas_info[0]) html_graphe_code = """<p>%s"""% html_command(graphe_image) html_result = html_head + html_graphe_code return html_result
def create_login_page_box(referer='', ln=CFG_SITE_LANG): # List of referer regexep and message to print _ = gettext_set_language(ln) login_referrer2msg = ( (re.compile(r"/search"), "<p>" + _("This collection is restricted. If you think you have right to access it, please authenticate yourself.") + "</p>"), (re.compile(r"/%s/\d+/files/.+" % CFG_SITE_RECORD), "<p>" + _("This file is restricted. If you think you have right to access it, please authenticate yourself.") + "</p>"), ) msg = "" for regexp, txt in login_referrer2msg: if regexp.search(referer): msg = txt break internal = None for system in CFG_EXTERNAL_AUTHENTICATION.keys(): if CFG_EXTERNAL_AUTHENTICATION[system] is None: internal = system break register_available = CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS <= 1 and internal ## Let's retrieve all the login method that are not dedicated to robots methods = [method[0] for method in CFG_EXTERNAL_AUTHENTICATION.iteritems() if not method[1] or not method[1].robot_login_method_p()] methods.sort() return websession_templates.tmpl_login_form( ln = ln, referer = referer, internal = internal, register_available = register_available, methods = methods, selected_method = CFG_EXTERNAL_AUTH_DEFAULT, msg = msg, )
def external_collection_overview(self, lang=CFG_SITE_LANG, engine_list=()): """Prints results overview box with links to particular collections below. lang: The language to display engine_list: The external engines to be used""" if len(engine_list) < 1: return "" _ = gettext_set_language(lang) out = """ <table class="externalcollectionsresultsbox"> <thead> <tr> <th class="externalcollectionsresultsboxheader"><strong>%s</strong></th> </tr> </thead> <tbody> <tr> <td class="externalcollectionsresultsboxbody"> """ % _("External collections results overview:") for engine in engine_list: internal_name = get_link_name(engine.name) name = _(engine.name) out += """<strong><a href="#%(internal_name)s">%(name)s</a></strong><br />""" % locals() out += """ </td> </tr> </tbody> </table> """ return out
def tmpl_webjournal_error_box(self, ln, title, title_msg, msg): """ returns an error box for webjournal errors. """ _ = gettext_set_language(ln) title = _(title) title_msg = _(title_msg) msg = _(msg) mail_msg = _("Contact %(x_url_open)sthe administrator%(x_url_close)s") % { "x_url_open": '<a href="mailto:%s">' % CFG_SITE_SUPPORT_EMAIL, "x_url_close": "</a>", } box = """ <div style="text-align: center;"> <fieldset style="width:400px; margin-left: auto; margin-right: auto;"> <legend style="color:#a70509;background-color:#fff;"> <i>%s</i> </legend> <p style="text-align:center;">%s</p> <br/> <div style="text-align:right;"> %s </div> </fieldset> </div> """ % ( title_msg, msg, mail_msg, ) return page(title=title, body=box)
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 add(self, req, form): """ Add a comment (review) to record with id recid where recid>0 Also works for adding a remark to basket with id recid where recid<-99 @param ln: languange @param recid: record id @param action: 'DISPLAY' to display add form 'SUBMIT' to submit comment once form is filled 'REPLY' to reply to an already existing comment @param msg: the body of the comment/review or remark @param score: star score of the review @param note: title of the review @param comid: comment id, needed for replying @param editor_type: the type of editor used for submitting the comment: 'textarea', 'fckeditor'. @param subscribe: if set, subscribe user to receive email notifications when new comment are added to this discussion @return the full html page. """ argd = wash_urlargd( form, { 'action': (str, "DISPLAY"), 'msg': (str, ""), 'note': (str, ''), 'score': (int, 0), 'comid': (int, 0), 'editor_type': (str, ""), 'subscribe': (str, ""), 'cookie': (str, "") }) _ = gettext_set_language(argd['ln']) actions = ['DISPLAY', 'REPLY', 'SUBMIT'] uid = getUid(req) # Is site ready to accept comments? if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS and not CFG_WEBCOMMENT_ALLOW_REVIEWS): return page_not_authorized(req, "../comments/add", navmenuid='search') # Is user allowed to post comment? user_info = collect_user_info(req) (auth_code_1, auth_msg_1) = check_user_can_view_comments(user_info, self.recid) (auth_code_2, auth_msg_2) = check_user_can_send_comments(user_info, self.recid) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) # Save user's value in cookie, so that these "POST" # parameters are not lost during login process msg_cookie = mail_cookie_create_common( 'comment_msg', { 'msg': argd['msg'], 'note': argd['note'], 'score': argd['score'], 'editor_type': argd['editor_type'], 'subscribe': argd['subscribe'] }, onetime=True) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {}) return redirect_to_url(req, target, norobot=True) elif (auth_code_1 or auth_code_2): return page_not_authorized(req, "../", \ text = auth_msg_1 + auth_msg_2) if argd['comid']: # If replying to a comment, are we on a record that # matches the original comment user is replying to? if not check_comment_belongs_to_record(argd['comid'], self.recid): return page_not_authorized(req, "../", \ text = _("Specified comment does not belong to this record")) # Is user trying to reply to a restricted comment? Make # sure user has access to it. We will then inherit its # restriction for the new comment (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid']) if auth_code: return page_not_authorized(req, "../", \ text = _("You do not have access to the specified comment")) # Is user trying to reply to a deleted comment? If so, we # let submitted comment go (to not lose possibly submitted # content, if comment is submitted while original is # deleted), but we "reset" comid to make sure that for # action 'REPLY' the original comment is not included in # the reply if is_comment_deleted(argd['comid']): argd['comid'] = 0 user_info = collect_user_info(req) can_attach_files = False (auth_code, auth_msg) = check_user_can_attach_file_to_comments( user_info, self.recid) if not auth_code and (user_info['email'] != 'guest'): can_attach_files = True warning_msgs = [] added_files = {} if can_attach_files: # User is allowed to attach files. Process the files file_too_big = False formfields = form.get('commentattachment[]', []) if not hasattr(formfields, "__getitem__"): # A single file was uploaded formfields = [formfields] for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]: if hasattr(formfield, "filename") and formfield.filename: filename = formfield.filename dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment', str(uid)) try: assert (dir_to_open.startswith(CFG_TMPDIR)) except AssertionError: register_exception(req=req, prefix='User #%s tried to upload file to forbidden location: %s' \ % (uid, dir_to_open)) if not os.path.exists(dir_to_open): try: os.makedirs(dir_to_open) except: register_exception(req=req, alert_admin=True) ## Before saving the file to disc, wash the filename (in particular ## washing away UNIX and Windows (e.g. DFS) paths): filename = os.path.basename(filename.split('\\')[-1]) filename = filename.strip() if filename != "": # Check that file does not already exist n = 1 while os.path.exists( os.path.join(dir_to_open, filename)): basedir, name, extension = decompose_file(filename) new_name = propose_next_docname(name) filename = new_name + extension fp = open(os.path.join(dir_to_open, filename), "w") # FIXME: temporary, waiting for wsgi handler to be # fixed. Once done, read chunk by chunk ## while formfield.file: ## fp.write(formfield.file.read(10240)) fp.write(formfield.file.read()) fp.close() # Isn't this file too big? file_size = os.path.getsize( os.path.join(dir_to_open, filename)) if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \ file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE: os.remove(os.path.join(dir_to_open, filename)) # One file is too big: record that, # dismiss all uploaded files and re-ask to # upload again file_too_big = True warning_msgs.append( ('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size / 1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE / 1024) + 'KB')) else: added_files[filename] = os.path.join( dir_to_open, filename) if file_too_big: # One file was too big. Removed all uploaded filed for filepath in added_files.items(): try: os.remove(filepath) except: # File was already removed or does not exist? pass client_ip_address = req.remote_ip check_warnings = [] (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln']) if ok: title, description, keywords = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln']) navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid)) # Infoscience modification navtrail += '<li><a href="%s/record/%s?ln=%s">%s</a></li>' % ( CFG_SITE_URL, self.recid, argd['ln'], title) navtrail += '<li class="last">%s</li>' % ( self.discussion == 1 and _('Reviews') or _('Comments')) if argd['action'] not in actions: argd['action'] = 'DISPLAY' if not argd['msg']: # User had to login in-between, so retrieve msg # from cookie try: (kind, cookie_argd) = mail_cookie_check_common(argd['cookie'], delete=True) argd.update(cookie_argd) except InvenioWebAccessMailCookieDeletedError, e: return redirect_to_url(req, CFG_SITE_URL + '/record/' + \ str(self.recid) + (self.discussion==1 and \ '/reviews' or '/comments')) except InvenioWebAccessMailCookieError, e: # Invalid or empty cookie: continue pass
def Create_Modify_Interface(parameters, curdir, form, user_info=None): """ Create an interface for the modification of a document, based on the fields that the user has chosen to modify. This avoids having to redefine a submission page for the modifications, but rely on the elements already defined for the initial submission i.e. SBI action (The only page that needs to be built for the modification is the page letting the user specify a document to modify). This function should be added at step 1 of your modification workflow, after the functions that retrieves report number and record id (Get_Report_Number, Get_Recid). Functions at step 2 are the one executed upon successful submission of the form. Create_Modify_Interface expects the following parameters: * "fieldnameMBI" - the name of a text file in the submission working directory that contains a list of the names of the WebSubmit fields to include in the Modification interface. These field names are separated by"\n" or "+". * "prefix" - some content displayed before the main modification interface. Can contain HTML (i.e. needs to be pre-escaped). The prefix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "suffix" - some content displayed after the main modification interface. Can contain HTML (i.e. needs to be pre-escaped). The suffix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "button_label" - the label for the "END" button. * "button_prefix" - some content displayed before the button to submit the form. Can contain HTML (i.e. needs to be pre-escaped). The prefix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "dates_conversion" - by default, values interpreted as dates are converted to their 'DD/MM/YYYY' format, whenever possible. Set another value for a different behaviour (eg. 'none' for no conversion) Given the list of WebSubmit fields to be included in the modification interface, the values for each field are retrieved for the given record (by way of each WebSubmit field being configured with a MARC Code in the WebSubmit database). An HTML FORM is then created. This form allows a user to modify certain field values for a record. The file referenced by 'fieldnameMBI' is usually generated from a multiple select form field): users can then select one or several fields to modify Note that the function will display WebSubmit Response elements, but will not be able to set an initial value: this must be done by the Response element iteself. Additionally the function creates an internal field named 'Create_Modify_Interface_DONE' on the interface, that can be retrieved in curdir after the form has been submitted. This flag is an indicator for the function that displayed values should not be retrieved from the database, but from the submitted values (in case the page is reloaded). You can also rely on this value when building your WebSubmit Response element in order to retrieve value either from the record, or from the submission directory. """ ln = wash_language(form['ln']) _ = gettext_set_language(ln) global sysno, rn t = "" # variables declaration fieldname = parameters['fieldnameMBI'] prefix = '' suffix = '' end_button_label = 'END' end_button_prefix = '' date_conversion_setting = '' if parameters.has_key('prefix'): prefix = parameters['prefix'] if parameters.has_key('suffix'): suffix = parameters['suffix'] if parameters.has_key('button_label') and parameters['button_label']: end_button_label = parameters['button_label'] if parameters.has_key('button_prefix'): end_button_prefix = parameters['button_prefix'] if parameters.has_key('dates_conversion'): date_conversion_setting = parameters['dates_conversion'] # Path of file containing fields to modify the_globals = { 'doctype': doctype, 'action': action, 'act': action, ## for backward compatibility 'step': step, 'access': access, 'ln': ln, 'curdir': curdir, 'uid': user_info['uid'], 'uid_email': user_info['email'], 'rn': rn, 'last_step': last_step, 'action_score': action_score, '__websubmit_in_jail__': True, 'form': form, 'sysno': sysno, 'user_info': user_info, '__builtins__': globals()['__builtins__'], 'Request_Print': Request_Print } if os.path.exists("%s/%s" % (curdir, fieldname)): fp = open("%s/%s" % (curdir, fieldname), "r") fieldstext = fp.read() fp.close() fieldstext = re.sub("\+", "\n", fieldstext) fields = fieldstext.split("\n") else: res = run_sql("SELECT fidesc FROM sbmFIELDDESC WHERE name=%s", (fieldname, )) if len(res) == 1: fields = res[0][0].replace(" ", "") fields = re.findall("<optionvalue=.*>", fields) regexp = re.compile( """<optionvalue=(?P<quote>['|"]?)(?P<value>.*?)(?P=quote)""") fields = [regexp.search(x) for x in fields] fields = [x.group("value") for x in fields if x is not None] fields = [x for x in fields if x not in ("Select", "select")] else: raise InvenioWebSubmitFunctionError("cannot find fields to modify") #output some text if not prefix: t += "<center bgcolor=\"white\">The document <b>%s</b> has been found in the database.</center><br />Please modify the following fields:<br />Then press the '%s' button at the bottom of the page<br />\n" % \ (rn, cgi.escape(_(end_button_label))) else: t += prefix % the_globals for field in fields: subfield = "" value = "" marccode = "" text = "" # retrieve and display the modification text t = t + "<FONT color=\"darkblue\">\n" res = run_sql("SELECT modifytext FROM sbmFIELDDESC WHERE name=%s", (field, )) if len(res) > 0: t = t + "<small>%s</small> </FONT>\n" % (res[0][0] is None and ' ' or res[0][0], ) # retrieve the marc code associated with the field res = run_sql("SELECT marccode FROM sbmFIELDDESC WHERE name=%s", (field, )) if len(res) > 0: marccode = res[0][0] # then retrieve the previous value of the field if os.path.exists("%s/%s" % (curdir, "Create_Modify_Interface_DONE")): # Page has been reloaded - get field value from text file on server, not from DB record value = Create_Modify_Interface_getfieldval_fromfile(curdir, field) else: # First call to page - get field value from DB record value = Create_Modify_Interface_getfieldval_fromDBrec( marccode, sysno) if date_conversion_setting != 'none': # If field is a date value, transform date into format DD/MM/YYYY: value = Create_Modify_Interface_transform_date(value) res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name=%s", (field, )) if len(res) > 0: element_type = res[0][3] numcols = res[0][6] numrows = res[0][5] size = res[0][4] maxlength = res[0][7] val = res[0][8] fidesc = res[0][9] if element_type == "T": text = "<textarea name=\"%s\" rows=%s cols=%s wrap>%s</textarea>" % ( field, numrows, numcols, cgi.escape(value)) elif element_type == "F": text = "<input type=\"file\" name=\"%s\" size=%s maxlength=\"%s\">" % ( field, size, maxlength) elif element_type == "I": text = "<input name=\"%s\" size=%s value=\"%s\"> " % ( field, size, val and escape_javascript_string( val, escape_quote_for_html=True) or '') text = text + '''<script type="text/javascript">/*<![CDATA[*/ document.forms[0].%s.value="%s"; /*]]>*/</script>''' % (field, escape_javascript_string( value, escape_for_html=False)) elif element_type == "H": text = "<input type=\"hidden\" name=\"%s\" value=\"%s\">" % ( field, val and escape_javascript_string( val, escape_quote_for_html=True) or '') text = text + '''<script type="text/javascript">/*<![CDATA[*/ document.forms[0].%s.value="%s"; /*]]>*/</script>''' % (field, escape_javascript_string( value, escape_for_html=False)) elif element_type == "S": values = re.split("[\n\r]+", value) text = fidesc if re.search("%s\[\]" % field, fidesc): multipletext = "[]" else: multipletext = "" if len(values) > 0 and not (len(values) == 1 and values[0] == ""): text += '<script type="text/javascript">/*<![CDATA[*/\n' text += "var i = 0;\n" text += "el = document.forms[0].elements['%s%s'];\n" % ( field, multipletext) text += "max = el.length;\n" for val in values: text += "var found = 0;\n" text += "var i=0;\n" text += "while (i != max) {\n" text += " if (el.options[i].value == \"%s\" || el.options[i].text == \"%s\") {\n" % \ (escape_javascript_string(val, escape_for_html=False), escape_javascript_string(val, escape_for_html=False)) text += " el.options[i].selected = true;\n" text += " found = 1;\n" text += " }\n" text += " i=i+1;\n" text += "}\n" #text += "if (found == 0) {\n" #text += " el[el.length] = new Option(\"%s\", \"%s\", 1,1);\n" #text += "}\n" text += "/*]]>*/</script>\n" elif element_type == "D": text = fidesc elif element_type == "R": try: co = compile(fidesc.replace("\r\n", "\n"), "<string>", "exec") ## Note this exec is safe WRT global variable because the ## Create_Modify_Interface has already been parsed by ## execfile within a protected environment. the_globals['text'] = '' exec co in the_globals text = the_globals['text'] except: msg = "Error in evaluating response element %s with globals %s" % ( pprint.pformat(field), pprint.pformat(globals())) register_exception(req=None, alert_admin=True, prefix=msg) raise InvenioWebSubmitFunctionError(msg) else: text = "%s: unknown field type" % field t = t + "<small>%s</small>" % text # output our flag field t += '<input type="hidden" name="Create_Modify_Interface_DONE" value="DONE\n" />' t += '<br />' if end_button_prefix: t += end_button_prefix % the_globals # output some more text t += "<br /><CENTER><small><INPUT type=\"button\" width=400 height=50 name=\"End\" value=\"%(end_button_label)s\" onClick=\"document.forms[0].step.value = 2;user_must_confirm_before_leaving_page = false;document.forms[0].submit();\"></small></CENTER></H4>" % { 'end_button_label': escape_javascript_string(_(end_button_label), escape_quote_for_html=True) } if suffix: t += suffix % the_globals return t
def tmpl_print_info(self, ln, infotext): """Outputs some info""" _ = gettext_set_language(ln) text = """<br /><b><span class="info">%s</span></b>""" % infotext return text
def display_webdoc_page(webdocname, categ="help", ln=CFG_SITE_LANG, req=None): """Display webdoc page WEBDOCNAME in language LN.""" _ = gettext_set_language(ln) uid = getUid(req) # wash arguments: if not webdocname: webdocname = 'help-central' ln_link = (ln != CFG_SITE_LANG and '?ln=' + ln) or '' # get page parts in given language: if webdocname != 'contents': page_parts = get_webdoc_parts(webdocname, parts=[ 'title', 'body', 'navtrail', 'lastupdated', 'description', 'keywords' ], categ=categ, ln=ln) else: # Print Table of Contents see_also_links = {'admin': '<a href="%s/help/admin/contents%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _('Admin Pages')), 'help':'<a href="%s/help/contents%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _('Help Pages')), 'hacking':'<a href="%s/help/hacking/contents%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _('Hacking Pages'))} titles = { 'admin': _("Admin Pages"), 'help': _("Help Pages"), 'hacking': _("Hacking Pages") } navtrails = {'admin': '<a class="navtrail" href="%s/help/admin%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _("Admin Area")), 'help': '<a class="navtrail" href="%s/help/%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _("Help Central")), 'hacking': '<a class="navtrail" href="%s/help/hacking%s">%s</a>' % \ (CFG_SITE_URL, ln_link, _("Hacking Invenio"))} body = '''<div style="float:right;clear:none;font-size:small;color:#666;width:auto;margin-right:30px;padding:5px" class="mini-panel"><strong>''' + \ _("Latest modifications:") + '</strong>' + \ get_webdoc_topics(sort_by='date', sc=0, limit=5, categ=[categ], ln=ln) + \ '</div>' + '<p>' +_('This is the table of contents of the %(x_category)s pages.') % {'x_category': categ} if categ != 'help': body += ' ' + _('See also') + ' ' + \ ', '.join([ link for (category, link) in \ see_also_links.iteritems() \ if category != categ]) + '.' body += '</p>' + get_webdoc_topics( sort_by='name', sc=1, categ=[categ], ln=ln) page_parts = { 'title': titles.get(categ, ''), 'body': body, 'navtrail': navtrails.get(categ, '') } # set page title: page_title = page_parts.get('title', '') if not page_title: page_title = _("Page %s Not Found") % cgi.escape(webdocname) # set page navtrail: page_navtrail = page_parts.get('navtrail', '') # set page body: page_body = page_parts.get('body', '') if not page_body: page_body = '<p>' + (_("Sorry, page %s does not seem to exist.") % \ ('<strong>' + cgi.escape(webdocname) + '</strong>')) + \ '</p>' page_body += '<p>' + (_("You may want to look at the %(x_url_open)s%(x_category)s pages%(x_url_close)s.") % \ {'x_category': _(categ), 'x_url_open': '<a href="%s/help/%scontents%s">' % \ (CFG_SITE_URL, ((categ != 'help' and categ + '/') or ''), ln_link), 'x_url_close': '</a>'}) + \ '</p>' # set page description: page_description = page_parts.get('description', '') # set page keywords: page_keywords = page_parts.get('keywords', '') # set page last updated timestamp: page_last_updated = page_parts.get('lastupdated', '') if categ == 'hacking': categ = 'help' # display page: return page(title=page_title, body=page_body, navtrail=page_navtrail, description=page_description, keywords=page_keywords, uid=uid, language=ln, req=req, navmenuid=categ)
def format_element(bfo, detail='no'): """ Prints the data of an institute authority record in HTML. By default prints brief version. @param detail: whether the 'detailed' rather than the 'brief' format @type detail: 'yes' or 'no' """ from invenio.messages import gettext_set_language _ = gettext_set_language(bfo.lang) # load the right message language # return value out = "" # brief main_dicts = bfo.fields('110%%') if len(main_dicts): main = main_dicts[0].get('a') or "" out += "<p>" + "<strong>" + _("Main %s name") % _( "institute") + "</strong>" + ": " + main + "</p>" # detail if detail.lower() == "yes": sees = [ see_dict['a'] for see_dict in bfo.fields('410%%') if 'a' in see_dict ] sees = filter(None, sees) # fastest way to remove empty ""s if len(sees): out += "<p>" + "<strong>" + _( "Variant(s)") + "</strong>" + ": " + ", ".join(sees) + "</p>" see_also_dicts = bfo.fields('510%%') cc_val = CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME c_val = "Institutes" record_url_pattern = "/record/" + "%s" search_url_pattern = "/search?" + \ "cc=" + "%s" + \ "&c=" + "%s" + \ "&p=" + "%s" + \ "&sc=" + "%s" link_pattern = "<a href='" + CFG_SITE_URL + '%s' + "'>" + '%s' + "</a>" # populate the first 3 lists parent_htmls, predecessor_htmls, successor_htmls = \ get_main_htmls(see_also_dicts, cc_val, c_val, record_url_pattern, search_url_pattern, link_pattern) # populate the list of children child_htmls = \ get_child_htmls(bfo.recID, cc_val, c_val, record_url_pattern, link_pattern) # put it all together if len(parent_htmls): out += "<p>" + "<strong>" + _( "Parent") + "</strong>" + ": " + ", ".join( parent_htmls) + "</p>" if len(child_htmls): out += "<p>" + "<strong>" + _( "Children") + "</strong>" + ": " + ", ".join( child_htmls) + "</p>" if len(predecessor_htmls): out += "<p>" + "<strong>" + _( "Predecessor") + "</strong>" + ": " + ", ".join( predecessor_htmls) + "</p>" if len(successor_htmls): out += "<p>" + "<strong>" + _( "Successor") + "</strong>" + ": " + ", ".join( successor_htmls) + "</p>" # return return out
def _get(self, req, form): """ Returns a file attached to a comment. Example: CFG_SITE_URL/record/5953/comments/attachments/get/652/myfile.pdf where 652 is the comment ID """ argd = wash_urlargd(form, {'file': (str, None), 'comid': (int, 0)}) _ = gettext_set_language(argd['ln']) # Can user view this record, i.e. can user access its # attachments? uid = getUid(req) user_info = collect_user_info(req) # Check that user can view record, and its comments (protected # with action "viewcomment") (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) # Does comment exist? if not query_get_comment(argd['comid']): req.status = apache.HTTP_NOT_FOUND return page(title=_("Page Not Found"), body=_('The requested comment could not be found'), req=req) # Check that user can view this particular comment, protected # using its own restriction (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid']) if auth_code and user_info['email'] == 'guest': cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/youraccount/login' + \ make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \ CFG_SITE_URL + user_info['uri']}, {}) return redirect_to_url(req, target) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg, ln=argd['ln']) # Check that comment is not currently deleted if is_comment_deleted(argd['comid']): return page_not_authorized(req, "../", \ text = _("You cannot access files of a deleted comment"), ln=argd['ln']) if not argd['file'] is None: # Prepare path to file on disk. Normalize the path so that # ../ and other dangerous components are removed. path = os.path.abspath(CFG_PREFIX + '/var/data/comments/' + \ str(self.recid) + '/' + str(argd['comid']) + \ '/' + argd['file']) # Check that we are really accessing attachements # directory, for the declared record. if path.startswith(CFG_PREFIX + '/var/data/comments/' + \ str(self.recid)) and \ os.path.exists(path): return stream_file(req, path) # Send error 404 in all other cases req.status = apache.HTTP_NOT_FOUND return page(title=_("Page Not Found"), body=_('The requested file could not be found'), req=req, language=argd['ln'])
def report(self, req, form): """ Report a comment/review for inappropriate content @param comid: comment/review id @param recid: the id of the record the comment/review is associated with @param ln: language @param do: display order hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param ds: display since all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param nb: number of results per page @param p: results page @param referer: http address of the calling function to redirect to (refresh) @param reviews: boolean, enabled for reviews, disabled for comments """ argd = wash_urlargd( form, { 'comid': (int, -1), 'recid': (int, -1), 'do': (str, "od"), 'ds': (str, "all"), 'nb': (int, 100), 'p': (int, 1), 'referer': (str, None) }) _ = gettext_set_language(argd['ln']) client_ip_address = req.remote_ip uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if isGuestUser(uid): cookie = mail_cookie_create_authorize_action( VIEWRESTRCOLL, { 'collection': guess_primary_collection_of_a_record( self.recid) }) target = '/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) # Check that comment belongs to this recid if not check_comment_belongs_to_record(argd['comid'], self.recid): return page_not_authorized(req, "../", \ text = _("Specified comment does not belong to this record")) # Check that user can access the record (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid']) if auth_code: return page_not_authorized(req, "../", \ text = _("You do not have access to the specified comment")) # Check that comment is not currently deleted if is_comment_deleted(argd['comid']): return page_not_authorized(req, "../", \ text = _("You cannot report a deleted comment"), ln=argd['ln']) success = perform_request_report(argd['comid'], client_ip_address, uid) if argd['referer']: argd[ 'referer'] += "?ln=%s&do=%s&ds=%s&nb=%s&p=%s&reported=%s&" % ( argd['ln'], argd['do'], argd['ds'], argd['nb'], argd['p'], str(success)) redirect_to_url(req, argd['referer']) else: #Note: sent to comments display referer = "%s/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 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.search_engine import \ get_permitted_restricted_collections, \ get_coll_i18nname, \ collection_i18nname_cache, \ collection_restricted_p _ = gettext_set_language(ln) # stem search units. remove those with field # TODO: search in hosted collection names too # TODO: ignore unattached trees # TODO: use synonyms if f or (CFG_WEBSEARCH_COLLECTION_NAMES_SEARCH < 0) or \ (CFG_WEBSEARCH_COLLECTION_NAMES_SEARCH == 0 and cc != CFG_SITE_NAME): return (0, '') words = [ stem(unit[1], ln) for unit in search_units if unit[2] in ('', 'collection') ] # Stemming if not words: return (0, '') permitted_restricted_collections = get_permitted_restricted_collections( user_info) cache = self.get_data_cache() matching_collections = {} for word in words: if CFG_CERN_SITE and word == 'cern': # This keyword is useless here... continue colls = cache.get(word.lower(), []) for coll in colls: if collection_restricted_p(coll) and \ not coll in permitted_restricted_collections: # Skip restricted collection user do not have access continue if not matching_collections.has_key(coll): matching_collections[coll] = 0 matching_collections[coll] += 1 matching_collections_sorted = sorted(matching_collections.iteritems(), key=lambda (k, v): (v, k), reverse=True) if not matching_collections_sorted: return (0, '') matching_collections_names = [(get_coll_i18nname(coll, ln, False), CFG_SITE_URL + '/collection/' + urllib.quote(coll, safe='') + '?ln=en') \ for coll, score in matching_collections_sorted] best_score = matching_collections_sorted[0][1] best_coll_words = whitespace_re.split( matching_collections_sorted[0][0]) relevance = min( 100, max(0, (100 * float(2 * best_score) / float(len(best_coll_words) + len(words)) - 10))) if (('submit' in p.lower()) or (_('submit') in p.lower())) and \ not (('submit' in best_coll_words) or (_('submit') in best_coll_words)): # User is probably looking for a submission. Decrease relevance relevance = max(0, relevance - 30) return (relevance, self.display_answer_helper(matching_collections_names, ln))
def _search_results_header(self, number_of_records, current_page, records_per_page, language, output_format): """Returns header of the search results""" _ = gettext_set_language(language) first_page_button = self._build_navigation_image( "buttonGoToFirstPage", "sb.gif", _("begin")) previous_page_button = self._build_navigation_image( "buttonGoToPreviousPage", "sp.gif", _("previous")) next_page_button = self._build_navigation_image( "buttonGoToNextPage", "sn.gif", _("next")) #for now we don't have last page button. last_page_button = "" #self._build_navigation_image("buttonGoToLastPage", "se.gif", _("end")) first_record_on_page = (current_page - 1) * records_per_page + 1 last_record_on_page = first_record_on_page + records_per_page - 1 if last_record_on_page > number_of_records: last_record_on_page = number_of_records last_page_number = number_of_records / records_per_page + 1 if current_page == 1: previous_page_button = "" if current_page < 2: first_page_button = "" if current_page == last_page_number: next_page_button = "" last_page_button = "" user_warning = "" if number_of_records > CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING: user_warning = """<div class="clean-error">%(warning_msg)s</div> """ % { "warning_msg": "Due to the amount of records to be modified, you need 'superadmin' rights to send the modifications. If it is not the case, your changes will be saved once you click the 'Apply Changes' button and you will be able to contact the admin to apply them" } header = """ %(user_warning)s <table class="searchresultsbox"> <tr><td class="searchresultsboxheader"> <strong>%(number_of_records)s</strong> %(text_records_found)s %(first_page_button)s %(previous_page_button)s %(first_record_on_page)s - %(last_record_on_page)s %(next_page_button)s %(last_page_button)s </td> <td class="searchresultsboxheader" style="text-align: right;"> Output format: <select name="view_format" onchange="onSelectOutputFormatChange(this.value)"> <option value="Marc" %(marc_selected)s>MARC</option> <option value="HTML Brief" %(brief_selected)s>HTML Brief</option> </select> </td> </tr> </table> """ % { "user_warning": user_warning, "number_of_records": number_of_records, "text_records_found": _("records found"), "first_page_button": first_page_button, "previous_page_button": previous_page_button, "next_page_button": next_page_button, "last_page_button": last_page_button, "first_record_on_page": first_record_on_page, "last_record_on_page": last_record_on_page, "marc_selected": output_format == "hm" and "SELECTED" or "", "brief_selected": output_format == "hb" and "SELECTED" or "" } return header
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_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 #display_comment_rounds = [cmtgrp for cmtgrp in argd['cmtgrp'] if cmtgrp.isdigit() or cmtgrp == "all" or cmtgrp == "-1"] display_comment_rounds = argd['cmtgrp'] check_warnings = [] (ok, problem) = check_recID_is_in_range(self.recid, check_warnings, argd['ln']) if ok: (body, errors, warnings) = perform_request_display_comments_or_remarks( req=req, recID=self.recid, display_order=argd['do'], display_since=argd['ds'], nb_per_page=argd['nb'], page=argd['p'], ln=argd['ln'], voted=argd['voted'], reported=argd['reported'], subscribed=argd['subscribed'], reviews=self.discussion, uid=uid, can_send_comments=can_send_comments, can_attach_files=can_attach_files, user_is_subscribed_to_discussion= user_is_subscribed_to_discussion, user_can_unsubscribe_from_discussion= user_can_unsubscribe_from_discussion, display_comment_rounds=display_comment_rounds) unordered_tabs = get_detailed_page_tabs(get_colID( guess_primary_collection_of_a_record(self.recid)), self.recid, ln=argd['ln']) ordered_tabs_id = [(tab_id, values['order']) for (tab_id, values) in unordered_tabs.iteritems()] ordered_tabs_id.sort(lambda x, y: cmp(x[1], y[1])) link_ln = '' if argd['ln'] != CFG_SITE_LANG: link_ln = '?ln=%s' % argd['ln'] tabs = [(unordered_tabs[tab_id]['label'], \ '%s/record/%s/%s%s' % (CFG_SITE_URL, self.recid, tab_id, link_ln), \ tab_id in ['comments', 'reviews'], unordered_tabs[tab_id]['enabled']) \ for (tab_id, order) in ordered_tabs_id if unordered_tabs[tab_id]['visible'] == True] top = webstyle_templates.detailed_record_container_top( self.recid, tabs, argd['ln']) bottom = webstyle_templates.detailed_record_container_bottom( self.recid, tabs, argd['ln']) title, description, keywords = websearch_templates.tmpl_record_page_header_content( req, self.recid, argd['ln']) navtrail = create_navtrail_links( cc=guess_primary_collection_of_a_record(self.recid), ln=argd['ln']) # Infoscience modification : # Custom navtrail presentation navtrail += '<li><a href="%s/record/%s?ln=%s">%s</a></li>' % ( CFG_SITE_URL, self.recid, argd['ln'], title) navtrail += '<li class="last">%s</li>' % ( self.discussion == 1 and _("Reviews") or _("Comments")) mathjaxheader = '' if CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS: mathjaxheader = """<script src='/MathJax/MathJax.js' type='text/javascript'></script>""" jqueryheader = ''' <script src="%(CFG_SITE_URL)s/js/jquery.min.js" type="text/javascript" language="javascript"></script> <script src="%(CFG_SITE_URL)s/js/jquery.MultiFile.pack.js" type="text/javascript" language="javascript"></script> ''' % { 'CFG_SITE_URL': CFG_SITE_URL } return pageheaderonly(title=title, navtrail=navtrail, uid=uid, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', # Infoscience modification : # Added user_info to search templates generator navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(user_info, '', argd['ln']) + \ top + body + bottom + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(lastupdated=__lastupdated__, language=argd['ln'], req=req) else: return page(title=_("Record Not Found"), body=problem, uid=uid, verbose=1, req=req, language=argd['ln'], warnings=check_warnings, errors=[], navmenuid='search')
def page_contents(self, language, collections): """Returns HTML representing the MultiEdit page""" _ = gettext_set_language(language) page_html = """\ <div class="pagebody"> <input type="hidden" value="%(language)s" id="language"> <table width="100%%" cellspacing="6" border="0"> <tr> <td> <b>%(text_choose_search_criteria)s</b> %(text_search_criteria_explanation)s </td> </tr> <tr> <td> <div class="boxContainer"> <div class="boxleft"> <b>%(text_search_criteria)s:</b> </div> <div class="boxleft_2"> <input type="text" placeholder='Use default search engine syntax' id="textBoxSearchCriteria" size="60"> <br /> </div> </div> <div class="boxContainer"> <div class="boxleft"> <b>%(text_filter_collection)s: </b> </div> <div class="boxleft_2"> %(collections)s <br /> </div> </div> <div class="boxContainer"> <div class="boxleft"> <b>%(text_output_tags)s:</b> </div> <div class="boxleft_2"> <div><input class="inputValueGrey" type="text" id="textBoxOutputTags" value="All tags" size="28"> <i>Ex. 100, 700</i><br/></div> </div> </div> <div class="boxContainer"> <div class="boxleft"> <input id="buttonTestSearch" value="%(text_test_search)s" type="submit" class="formbutton"></button> </div> </div> </td> </tr> <tr/> <tr/> <tr> <td align="center"> %(actions_definition_html)s </td> </tr> <tr> <td> <div class="boxContainer"> <div class="boxleft"> <input id="buttonPreviewResults" value="%(text_preview_results)s" type="button" class="formbutton"></button> </div> <div class="boxleft_2"> <input id="buttonSubmitChanges" value="%(text_submit_changes)s" type="button" class="formbutton"></button> </div> </div> </td> </tr> </table> <br/> <div id="info_area"></div> <div id="preview_area"></div> </div> """ % { "language": language, "text_test_search": _("Search"), "text_next_step": _("Next Step"), "text_search_criteria": _("Search criteria"), "text_output_tags": _("Output tags"), "text_filter_collection": _("Filter collection"), "text_choose_search_criteria": _("1. Choose search criteria"), "text_search_criteria_explanation": _("""Specify the criteria you'd like to use for filtering records that will be changed. Use "Search" to see which records would have been filtered using these criteria.""" ), "actions_definition_html": self._get_actions_definition_html(language), "text_preview_results": _("Preview results"), "text_submit_changes": _("Apply changes"), "collections": self._get_collections(collections), } return page_html
def get_label(self, ln=CFG_SITE_LANG): "Return label for the list of answers" _ = gettext_set_language(ln) return _("Looking for a particular collection? Try:")
def format_element(bfo, number_of_featured_articles="1", number_of_articles_with_image="3", new_articles_first='yes', image_px_width="300", small_image_px_width="200", subject_to_css_class_kb="WebJournalSubject2CSSClass", link_image_to_article='yes', image_alignment='left'): """ Creates an overview of all the articles of a certain category in one specific issue. Note the following: <ul> <li>The element consider only the latest issue: when viewing archives of your journal, readers will see the newest articles of the latest issue, not the ones of the issue they are looking at</li> <li>This is not an index of the articles of the latest issue: it display only <b>new</b> articles, that is articles that have never appeared in a previous issue</li> <li>This element produces a table-based layout, in order to have a more or less readable HTML alert when sent some Email clients (Outlook 2007)</li> <li>When producing the HTML output of images, this element tries to insert the width and height attributes to the img tag: this is necessary in order to produce nice HTML alerts. This dimension therefore overrides any dimension defined in the CSS. The Python Image Library (PIL) should be installed for this element to recognize the size of images.</li> </ul> @param number_of_featured_articles: the max number of records with emphasized title @param number_of_articles_with_image: the max number of records for which their image is displayed @param new_articles_first: if 'yes', display new articles before other articles @param image_px_width: (integer) width of first image featured on this page @param small_image_px_width: (integer) width of small images featured on this page @param subject_to_css_class_kb: knowledge base that maps 595__a to a CSS class @param link_image_to_article: if 'yes', link image (if any) to article @param image_alignment: 'left', 'center' or 'right'. To help rendering in Outlook. """ args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] this_issue_number = args["issue"] category_name = args["category"] verbose = args["verbose"] ln = bfo.lang _ = gettext_set_language(ln) if image_px_width.isdigit(): image_px_width = int(image_px_width) else: image_px_width = None if small_image_px_width.isdigit(): small_image_px_width = int(small_image_px_width) else: small_image_px_width = None # We want to put emphasis on the n first articles (which are not # new) if number_of_featured_articles.isdigit(): number_of_featured_articles = int(number_of_featured_articles) else: number_of_featured_articles = 0 # Only n first articles will display images if number_of_articles_with_image.isdigit(): number_of_articles_with_image = int(number_of_articles_with_image) else: number_of_articles_with_image = 0 # Help image alignement without CSS, to have better rendering in Outlook img_align = '' if image_alignment: img_align = 'align="%s"' % image_alignment # Try to get the page from cache. Only if issue is older or equal # to latest release. latest_released_issue = get_current_issue(ln, journal_name) if verbose == 0 and not issue_is_later_than(this_issue_number, latest_released_issue): cached_html = get_index_page_from_cache(journal_name, category_name, this_issue_number, ln) if cached_html: return cached_html out = '<table border="0" cellpadding="0" cellspacing="0">' # Get the id list ordered_articles = get_journal_articles(journal_name, this_issue_number, category_name, newest_first=new_articles_first.lower() == 'yes') new_articles_only = False if ordered_articles.keys() and max(ordered_articles.keys()) < 0: # If there are only new articles, don't bother marking them as # new new_articles_only = True order_numbers = ordered_articles.keys() order_numbers.sort() img_css_class = "featuredImageScale" for order_number in order_numbers: for article_id in ordered_articles[order_number]: # A record is considered as new if its position is # negative and there are some non-new articles article_is_new = (order_number < 0 and not new_articles_only) temp_rec = BibFormatObject(article_id) title = '' if ln == "fr": title = temp_rec.field('246_1a') if title == '': title = temp_rec.field('245__a') else: title = temp_rec.field('245__a') if title == '': title = temp_rec.field('246_1a') # Get CSS class (if relevant) notes = temp_rec.fields('595__a') css_classes = [temp_rec.kb(subject_to_css_class_kb, note, None) \ for note in notes] css_classes = [css_class for css_class in css_classes \ if css_class is not None] if article_is_new: css_classes.append('new') # Maybe we want to force image to appear? display_image_on_index = False if 'display_image_on_index' in notes: display_image_on_index = True # Build generic link to this article article_link = make_journal_url(bfo.user_info['uri'], {'recid':str(article_id), 'ln': bfo.lang}) # Build the "more" link more_link = '''<a class="readMore" title="link to the article" href="%s"> >> </a> ''' % (article_link) # If we should display an image along with the text, # prepare it here img = '' if (number_of_articles_with_image > 0 and \ not article_is_new) or display_image_on_index: img = _get_feature_image(temp_rec, ln) if img != "": # Now we will try to identify image size in order # to resize it in the HTML for a nicer rendering # of the HTML alert in email clients (Outlook wants # both height and width) img_width = None img_height = None small_img_width = None small_img_height = None width_and_height = '' if PIL_imported: try: local_img = os.path.join(CFG_TMPDIR, 'webjournal_' + \ ''.join([char for char in img \ if char.isalnum()])) if len(local_img) > 255: # Shorten to 255 chars local_img = local_img[0:100] + '_' + local_img[156:] if not os.path.exists(local_img): # Too bad, must download entire image for PIL content_type = get_content_type(img) if 'image' in content_type: (local_img, headers) = urllib.urlretrieve(img, local_img) img_file = Image.open(local_img) # IOError if not readable image else: raise IOError('Not an image') else: img_file = Image.open(local_img) # IOError if not readable image except IOError, e: pass else: orig_img_width = img_file.size[0] orig_img_height = img_file.size[1] # Then scale according to user-defined width ## First image ratio = float(orig_img_width) / image_px_width img_width = image_px_width img_height = int(orig_img_height / ratio) ## Other smaller images ratio = float(orig_img_width) / small_image_px_width small_img_width = small_image_px_width small_img_height = int(orig_img_height / ratio) # Note that we cannot reuse the nice phl, ph and # phr classes to put a frame around the image: # this is not supported in Outlook 2007 when HTML # alert is sent. if not img_css_class == "featuredImageScale": # Not first image: display smaller img_width = small_img_width img_height = small_img_height if img_width and img_height: width_and_height = 'width="%i" height="%i"' % \ (img_width, img_height) img = '<img alt="" class="%s" src="%s" %s %s/>' % \ (img_css_class, img, img_align, width_and_height) number_of_articles_with_image -= 1 # Next images will be displayed smaller img_css_class = "featuredImageScaleSmall" # Determine size of the title header_tag_size = '3' if number_of_featured_articles > 0 and \ not article_is_new: # n first articles are especially featured header_tag_size = '2' number_of_featured_articles -= 1 # Finally create the output. Two different outputs # depending on if we have text to display or not text = '' if not article_is_new: text = _get_feature_text(temp_rec, ln) # Link image to article if wanted if link_image_to_article.lower() == 'yes': img = create_html_link(urlbase=article_link, link_label=img, urlargd={}) if text != '': out += ''' <tr><td class="article"> <h%(header_tag_size)s class="%(css_classes)s articleTitle" style="clear:both;"> <a title="link to the article" href="%(article_link)s">%(title)s</a> </h%(header_tag_size)s> <div class="articleBody"> %(img)s %(text)s %(more_link)s </div> </td></tr> ''' % {'article_link': article_link, 'title': title, 'img': img, 'text': text, 'more_link': more_link, 'css_classes': ' '.join(css_classes), 'header_tag_size': header_tag_size} else: out += ''' <tr><td class="article"> <h%(header_tag_size)s class="%(css_classes)s articleTitle" style="clear:both;"> <a title="link to the article" href="%(article_link)s">%(title)s</a> %(more_link)s </h%(header_tag_size)s> %(img)s </td></tr> ''' % {'article_link': article_link, 'title': title, 'more_link': more_link, 'img': img, 'css_classes': ' '.join(css_classes), 'header_tag_size': header_tag_size}
def _get_actions_definition_html(self, language): """Returns the html for definition of actions""" _ = gettext_set_language(language) html = """ <!-- Area for displaying actions to the users --> <table id="actionsDisplayArea" width="100%%" cellspacing="0" > <col class="colDeleteButton"/> <col class="colFieldTag"/> <col class="colDeleteButton"/> <col class="colSubfieldCode"/> <col class="colActionType"/> <col/> <col class="colAddButton"/> <tbody><tr class="header"><td colspan="7"> <b>%(text_define_changes)s</b> %(text_define_changes_explanation)s </td><tr></tbody> <tbody class="lastRow" valign="middle"><tr><td colspan="7" align="left"> <img src="%(site_url)s/img/add.png" class="buttonNewField" alt="Add new"/> <span class="buttonNewField linkButton">%(text_define_field)s</span> </td></tr></tbody> </table> <!-- Templates for displaying of actions --> <table id="displayTemplates" width="100%%" cellspacing="0"> <col class="colDeleteButton"/> <col class="colFieldTag"/> <col class="colDeleteButton"/> <col class="colSubfieldCode"/> <col class="colActionType"/> <col/> <col class="colAddButton"/> <!-- Templates for fields --> <tbody class="templateNewField"> <tr class="tagTableRow"> <td/> <td>%(text_field)s</td> <td /><td colspan="4" /> </tr> <tr class="tagTableRow"> <td /> <td> <input class="textBoxFieldTag txtTag" type="Text" maxlength="3" /><input class="textBoxFieldInd1 txtInd" type="Text" maxlength="1" /><input class="textBoxFieldInd2 txtInd" type="text" maxlength="1" /> </td> <td /> <td /> <td> <select class="fieldActionType" onchange="onFieldActionTypeChange(this);"> <option value="%(text_select_action)s">%(text_select_action)s</option> <option value="0">%(text_add_field)s</option> <option value="1">%(text_delete_field)s</option> <option value="2">%(text_update_field)s</option> </select> </td> <td/> <td/> </tr> <tr class="tagTableRow"><td /><td /><td /><td /><td> </td><td/><td/></tr> </tbody> <tr class="tagTableRow"><td /><td /><td> </td><td /><td colspan="2"> <input value="%(text_save)s" type="button" id="buttonSaveNewField" class="formbutton"/> <input value="%(text_cancel)s" type="button" id="buttonCancelNewField" class="formbutton"/> </td><td/></tr> <tbody class="templateDisplayField" valign="middle"> <tr class="tagTableRow"> <td><img src="%(site_url)s/img/delete.png" class="buttonDeleteField" alt="Delete"/></td> <td> <strong> <span class="tag"></span><span class="ind1"></span><span class="ind2"></span> </strong> </td> <td /> <td /> <td><span class="action colActionType"></span></td> <td class="conditionParametersDisplay"> <span class="conditionParametersDisplay"><strong> %(text_with_condition)s</strong></span> <input id="textBoxConditionSubfieldDisplay" class="txtValue textBoxConditionSubfield conditionSubfieldParameters" type="text" maxlength="1"/> <span class="conditionExact conditionParametersDisplay"></span> <input id="textBoxConditionFieldDisplay" class="txtValue textBoxCondition conditionParametersDisplay" type="text"/> </td> <td> <img src="%(site_url)s/img/add.png" class="buttonNewSubfield" alt="Add new"/> <span class="buttonNewSubfield linkButton">%(text_define_subfield)s</span> </td> <td /> </tr> <tr class="conditionParameters"> <td /> <td /> <td /> <td /><td colspan="3">%(text_condition_subfield_delete)s <input id="textBoxConditionSubfield" class="txtValue textBoxConditionSubfield" type="text" maxlength="1"/> <select class="selectConditionExactMatch"> <option value="0">%(text_equal_to)s</option> <option value="1">%(text_contains)s</option> <option value="2">%(text_not_exists)s</option> </select> <input id="textBoxCondition" class="txtValue textBoxCondition" type="text" value="%(text_condition)s"/> </td> </tr> <tr class="conditionActOnFields"> <td /><td /><td /><td /> <td colspan="3"> <span class="actOnFieldLink" id="actOnFieldsDelete"><u>%(text_filter_fields)s</u></span> </td> </tr> <tr class="conditionActOnFieldsSave"> <td /><td /><td /><td /><td> <input value="%(text_save)s" type="button" id="buttonSaveNewFieldCondition" class="formbutton"/> <input value="%(text_cancel)s" type="button" id="buttonCancelFieldCondition" class="formbutton"> </td> </tr> </tbody> <!-- Templates for subfields --> <tbody class="templateDisplaySubfield"> <tr class="subfieldTableRow"> <td /> <td /> <td><img src="%(site_url)s/img/delete.png" class="buttonDeleteSubfield" alt="Delete" /></td> <td>$$<span class="subfieldCode">a</span></td> <td> <span class="action colActionType">%(text_replace_text)s</span> </td> <td> <input id="textBoxValueDisplay" class="txtValue textBoxValue valueParameters" type="text"/> <span class="newValueParameters"><strong> %(text_with)s </strong></span> <input id="textBoxNewValueDisplay" class="txtValue textBoxNewValue newValueParameters" type="text" value="%(text_new_value)s"/> <span class="conditionParameters"><strong> %(text_with_condition)s</strong></span> <input id="textBoxConditionSubfieldDisplay" class="txtValue textBoxConditionSubfield conditionSubfieldParameters" type="text" maxlength="1"/> <span class="conditionExact conditionParameters"></span> <input id="textBoxConditionDisplay" class="txtValue textBoxCondition conditionParameters" type="text"/> </td> <td/> </tr> </tbody> <tbody class="templateNewSubfield"> <tr> <td /> <td /> <td /> <td><input class="txtSubfieldCode textBoxSubfieldCode" type="text" maxlength="1"/></td> <td> <select class="subfieldActionType"> <option value="0">%(text_add_subfield)s</option> <option value="1">%(text_delete_subfield)s</option> <option value="2">%(text_replace_content)s</option> <option value="3">%(text_replace_text)s</option> </select> </td> </tr> <tr class="valueParameters"> <td /><td /><td /><td /> <td colspan="3"> <input id="textBoxValue" class="txtValue textBoxValue" type="text" placeholder="%(text_value)s"/> </td> </tr> <tr class="newValueParameters"> <td /><td /><td /><td /> <td colspan="3"> <input id="textBoxNewValue" class="txtValue textBoxNewValue" type="text" placeholder="%(text_new_value)s"/> </td> </tr> <tr class="conditionParameters"> <td /> <td /> <td /> <td /><td colspan="3">%(text_condition_subfield)s <input class="txtValue textBoxConditionSubfield" type="text" maxlength="1"/> <select class="selectConditionExactMatch"> <option value="0">%(text_equal_to)s</option> <option value="1">%(text_contains)s</option> <option value="2">%(text_not_exists)s</option> </select> <input id="textBoxCondition" class="txtValue textBoxCondition" type="text" value="%(text_condition)s"/> </td> </tr> <tr class="conditionActOnFields"> <td /><td /><td /><td /> <td colspan="3"> <span class="actOnFieldLink" id="actOnFields"><u>%(text_filter_fields)s</u></span> </td> </tr> <tr> <td /><td /><td /><td /><td> <input value="%(text_save)s" type="button" id="buttonSaveNewSubfield" class="formbutton"/> <input value="%(text_cancel)s" type="button" id="buttonCancelNewSubfield" class="formbutton"> </td> </tr> </tbody> <tbody class="templateMsg"> <tr> <td colspan="100"><span class="msg"></span></td> <td/> <td/> <td/> <td/> <td/> <td/> </tr> </tbody> </table> """ % { "site_url": CFG_SITE_URL, "text_define_changes": _("2. Define changes"), "text_define_changes_explanation": _("Specify fields and their subfields that should be changed in every record matching the search criteria." ), "text_define_field": _("Define new field action"), "text_define_subfield": _("Define new subfield action"), "text_field": _("Field"), "text_select_action": _("Select action"), "text_add_field": _("Add field"), "text_delete_field": _("Delete field"), "text_update_field": _("Update field"), "text_add_subfield": _("Add subfield"), "text_delete_subfield": _("Delete subfield"), "text_save": _("Save"), "text_cancel": _("Cancel"), "text_replace_text": _("Replace substring"), "text_replace_content": _("Replace full content"), "text_with": _("with"), "text_with_condition": _("when subfield $$"), "text_new_value": _("new value"), "text_equal_to": _("is equal to"), "text_contains": _("contains"), "text_not_exists": _("does not exist"), "text_condition": _("condition"), "text_condition_subfield": _("when other subfield"), "text_condition_subfield_delete": _("when subfield"), "text_filter_fields": _("Apply only to specific field instances"), "text_value": _("value") } return html
'doctype': 'DEMOJRN', 'act': 'MBI', 'categ': '*' }), ('submit_DEMOJRN_*', 'cfgwebjournal', { 'name': 'AtlantisTimes', 'with_editor_rights': 'no' }), ('atlantiseditor', 'cfgwebjournal', { 'name': 'AtlantisTimes', 'with_editor_rights': 'yes' }), ('referee_DEMOBOO_*', 'runbatchuploader', { 'collection': 'Books' }), ('poetrycommentreader', 'viewcomment', { 'collection': 'Poetry' })) _ = gettext_set_language(CFG_SITE_LANG) # Activities (i.e. actions) for which exists an administrative web interface. CFG_ACC_ACTIVITIES_URLS = { 'runbibedit': (_("Run Record Editor"), "%s/record/edit/?ln=%%s" % CFG_SITE_URL), 'runbibeditmulti': (_("Run Multi-Record Editor"), "%s/record/multiedit/?ln=%%s" % CFG_SITE_URL), 'runbibdocfile': (_("Run Document File Manager"), "%s/submit/managedocfiles?ln=%%s" % CFG_SITE_URL), 'runbibmerge': (_("Run Record Merger"), "%s/record/merge/?ln=%%s" % CFG_SITE_URL), 'runbibswordclient': (_("Run BibSword client"), "%s/bibsword/?ln=%%s" % CFG_SITE_URL), 'cfgbibknowledge': (_("Configure BibKnowledge"), "%s/kb?ln=%%s" % CFG_SITE_URL),
def format_element(bfo, separator='<br/>'): """ Display article body @param separator: separator between each body """ ln = bfo.lang _ = gettext_set_language(ln) if ln == "fr": article = bfo.fields('590__b') if not article or \ (len(article) == 1 and \ (article[0].strip() in ['', '<br />', '<!--HTML--><br />'])): article = bfo.fields('520__b') else: article = bfo.fields('520__b') if not article or \ (len(article) == 1 and \ (article[0].strip() in ['', '<br />', '<!--HTML--><br />'])): article = bfo.fields('590__b') if not CFG_CERN_SITE or \ not bfo.field('980__a').startswith('BULLETIN'): return separator.join(article) ################################################################ # CERN Bulletin-specific code # ################################################################ # We need a compatibility layer for old CERN Bulletin # articles. Identify them and process them if needed. is_old_cern_bulletin_article = False if bfo.field('980__a').startswith('BULLETIN'): try: year = int(bfo.fields('260__c')[0]) except IndexError: year = 2000 if year < 2009 or \ (bfo.field('980__a').startswith('BULLETINSTAFF') and \ ("CERN EDS" in bfo.field('595__a'))): is_old_cern_bulletin_article = True header_out = '' if not is_old_cern_bulletin_article: # Return the same as any other journal article return separator.join(article) # Old CERN articles if year < 2007 or bfo.field('980__a').startswith('BULLETINSTAFF'): # Really old CERN articles if len(article) > 0: # CERN-only: old CERN Bulletin articles return __backward_compatible_HTML(article[0]) + \ (bfo.field('980__a').startswith('BULLETINSTAFF') and \ ('<br/><br/>' + bfe_fulltext.format_element(bfo, style="", show_icons='yes')) \ or '') else: return '' # Not-so-old CERN articles follow: # 2. prepare regex's for the elements #===================================================== from invenio.webjournal_utils import \ image_pattern, \ para_pattern, \ header_pattern page_elements = {} # 3. get the header (either from marc xml or regex) #===================================================== if bfo.lang == "fr": header = bfo.field('590__a') if header == '': header = bfo.field('520__a') else: header = bfo.field('520__a') if header == '': header = bfo.field('590__a') if not header: try: header_obj = re.search(header_pattern, article[0]) header_text = header_obj.group("header") except: header_text = "" else: header_text = header washer = HTMLWasher() header_text_clean = washer.wash(html_buffer=header_text, allowed_tag_whitelist=['a'], allowed_attribute_whitelist=['href']) header_out = '<p class="articleHeader">' + header_text_clean + '</p>' # strip out all empty p tags and the header try: article = article[0].replace("<p/>", "") article = article.replace(header_text, "") article = article.replace(header_text_clean, "") except IndexError: article = "" image_iter = image_pattern.finditer(article) difference_from_original = 0 for image in image_iter: page_elements[image.start()] = {"link" : image.group("hyperlink"), "image" : image.group("image"), "caption" : image.group("caption")} # make sure we delete the image from the article (else might be used twice) start_index = image.span()[0] - difference_from_original end_index = image.span()[1] - difference_from_original article = article.replace(article[start_index:end_index], "") difference_from_original += image.span()[1] - image.span()[0] # replace <center> by <p><center> article = article.replace("<center>", "<p><center>") article = article.replace("</center>", "</center></p>") para_iter = para_pattern.finditer(article) for paragraph in para_iter: page_elements[paragraph.start()] = paragraph.group("paragraph") # TODO: find a way to do this inline in the dict ordered_keys = page_elements.keys() ordered_keys.sort() article_out = "" left_right_lever = True did_you_know_box = False for key in ordered_keys: if type(page_elements[key]) == types.DictType: if left_right_lever == True: article_out += '<div class="phrwithcaption"><div class="imageScale">' else: article_out += '<div class="phlwithcaption"><div class="imageScale">' if page_elements[key]["link"] != None: article_out += '<a href="' + page_elements[key]["link"] + '">' article_out += '<img class="featureImageScaleHolder" src="' + \ page_elements[key]["image"] + '" border="0" />' + \ '</a>' + \ '</div>' if page_elements[key]["caption"] != None: article_out += '<p>' + page_elements[key]["caption"] + \ '</p>' article_out += '</div>' elif type(page_elements[key]) == types.StringType: left_right_lever = not left_right_lever if (page_elements[key].lower().find("did you know") != -1) or \ (page_elements[key].lower().find("le saviez-vous ?") != -1): did_you_know_box = True continue if did_you_know_box == True: did_you_know_box = False article_out += __did_you_know_box(page_elements[key], left_right_lever, bfo.lang) continue article_out += '<p>' article_out += page_elements[key] article_out += '</p>' return header_out + article_out
def direct(self, req, form): """Directly redirected to an initialized submission.""" args = wash_urlargd(form, {'sub': (str, ''), 'access': (str, '')}) sub = args['sub'] access = args['access'] ln = args['ln'] _ = gettext_set_language(ln) uid = getUid(req) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "direct", navmenuid='submit', text=_("Submissions are not available")) myQuery = req.args if not sub: return warning_page(_("Sorry, 'sub' parameter missing..."), req, ln=ln) res = run_sql( "SELECT docname,actname FROM sbmIMPLEMENT WHERE subname=%s", (sub, )) if not res: return warning_page(_("Sorry. Cannot analyse parameter"), req, ln=ln) else: # get document type doctype = res[0][0] # get action name action = res[0][1] # get category categ = req.form.get('combo%s' % doctype, '*') # retrieve other parameter values params = dict(form) # Check if user is authorized, based on doctype/action/categ, # in order to give guest users a chance to log in if needed: (auth_code, auth_message) = acc_authorize_action( req, 'submit', authorized_if_no_roles=not isGuestUser(uid), verbose=0, doctype=doctype, act=action, categ=categ) if not auth_code == 0 and isGuestUser(uid): # Propose to login redirection_params = params redirection_params[ 'referer'] = CFG_SITE_SECURE_URL + req.unparsed_uri return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd(redirection_params, {})), norobot=True) # else: continue, and let main interface control the access # find existing access number if not access: # create 'unique' access number pid = os.getpid() now = time.time() access = "%i_%s" % (now, pid) # retrieve 'dir' value res = run_sql("SELECT dir FROM sbmACTION WHERE sactname=%s", (action, )) dir = res[0][0] mainmenu = req.headers_in.get('referer') params['access'] = access params['act'] = action params['doctype'] = doctype params['startPg'] = '1' params['mainmenu'] = mainmenu params['ln'] = ln params['indir'] = dir url = "%s/submit?%s" % (CFG_SITE_SECURE_URL, urlencode(params)) redirect_to_url(req, url)
def format_element( bfo, limit, separator='; ', extension='[...]', print_links="yes", print_affiliations='no', affiliation_prefix=' (', affiliation_suffix=')', print_affiliation_first='no', interactive="no", highlight="no", affiliations_separator=" ; ", name_last_first="yes", collaboration="yes", id_links="no", markup="html", link_extension="no", ): """ Prints the list of authors of a record. @param limit: the maximum number of authors to display @param separator: the separator between authors. @param extension: a text printed if more authors than 'limit' exist @param print_links: if yes, prints the authors as HTML link to their publications @param print_affiliations: if yes, make each author name followed by its affiliation @param affiliation_prefix: prefix printed before each affiliation @param affiliation_suffix: suffix printed after each affiliation @param print_affiliation_first: if 'yes', affiliation is printed before the author @param interactive: if yes, enable user to show/hide authors when there are too many (html + javascript) @param highlight: highlights authors corresponding to search query if set to 'yes' @param affiliations_separator: separates affiliation groups @param name_last_first: if yes (default) print last, first otherwise first last @param collaboration: if yes (default) uses collaboration name in place of long author list, if available @param id_links: if yes (default = no) prints link based on INSPIRE IDs if available - only used if print_links = yes @param markup: html (default) or latex controls small markup differences @param link_extension: if 'yes' link the extension to the detailed record page """ from urllib import quote from cgi import escape import re from invenio.config import CFG_BASE_URL, CFG_SITE_RECORD, CFG_SITE_URL #regex for parsing last and first names and initials re_last_first = re.compile( '^(?P<last>[^,]+)\s*,\s*(?P<first_names>[^\,]*)(?P<extension>\,?.*)$') re_initials = re.compile(r'(?P<initial>\w)(\w+|\.)\s*') re_coll = re.compile(r'\s*collaborations?', re.IGNORECASE) from invenio.messages import gettext_set_language _ = gettext_set_language(bfo.lang) # load the right message language bibrec_id = bfo.control_field("001") authors = [] authors = bfo.fields('100__', repeatable_subfields_p=True) authors.extend(bfo.fields('700__', repeatable_subfields_p=True)) # Keep real num of authorsfix + affiliations_separator.join(author['u']) + \ nb_authors = len(authors) # Limit num of authors, so that we do not process # the authors that will not be shown. This can only # be done in non-interactive mode, as interactive mode # allows to show all of them. if limit.isdigit() and nb_authors > int(limit) \ and interactive != "yes": if bfo.field('710g'): #check for colln note authors = authors[:1] else: authors = authors[:int(limit)] # Process authors to add link, affiliation and highlight for author in authors: if author.has_key('a'): author['a'] = author['a'][0] # There should not be if highlight == 'yes': from invenio import bibformat_utils author['a'] = bibformat_utils.highlight( author['a'], bfo.search_pattern) #check if we need to reverse last, first #we don't try to reverse it if it isn't stored with a comma. first_last_match = re_last_first.search(author['a']) author['display'] = author['a'] if name_last_first.lower() == "no": if first_last_match: author['display'] = first_last_match.group('first_names') + \ ' ' + \ first_last_match.group('last') + \ first_last_match.group('extension') #for latex we do initials only (asn assume first last) if markup == 'latex': if first_last_match: first = re_initials.sub('\g<initial>.~', \ first_last_match.group('first_names')) author['display'] = first + \ first_last_match.group('last') + \ first_last_match.group('extension') if print_links.lower() == "yes": # if there is an ID, search using that. id_link = '' if id_links == "yes" and author.has_key('i'): author['i'] = author['i'][0] #possible to have more IDs? id_link = '<a class="authoridlink" href="' + \ CFG_BASE_URL + \ '/search?' + \ 'ln=' + bfo.lang + \ '&p=100__i' + escape(':' + author['i']) + \ '+or+700__i' + escape(':' + author['i']) + \ '">' + escape("(ID Search)") + '</a> ' author['display'] = '<a class="authorlink" target="_blank" ' + \ 'href="' + \ CFG_SITE_URL + \ '/author/search?q=' + bibrec_id + ':' + \ quote(author['a']) + \ '&ln=' + bfo.lang + \ '">' + escape(author['display']) + '</a>' + \ id_link if print_affiliations == "yes": if author.has_key('e'): author['e'] = affiliation_prefix + \ affiliations_separator.join(author['e']) + \ affiliation_suffix if author.has_key('u'): author['ilink'] = [ '%s' % string.lstrip() for string in author['u'] ] author['u'] = affiliation_prefix + \ affiliations_separator.join(author['ilink']) + \ affiliation_suffix # # Consolidate repeated affiliations # last = '' authors.reverse() for author in authors: if not author.has_key('u'): author['u'] = '' #print 'this->'+ author['a']+'\n' if last == author['u']: author['u'] = '' else: last = author['u'] authors.reverse() # Flatten author instances if print_affiliations == 'yes': # 100__a (100__e) 700__a (100__e) (100__u) if print_affiliation_first.lower() != 'yes': authors = [author.get('display', '') + author.get('u', '') \ for author in authors] else: authors = [author.get('u', '') + author.get('display', '') \ for author in authors] else: authors = [author.get('display', '') for author in authors] # link the extension to detailed record if link_extension == 'yes' and interactive != 'yes': extension = '<a class="authorlink" href="' + \ CFG_BASE_URL + '/' + CFG_SITE_RECORD + '∕' + str(bfo.recID) + '">' + \ extension + '</a>' # Detect Collaborations: if collaboration == "yes": colls = bfo.fields("710__g") else: colls = [] if colls: short_coll = False colls = [re_coll.sub('', coll) for coll in colls] if print_links.lower() == "yes": colls = ['<a class="authorlink" href="' + \ CFG_BASE_URL + '/search' + \ '?p=' + quote(coll) + \ '&ln=' + bfo.lang + \ '&f=collaboration' + \ '">' + escape(coll) + '</a>' for coll in colls] coll_display = " and ".join(colls) if not coll_display.endswith("aboration"): coll_display += " Collaboration" if len(colls) > 1: coll_display += 's' if nb_authors > 1: if markup == 'latex': coll_display = authors[0] + extension + " [ " + \ coll_display + " ]" elif interactive == "yes": coll_display += " (" + authors[0] + " " extension += ")" else: #html coll_display += " (" + authors[0] + extension + ")" elif nb_authors == 1: short_coll = True if markup == 'latex': coll_display = authors[0] + " [ " + coll_display + " ]" else: #html coll_display += " (" + authors[0] + " for the collaboration)" elif nb_authors == 0: short_coll = True if markup == 'latex': coll_display = "[ " + coll_display + " ]" # Start outputting, depending on options and number of authors if colls and (interactive != "yes" or short_coll): return coll_display if limit.isdigit() and nb_authors > int(limit) and interactive != "yes": return separator.join(authors[:len(authors)]) + \ extension elif interactive == "yes" and ( (colls and not short_coll) or (limit.isdigit() and nb_authors > int(limit))): out = ''' <script> function toggle_authors_visibility(){ var more = document.getElementById('more'); var link = document.getElementById('link'); var extension = document.getElementById('extension'); if (more.style.display=='none'){ more.style.display = ''; extension.style.display = 'none'; link.innerHTML = "%(show_less)s" } else { more.style.display = 'none'; extension.style.display = ''; link.innerHTML = "%(show_more)s" } link.style.color = "rgb(204,0,0);" } function set_up(){ var extension = document.getElementById('extension'); extension.innerHTML = '%(extension)s'; toggle_authors_visibility(); } </script> ''' % { 'show_less': _("Hide"), 'show_more': _("Show all %i authors") % nb_authors, 'extension': extension } # out += '<a name="show_hide" />' if colls: show = coll_display more = separator + separator.join(authors[1:]) + ')' else: show = separator.join(authors[:int(limit)]) more = separator.join(authors[int(limit):len(authors)]) out += show out += ' <span id="more" style="">' + more + '</span>' out += ' <span id="extension"></span>' out += ' <small><i><a id="link" href="#"' + \ ' onclick="toggle_authors_visibility()" ' + \ ' style="color:rgb(204,0,0);"></a></i></small>' out += '<script>set_up()</script>' return out elif nb_authors > 0: return separator.join(authors)
def format_element(bfo): """ Prints the control number of an author authority record in HTML. By default prints brief version. @param brief: whether the 'brief' rather than the 'detailed' format @type brief: 'yes' or 'no' """ from invenio.messages import gettext_set_language _ = gettext_set_language(bfo.lang) # load the right message language control_nos = [d['a'] for d in bfo.fields('035__') if d.get('a')] control_nos.extend([d['a'] for d in bfo.fields('970__') if d.get('a')]) authority_type = [d.get('a') for d in bfo.fields('980__') if d.get('a') and d.get('a')!=authority_identifier] if authority_type and type(authority_type) is list: authority_type = authority_type[0] related_control_number_fields = ['510','970'] related_control_number_fields.extend(control_number_fields.get(authority_type,[])) control_nos_formatted = [] for control_no in control_nos: recIDs = get_dependent_records_for_control_no(control_no) count = len(recIDs) count_string = str(count) + " dependent records" from urllib import quote # if we have dependent records, provide a link to them if count: prefix_pattern = "<a href='" + CFG_SITE_URL + "%s" + "'>" postfix = "</a>" url_str = '' # we have multiple dependent records if count > 1: # joining control_nos might be more helpful for the user # than joining recIDs... or maybe not... parameters = [] for control_number_field in related_control_number_fields: parameters.append(control_number_field + ":" + control_no ) p_val = quote(" or ".join(parameters)) # include "&c=" parameter for bibliographic records # and one "&c=" parameter for authority records url_str = \ "/search" + \ "?p=" + p_val + \ "&c=" + quote(CFG_SITE_NAME) + \ "&c=" + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME + \ "&sc=1" + \ "&ln=" + bfo.lang # we have exactly one dependent record elif count == 1: url_str = "/record/" + str(recIDs[0]) prefix = prefix_pattern % (url_str) count_string = prefix + count_string + postfix #assemble the html and append to list html_str = control_no + " (" + count_string + ")" # check if there are more than one authority record with the same # control number. If so, warn the user about this inconsistency. # TODO: hide this warning from unauthorized users my_recIDs = get_low_level_recIDs_from_control_no(control_no) if len(my_recIDs) > 1: url_str = \ "/search" + \ "?p=" + CFG_BIBAUTHORITY_RECORD_CONTROL_NUMBER_FIELD + ":" + control_no + \ "&c=" + quote(CFG_SITE_NAME) + \ "&c=" + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME + \ "&sc=1" + \ "&ln=" + bfo.lang html_str += \ ' <span style="color:red">' + \ '(Warning, there is currently ' + \ '<a href="' + url_str + '">more than one authority record</a> ' + \ 'with this Control Number)' + \ '</span>' control_nos_formatted.append(html_str) title = "<strong>" + _("Control Number(s)") + "</strong>" if control_nos_formatted: content = "<ul><li>" + "</li><li> ".join(control_nos_formatted) + "</li></ul>" else: content = "<strong style='color:red'>Missing !</strong>" return "<p>" + title + ": " + content + "</p>"
def create_download_history_graph_and_box(id_bibrec, ln=CFG_SITE_LANG): """Create graph with citation history for record ID_BIBREC (into a temporary file) and return HTML box refering to that image. Called by Detailed record pages. Notes: if id_bibdoc=0 : its an oustide-stored document and it has no id_bibdoc --> only one line if len(id_bibdocs) <= cfg_id_bibdoc_id_bibrec draw one line per id_bibdoc if len(id_bibdocs) > cfg_id_bibdoc_id_bibrec draw only one line which hold simultaneously the downloads for all id_bibdoc Each time this function is called, all the images older than 10 minutes are deleted. """ _ = gettext_set_language(ln) out = "" # Prepare downloads history graph: if CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS: html_content = "" # remove images older than 10 minutes remove_old_img("download") # download count graph id_bibdocs = intbitset( run_sql( "select distinct id_bibdoc from rnkDOWNLOADS where id_bibrec=%s", (id_bibrec, ))) id_existing_bibdocs = intbitset( run_sql( "SELECT id_bibdoc FROM bibrec_bibdoc JOIN bibdoc ON id_bibdoc=id WHERE id_bibrec=%s AND status<>'DELETED'", (id_bibrec, ))) ## FIXME: when bibdocs are deleted we loose the stats. What shall we do with them? id_bibdocs &= id_existing_bibdocs history_analysis_results = () if not id_bibdocs: pass elif len( id_bibdocs) <= CFG_ID_BIBDOC_ID_BIBREC and 0 not in id_bibdocs: history_analysis_results = draw_downloads_statistics( id_bibrec, list(id_bibdocs)) else: history_analysis_results = draw_downloads_statistics(id_bibrec, []) if history_analysis_results and history_analysis_results[0]: if CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS == 2: graph_file_history = CFG_WEBDIR + "/img/" + history_analysis_results[ 0] html_content += """<tr><td valign=center align=center>%s</td>""" % open( graph_file_history).read() else: # gnuplot graph_file_history = CFG_SITE_URL + "/img/" + history_analysis_results[ 0] html_content += """<tr><td valign=center align=center><img src='%s'/></td>""" % graph_file_history file_to_close_history = history_analysis_results[1] if file_to_close_history: if os.path.exists(file_to_close_history): os.unlink(file_to_close_history) if html_content != "": out += """<br/><br/><table><tr><td class="blocknote"> %s</td></tr><tr><td> <table border="0" cellspacing="1" cellpadding="1">""" % _( "Download history:") out += html_content + "</table></td></tr></table>" if CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION: # do we show also user IP repartition? html_content = "" remove_old_img("download") #Users analysis graph ips = database_tuples_to_single_list( run_sql( "select client_host from rnkDOWNLOADS where id_bibrec=%s;" % id_bibrec)) if ips: users_analysis_results = create_users_analysis_graph( id_bibrec, ips) if users_analysis_results[0]: file_to_close_users = users_analysis_results[1] if CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION == 1: html_content += """<tr><td valign=center align=center><img src='%s/img/%s' align="center" alt=""></td>""" % ( CFG_SITE_URL, users_analysis_results[0]) elif CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION == 2: html_content += """<tr><td valign=center align=center>%s</td>""" % open( CFG_WEBDIR + "/img/" + users_analysis_results[0]).read() if file_to_close_users: if os.path.exists(file_to_close_users): os.unlink(file_to_close_users) if html_content != "": out += """<br/><br/><table><tr><td class="blocknote"> %s</td></tr><tr><td> <table border="0" cellspacing="1" cellpadding="1">""" % _( "Download user distribution:") out += html_content out += "</table></td></tr></table>" # return html code used by get_file or search_engine return out
def tmpl_upload_history(self, ln=CFG_SITE_LANG, upload_meta_list="", upload_doc_list=""): """Displays upload history of a given user""" _ = gettext_set_language(ln) body_content = "" body_content += "<h3> Metadata uploads </h3>" if not upload_meta_list: body_content += _("No metadata files have been uploaded yet.") body_content += "<br/>" else: body_content += """ <table border=0> <tr> <b> <th>%(txt1)s</th> <th>%(txt2)s</th> <th>%(txt3)s</th> <th>%(txt4)s</th> </b> </tr> """ % { 'txt1': _("Submit time"), 'txt2': _("File name"), 'txt3': _("Execution time"), 'txt4': _("Status") } for upload in upload_meta_list: color = "" if "ERROR" in upload[3]: color = "red" elif upload[3] == "WAITING": color = "yellow" elif upload[3] == "DONE": color = "green" body_content += """ <tr> <td style="text-align: center; vertical-align: middle; width: 220px;">%(submit_time)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;">%(file_name)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;">%(exec_time)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;"><span class="%(color)s">%(status)s</span></td> </tr> """ % { 'submit_time': upload[0], 'file_name': upload[1], 'exec_time': upload[2], 'color': color, 'status': upload[3] } body_content += "</table><br/>" body_content += "<h3> Document uploads </h3>" if not upload_doc_list: body_content += _("No document files have been uploaded yet.") body_content += "<br/>" else: body_content += """ <table border=0> <tr> <b> <th>%(txt1)s</th> <th>%(txt2)s</th> <th>%(txt3)s</th> <th>%(txt4)s</th> </b> </tr> """ % { 'txt1': _("Submit time"), 'txt2': _("File name"), 'txt3': _("Execution time"), 'txt4': _("Status") } for upload in upload_doc_list: color = "" if "ERROR" in upload[3]: color = "red" elif upload[3] == "WAITING": color = "yellow" elif upload[3] == "DONE": color = "green" body_content += """ <tr> <td style="text-align: center; vertical-align: middle; width: 220px;">%(submit_time)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;">%(file_name)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;">%(exec_time)s</td> <td style="text-align: center; vertical-align: middle; width: 220px;"><span class="%(color)s">%(status)s</span></td> </tr> """ % { 'submit_time': upload[0], 'file_name': upload[1], 'exec_time': upload[2], 'color': color, 'status': upload[3] } body_content += "</table>" return body_content
def format_element(bfo, limit, separator=' ; ', extension='[...]', print_links="yes", print_affiliations='no', affiliation_prefix=' (', affiliation_suffix=')', interactive="no", highlight="no", link_author_pages="no"): """ Prints the list of authors of a record. @param limit: the maximum number of authors to display @param separator: the separator between authors. @param extension: a text printed if more authors than 'limit' exist @param print_links: if yes, prints the authors as HTML link to their publications @param print_affiliations: if yes, make each author name followed by its affiliation @param affiliation_prefix: prefix printed before each affiliation @param affiliation_suffix: suffix printed after each affiliation @param interactive: if yes, enable user to show/hide authors when there are too many (html + javascript) @param highlight: highlights authors corresponding to search query if set to 'yes' """ _ = gettext_set_language(bfo.lang) # load the right message language authors = [] authors_1 = bfo.fields('100__') authors_2 = bfo.fields('700__') authors.extend(authors_1) authors.extend(authors_2) nb_authors = len(authors) bibrec_id = bfo.control_field("001") # Process authors to add link, highlight and format affiliation for author in authors: if author.has_key('a'): if highlight == 'yes': from invenio import bibformat_utils author['a'] = bibformat_utils.highlight( author['a'], bfo.search_pattern) if print_links.lower() == "yes": if link_author_pages == "no": author['a'] = '<a href="' + CFG_SITE_URL + \ '/search?f=author&p=' + quote(author['a']) + \ '&ln=' + bfo.lang + \ '">' + escape(author['a']) + '</a>' else: author['a'] = '<a rel="author" href="' + CFG_SITE_URL + \ '/author/' + quote(author['a']) + \ '?recid=' + bibrec_id + \ '&ln=' + bfo.lang + \ '">' + escape(author['a']) + '</a>' if author.has_key('u'): if print_affiliations == "yes": author['u'] = affiliation_prefix + author['u'] + \ affiliation_suffix # Flatten author instances if print_affiliations == 'yes': authors = [ author.get('a', '') + author.get('u', '') for author in authors ] else: authors = [author.get('a', '') for author in authors] if limit.isdigit() and nb_authors > int(limit) and interactive != "yes": return separator.join(authors[:int(limit)]) + extension elif limit.isdigit() and nb_authors > int(limit) and interactive == "yes": out = '<a name="show_hide" />' out += separator.join(authors[:int(limit)]) out += '<span id="more_%s" style="">' % bibrec_id + separator + \ separator.join(authors[int(limit):]) + '</span>' out += ' <span id="extension_%s"></span>' % bibrec_id out += ' <small><i><a id="link_%s" href="#" style="color:rgb(204,0,0);"></a></i></small>' % bibrec_id out += ''' <script type="text/javascript"> $('#link_%(recid)s').click(function(event) { event.preventDefault(); var more = document.getElementById('more_%(recid)s'); var link = document.getElementById('link_%(recid)s'); var extension = document.getElementById('extension_%(recid)s'); if (more.style.display=='none'){ more.style.display = ''; extension.style.display = 'none'; link.innerHTML = "%(show_less)s" } else { more.style.display = 'none'; extension.style.display = ''; link.innerHTML = "%(show_more)s" } link.style.color = "rgb(204,0,0);" }); function set_up_%(recid)s(){ var extension = document.getElementById('extension_%(recid)s'); extension.innerHTML = "%(extension)s"; $('#link_%(recid)s').click(); } </script> ''' % { 'show_less': _("Hide"), 'show_more': _("Show all %i authors") % nb_authors, 'extension': extension, 'recid': bibrec_id } out += '<script type="text/javascript">set_up_%s()</script>' % bibrec_id return out elif nb_authors > 0: return separator.join(authors)
def send(self, req, form): """ Sends the message. Possible form keys: @param msg_to_user: comma separated usernames. @type msg_to_user: string @param msg_to_group: comma separated groupnames. @type msg_to_group: string @param msg_subject: message subject. @type msg_subject: string @param msg_body: message body. @type msg_body: string @param msg_send_year: year to send this message on. @type msg_send_year: int @param_msg_send_month: month to send this message on @type msg_send_month: year @param_msg_send_day: day to send this message on @type msg_send_day: int @param results_field: value determining which results field to display. See CFG_WEBMESSAGE_RESULTS_FIELD in webmessage_config.py. @param names_to_add: list of usernames to add to msg_to_user / group. @type names_to_add: list of strings @param search_pattern: will search for users/groups with this pattern. @type search_pattern: string @param add_values: if 1 users_to_add will be added to msg_to_user field. @type add_values: int @param *button: which button was pressed. @param ln: language. @type ln: string @return: body. """ argd = wash_urlargd( form, { 'msg_to_user': (str, ""), 'msg_to_group': (str, ""), 'msg_subject': (str, ""), 'msg_body': (str, ""), 'msg_send_year': (int, 0), 'msg_send_month': (int, 0), 'msg_send_day': (int, 0), 'results_field': (str, CFG_WEBMESSAGE_RESULTS_FIELD['NONE']), 'names_selected': (list, []), 'search_pattern': (str, ""), 'send_button': (str, ""), 'search_user': (str, ""), 'search_group': (str, ""), 'add_user': (str, ""), 'add_group': (str, ""), }) # Check if user is logged uid = getUid(req) _ = gettext_set_language(argd['ln']) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourmessages/send" % \ (CFG_SITE_URL,), navmenuid="yourmessages") elif uid == -1 or isGuestUser(uid): return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( { 'referer': "%s/yourmessages/send%s" % (CFG_SITE_URL, make_canonical_urlargd(argd, {})), "ln": argd['ln'] }, {}))) user_info = collect_user_info(req) if not user_info['precached_usemessages']: return page_not_authorized(req, "../", \ text = _("You are not authorized to use messages.")) if argd['send_button']: (body, title, navtrail) = perform_request_send( uid=uid, msg_to_user=argd['msg_to_user'], msg_to_group=argd['msg_to_group'], msg_subject=escape_html(argd['msg_subject']), msg_body=escape_email_quoted_text(argd['msg_body']), msg_send_year=argd['msg_send_year'], msg_send_month=argd['msg_send_month'], msg_send_day=argd['msg_send_day'], ln=argd['ln']) else: title = _('Write a message') navtrail = get_navtrail(argd['ln'], title) if argd['search_user']: argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['USER'] elif argd['search_group']: argd['results_field'] = CFG_WEBMESSAGE_RESULTS_FIELD['GROUP'] add_values = 0 if argd['add_group'] or argd['add_user']: add_values = 1 body = perform_request_write_with_search( uid=uid, msg_to_user=argd['msg_to_user'], msg_to_group=argd['msg_to_group'], msg_subject=escape_html(argd['msg_subject']), msg_body=escape_email_quoted_text(argd['msg_body']), msg_send_year=argd['msg_send_year'], msg_send_month=argd['msg_send_month'], msg_send_day=argd['msg_send_day'], names_selected=argd['names_selected'], search_pattern=argd['search_pattern'], results_field=argd['results_field'], add_values=add_values, ln=argd['ln']) return page(title=title, body=body, navtrail=navtrail, uid=uid, lastupdated=__lastupdated__, req=req, language=argd['ln'], navmenuid="yourmessages", secure_page_p=1)
def tmpl_daemon_content(self, ln=CFG_SITE_LANG, docs=None, metadata=None): """ Displays all information related with batch uploader daemon mode """ _ = gettext_set_language(ln) body_content = "<br/><div id=\"info_box\">" body_content += "<ul>" body_content += "<li>" + _("Using %(x_fmt_open)sweb interface upload%(x_fmt_close)s, actions are executed a single time.") % \ {'x_fmt_open': '<b>', 'x_fmt_close':'</b>'} + "</li>" body_content += "<li>" + _("Check the %(x_url_open)sBatch Uploader daemon help page%(x_url_close)s for executing these actions periodically.") % \ {'x_url_open': '<a href="%s/help/admin/bibupload-admin-guide#4.2">' % CFG_SITE_URL, 'x_url_close': "</a>"} + \ "</li>" body_content += "</div><br/>" body_content += "<h3>%s</h3>" % _("Metadata folders") body_content += "<ul>" for folder in metadata.keys(): body_content += "<li><b>" + folder + "</b></li>" for filename, info in metadata[folder]: body_content += " " for stat in info: body_content += "%s " % stat body_content += filename + "<br />" body_content += "</ul>" body_content += "<h3> Document folders </h3>" body_content += "<ul>" for folder in docs.keys(): body_content += "<li><b>" + folder + "</b></li>" body_content += " " for filename, info in docs[folder]: for stat in info: body_content += "%s " % stat body_content += filename + "<br />" body_content += "</ul>" header = [_("ID"), _("Name"), _("Time"), _("Status"), _("Progress")] actions = [] body_content += """<br /><b>%s</b><br />""" % _("Last BibSched tasks:") res = run_sql( "select id, proc, host, user, runtime, sleeptime, arguments, status, progress from schTASK where proc='batchuploader' and runtime< now() ORDER by runtime" ) if len(res) > 0: (tsk_id, proc, host, user, runtime, sleeptime, arguments, status, progress) = res[len(res) - 1] actions.append([ tsk_id, proc, runtime, (status != "" and status or ''), (progress != "" and progress or '') ]) else: actions.append(['', 'batchuploader', '', '', 'Not executed yet']) body_content += tupletotable(header=header, tuple=actions) body_content += """<br /><b>%s</b><br />""" % _( "Next scheduled BibSched run:") actions = [] res = run_sql( "select id, proc, host, user, runtime, sleeptime, arguments, status, progress from schTASK where proc='batchuploader' and runtime > now() ORDER by runtime" ) if len(res) > 0: (id, proc, host, user, runtime, sleeptime, arguments, status, progress) = res[0] actions.append([ id, proc, runtime, (status != "" and status or ''), (progress != "" and progress or '') ]) else: actions.append(['', 'batchuploader', '', '', 'Not scheduled']) body_content += tupletotable(header=header, tuple=actions) return body_content
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, { 'filetype': (str, None), 'mode': (str, None), 'submit_date': (str, None), 'submit_time': (str, None), 'filename': (str, None), 'priority': (str, None) }) _ = 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/metadata?error=1&filetype=%s&mode=%s&submit_date=%s" % (CFG_SITE_SECURE_URL, argd['filetype'], argd['mode'], argd['submit_date'])) if not form.get('metafile', None) or not form.get( 'metafile', None).value: # Empty file redirect_to_url( req, "%s/batchuploader/metadata?error=2&filetype=%s&mode=%s&submit_date=%s&submit_time=%s" % (CFG_SITE_SECURE_URL, argd['filetype'], argd['mode'], argd['submit_date'], argd['submit_time'])) if correct_date != 0: redirect_to_url( req, "%s/batchuploader/metadata?error=%s&filetype=%s&mode=%s&submit_time=%s" % (CFG_SITE_SECURE_URL, correct_date, argd['filetype'], argd['mode'], 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/metadata?error=1&filetype=%s&mode=%s&submit_date=%s" % (CFG_SITE_SECURE_URL, argd['filetype'], argd['mode'], argd['submit_date'])) elif date == '' and time != '': redirect_to_url( req, "%s/batchuploader/metadata?error=4&filetype=%s&mode=%s&submit_time=%s" % (CFG_SITE_SECURE_URL, argd['filetype'], argd['mode'], argd['submit_time'])) #Function where bibupload queues the file auth_code, auth_message = metadata_upload(req, form.get('metafile', None), argd['filetype'], argd['mode'].split()[0], date, time, argd['filename'], argd['ln'], argd['priority']) 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']) if auth_code == 2: # invalid MARCXML body += batchuploader_templates.tmpl_invalid_marcxml( argd['ln']) title = _("Invalid MARCXML") else: 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 tmpl_display_web_metaupload_form(self, ln=CFG_SITE_LANG, error=0, mode=1, submit_date="yyyy-mm-dd", submit_time="hh:mm:ss"): """ Displays Metadata upload form @param error: defines the type of error to be displayed @param mode: upload mode @param submit_date: file upload date @param submit_time: file upload time @return: the form in HTML format """ _ = gettext_set_language(ln) body_content = "" body_content += """ <script type="text/javascript"> $(function() { $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'}); }); </script> """ body_content += """<form id="uploadform" method="post" action="%(site_url)s/batchuploader/metasubmit" enctype="multipart/form-data">""" \ % {'site_url': CFG_SITE_URL} body_content += """ <div id="content"> <fieldset> """ if error != 0: if error == 1: body_content += """ <div><b>%(msg)s</b></div> """ % { 'msg': _("Warning: Please, select a valid time") } elif error == 2: body_content += """ <div><b>%(msg)s</b></div> """ % { 'msg': _("Warning: Please, select a valid file") } elif error == 3: body_content += """ <div><b>%(msg)s</b></div> """ % { 'msg': _("Warning: The date format is not correct") } elif error == 4: body_content += """ <div><b>%(msg)s</b></div> """ % { 'msg': _("Warning: Please, select a valid date") } body_content += """ <div><span class="mandatory_field""> * </span> %(txt1)s:<input type="file" name="metafile" size="30" onChange="filename.value=(this.value)"></div> <input type="hidden" name="filename" id="filename" value=""> <div><span class="mandatory_field""> * </span> %(txt2)s: <select name="filetype"> <option>MarcXML</option> </select> </div> <div><span class="mandatory_field""> * </span> %(txt3)s: <select name="mode"> <option %(sel1)s>--insert</option> <option %(sel2)s>--replace</option> <option %(sel3)s>--correct</option> <option %(sel4)s>--append</option> <option %(sel5)s>-ir insert-or-replace</option> </select> </div><br/> <div>%(txt4)s <span class="italics">%(txt5)s:</span> <input type="text" id="datepicker" name="submit_date" value=%(submit_date)s onBlur="defText(this)" onFocus="clearText(this)" style="width:100px" > <span class="italics">%(txt6)s:</span> <input type="text" name="submit_time" value=%(submit_time)s onBlur="defText(this)" onFocus="clearText(this)" style="width:100px" > <span class="italics">%(txt7)s: 2009-12-20 19:22:18</span> <div><i>%(txt8)s</i></div> <div> <input type="submit" value="Upload" class="adminbutton"> </div> </fieldset> """ % {'txt1': _("Select file to upload"), 'txt2': _("File type"), 'txt3': _("Upload mode"), 'txt4': _("Upload later? then select:"), 'txt5': _("Date"), 'txt6': _("Time"), 'txt7': _("Example"), 'txt8': _("All fields with %(x_fmt_open)s*%(x_fmt_close)s are mandatory") % \ {'x_fmt_open': '<span class="mandatory_field">', 'x_fmt_close': '</span>'}, 'sel1': mode == '--insert' and "selected" or "", 'sel2': mode == '--replace' and "selected" or "", 'sel3': mode == '--correct' and "selected" or "", 'sel4': mode == '--append' and "selected" or "", 'sel5': mode == '-ir insert-or-replace' and "selected" or "", 'submit_date': submit_date, 'submit_time': submit_time} body_content += """</form></div>""" return body_content
def edit(self, req, form): argd = wash_urlargd( form, { 'projectid': (int, -1), #'delete': (str, ''), 'id': (str, ''), 'a': (str, 'edit'), #'linkproject': (int, -1), #'unlinkproject': (int, -1), #style': (str, None), #'upload': (str, ''), #'dropbox': (str, '') }) _ = gettext_set_language(argd['ln']) # Check if user is authorized to deposit publications user_info = collect_user_info(req) auth_code, auth_message = acc_authorize_action(user_info, 'submit', doctype='OpenAIRE') if auth_code: if user_info['guest'] == '1': return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( { 'referer': "%s%s" % (CFG_SITE_URL, req.unparsed_uri), "ln": argd['ln'] }, {}))) else: return page( req=req, body=_( "You are not authorized to use OpenAIRE deposition."), title=_("Authorization failure"), navmenuid="submit") # Validate action action = argd['a'] if action not in ['edit', 'save', 'submit', 'delete']: abort(404) uid = user_info['uid'] if not argd['id']: return redirect("/deposit/") try: pub = OpenAIREPublication(uid, publicationid=argd['id']) title = pub.metadata.get('title', 'Untitled') except ValueError: abort(404) # # Action handling # if action == 'delete': pub.delete() flash("Upload '%s' was deleted." % title, 'info') return redirect('/deposit/') elif action == 'edit': ctx = { 'pub': pub, 'title': title, 'recid': pub.metadata.get('__recid__', None), } ctx['rendered_form'] = openaire_deposit_templates.tmpl_form( pub.metadata['__publicationid__'], -1, "", # projects_information "", # publication_information "", # fulltext_information form=None, metadata_status='empty', warnings=None, errors=None, ln='en', ) #if action == "edit": #elif action == "delete": # pass # if projectid >= 0: # ## There is a project on which we are working good! # publications = get_all_publications_for_project( # uid, projectid, ln=argd['ln'], style=style) # if argd['publicationid'] in publications: # if argd['addproject'] in all_project_ids: # publications[argd['publicationid'] # ].link_project(argd['linkproject']) # if argd['delproject'] in all_project_ids: # publications[argd['publicationid'] # ].unlink_project(argd['unlinkproject']) # if argd['delete'] and argd['delete'] in publications: # ## there was a request to delete a publication # publications[argd['delete']].delete() # del publications[argd['delete']] # forms = "" # submitted_publications = "" # for index, (publicationid, publication) in enumerate(publications.iteritems()): # if req.method.upper() == 'POST': # publication.merge_form(form, ln=argd['ln']) # if publication.status == 'edited': # publication.check_metadata() # publication.check_projects() # if 'submit_%s' % publicationid in form and not "".join(publication.errors.values()).strip(): # ## i.e. if the button submit for the corresponding publication has been pressed... # publication.upload_record() # if publication.status in ('initialized', 'edited'): # forms += publication.get_publication_form(projectid) # else: # submitted_publications += publication.get_publication_preview() # body += openaire_deposit_templates.tmpl_add_publication_data_and_submit(projectid, forms, submitted_publications, project_information=upload_to_project_information, ln=argd['ln']) # body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid.encode('utf8'), style=style, ln=argd['ln']) # else: ctx.update({ 'myresearch': get_exisiting_publications_for_uid(uid), }) return render_template("openaire_edit.html", req=req, breadcrumbs=[ (_('Home'), ''), (_('Upload'), 'deposit'), (title, ''), ], **ctx).encode('utf8')
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 = perform_request_write(uid=uid, msg_reply_id=argd['msg_reply_id'], msg_to=argd['msg_to'], msg_to_group=argd['msg_to_group'], msg_subject=argd['msg_subject'], msg_body=argd['msg_body'], ln=argd['ln']) title = _("Write a message") return page(title=title, body=body, navtrail=get_navtrail(argd['ln'], title), uid=uid, lastupdated=__lastupdated__, req=req, language=argd['ln'], navmenuid="yourmessages", secure_page_p=1)
def index(self, req, form): """ Main submission page installed on /deposit (hack in Invenio source) with the following features: * Two different themes/skins (for portal and for invenio) * Upload new file to start a publication submission. * Enter metadata for publication(s) related to a project URL parameters: * style: Theme/skin to use - "invenio" or "portal" * projectid: Work on publications for this project * delete: Delete file and publication * plus: ? * upload: Upload new file (without Uploadify backend) """ argd = wash_urlargd( form, { 'projectid': (int, -1), 'delete': (str, ''), 'publicationid': (str, ''), 'plus': (int, -1), 'linkproject': (int, -1), 'unlinkproject': (int, -1), 'style': (str, None), 'upload': (str, ''), 'dropbox': (str, '') }) _ = gettext_set_language(argd['ln']) # Check if user is authorized to deposit publications user_info = collect_user_info(req) auth_code, auth_message = acc_authorize_action(user_info, 'submit', doctype='OpenAIRE') if auth_code: if user_info['guest'] == '1': return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( { 'referer': "%s%s" % (CFG_SITE_URL, req.unparsed_uri), "ln": argd['ln'] }, {}))) else: return page( req=req, body=_( "You are not authorized to use OpenAIRE deposition."), title=_("Authorization failure"), navmenuid="submit") # Get parameters projectid = argd['projectid'] plus = argd['plus'] style = get_openaire_style(req) if plus == -1: try: plus = bool(session_param_get(req, 'plus')) except KeyError: plus = False session_param_set(req, 'plus', plus) else: plus = bool(plus) session_param_set(req, 'plus', plus) # Check projectid all_project_ids = get_all_projectsids() if projectid not in all_project_ids: projectid = -1 uid = user_info['uid'] ## Perform file upload (if needed) if argd['upload']: if projectid < 0: projectid = 0 try: upload_file(form, uid, projectid) except UploadError, e: return page(req=req, body=unicode(e), title=_("File upload error"), navmenuid="submit")
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")