def format_element(bfo): """ List the 'featured' records """ args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] featured_records = get_featured_records(journal_name) lines = [] for (recid, img_url) in featured_records: featured_record = BibFormatObject(recid) if bfo.lang == 'fr': title = featured_record.field('246_1a') if title == '': # No French translation, get it in English title = featured_record.field('245__a') else: title = featured_record.field('245__a') lines.append(''' <a href="%s/record/%s?ln=%s" style="display:block"> <img src="%s" alt="" width="100" class="phr" /> %s </a> ''' % (CFG_SITE_URL, recid, bfo.lang, img_url, title)) return '<br/><br/>'.join(lines)
def format(bfo): """ List the 'featured' records """ args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] featured_records = get_featured_records(journal_name) lines = [] for (recid, img_url) in featured_records: featured_record = BibFormatObject(recid) if bfo.lang == 'fr': title = featured_record.field('246_1a') if title == '': # No French translation, get it in English title = featured_record.field('245__a') else: title = featured_record.field('245__a') lines.append(''' <a href="%s/record/%s?ln=%s" style="display:block"> <img src="%s" alt="" width="100" class="phr" /> %s </a> ''' % (CFG_SITE_URL, recid, bfo.lang, img_url, title)) return '<br/><br/>'.join(lines)
def _get_breaking_news(lang, journal_name): """ Gets the 'Breaking News' articles that are currently active according to start and end dates. """ # CERN Bulletin only if not journal_name.lower() == 'cernbulletin': return '' # Look for active breaking news breaking_news_recids = [recid for recid in search_pattern(p='980__a:BULLETINBREAKING') \ if record_exists(recid) == 1] today = time.mktime(time.localtime()) breaking_news = "" for recid in breaking_news_recids: temp_rec = BibFormatObject(recid) try: end_date = time.mktime( time.strptime(temp_rec.field("925__b"), "%m/%d/%Y")) except: end_date = time.mktime(time.strptime("01/01/1970", "%m/%d/%Y")) if end_date < today: continue try: start_date = time.mktime( time.strptime(temp_rec.field("925__a"), "%m/%d/%Y")) except: start_date = time.mktime(time.strptime("01/01/2050", "%m/%d/%Y")) if start_date > today: continue publish_date = temp_rec.field("269__c") if lang == 'fr': title = temp_rec.field("246_1a") else: title = temp_rec.field("245__a") breaking_news += ''' <h2 class="%s">%s<br/> <strong> <a href="%s/journal/popup?name=%s&type=breaking_news&record=%s&ln=%s" target="_blank">%s</a> </strong> </h2> ''' % ("", publish_date, CFG_SITE_URL, journal_name, recid, lang, title) if breaking_news: breaking_news = '<li>%s</li>' % breaking_news return breaking_news
def _get_breaking_news(lang, journal_name): """ Gets the 'Breaking News' articles that are currently active according to start and end dates. """ # CERN Bulletin only if not journal_name.lower() == 'cernbulletin': return '' # Look for active breaking news breaking_news_recids = [recid for recid in search_pattern(p='980__a:BULLETINBREAKING') \ if record_exists(recid) == 1] today = time.mktime(time.localtime()) breaking_news = "" for recid in breaking_news_recids: temp_rec = BibFormatObject(recid) try: end_date = time.mktime(time.strptime(temp_rec.field("925__b"), "%m/%d/%Y")) except: end_date = time.mktime(time.strptime("01/01/1970", "%m/%d/%Y")) if end_date < today: continue try: start_date = time.mktime(time.strptime(temp_rec.field("925__a"), "%m/%d/%Y")) except: start_date = time.mktime(time.strptime("01/01/2050", "%m/%d/%Y")) if start_date > today: continue publish_date = temp_rec.field("269__c") if lang == 'fr': title = temp_rec.field("246_1a") else: title = temp_rec.field("245__a") breaking_news += ''' <h2 class="%s">%s<br/> <strong> <a href="%s/journal/popup?name=%s&type=breaking_news&record=%s&ln=%s" target="_blank">%s</a> </strong> </h2> ''' % ("", publish_date, CFG_SITE_URL, journal_name, recid, lang, title) if breaking_news: breaking_news = '<li>%s</li>' % breaking_news return breaking_news
class TestInspireFormatElements(unittest.TestCase): # # Test case depends on inspires test records #test CERN_authors def testField(self): print """testing bfeField""" self.bfo = BibFormatObject('7374') self.assertEqual(self.bfo.field('100a'), "Farhi, E.") def testAff(self): """testing Affs""" from bfe_CERN_authors import format_element self.bfo = BibFormatObject('7374') string = format_element(self.bfo, limit="5", print_affiliations="yes") self.assert_(re.search(r'Farhi, E.</a>', string)) self.assert_(re.search(r'</a> \(<a.*MIT', string)) #test INSPIRE_arXiv def testarX(self): """testing arXiv""" from bfe_INSPIRE_arxiv import format_element self.bfo = BibFormatObject('37650') string = format_element(self.bfo) print string self.assert_(re.search(r'3066', string)) self.assert_(not re.search(r'CERN', string)) self.assert_(re.search(r'hep-ph', string)) #test INSPIRE_date def testDate(self): """testing date""" from bfe_INSPIRE_date import format_element self.bfo = BibFormatObject('6194') string = format_element(self.bfo) print string string2 = format_element(self.bfo, us="no") print string2 # self.assert_(re.search(r'Jun 1, 1974',string)) # self.assert_(re.search(r'01 Jun 1974',string2)) #test INSPIRE_links def testLinks(self): """testing Links""" from bfe_INSPIRE_links import format_element self.bfo = BibFormatObject('37650') string = format_element(self.bfo, separator='</li>\n<li>', prefix="<ul><li>", suffix="</li></ul>") print string self.assert_(re.search(r'065201">Journal', string)) self.assert_(re.search(r'\?bibcode=2004', string))
class TestInspireFormatElements(unittest.TestCase): # # Test case depends on inspires test records #test CERN_authors def testField(self): print """testing bfeField""" self.bfo=BibFormatObject('7374') self.assertEqual(self.bfo.field('100a'),"Farhi, E.") def testAff(self): """testing Affs""" from bfe_CERN_authors import format_element self.bfo=BibFormatObject('7374') string = format_element(self.bfo,limit="5",print_affiliations="yes") self.assert_(re.search(r'Farhi, E.</a>',string)) self.assert_(re.search(r'</a> \(<a.*MIT',string)) #test INSPIRE_arXiv def testarX(self): """testing arXiv""" from bfe_INSPIRE_arxiv import format_element self.bfo=BibFormatObject('37650') string=format_element(self.bfo) print string self.assert_(re.search(r'3066',string)) self.assert_(not re.search(r'CERN',string)) self.assert_(re.search(r'hep-ph',string)) #test INSPIRE_date def testDate(self): """testing date""" from bfe_INSPIRE_date import format_element self.bfo=BibFormatObject('6194') string=format_element(self.bfo) print string string2=format_element(self.bfo,us="no") print string2 # self.assert_(re.search(r'Jun 1, 1974',string)) # self.assert_(re.search(r'01 Jun 1974',string2)) #test INSPIRE_links def testLinks(self): """testing Links""" from bfe_INSPIRE_links import format_element self.bfo=BibFormatObject('37650') string= format_element(self.bfo, separator='</li>\n<li>', prefix="<ul><li>",suffix="</li></ul>") print string self.assert_(re.search(r'065201">Journal',string)) self.assert_(re.search(r'\?bibcode=2004',string))
class TestInspireFormatElements(unittest.TestCase): """Test cases for INSPIRE format elements. Depends on default inspire test records (~1000)""" def testFieldRetrieval(self): """bfeField retrieval""" self.bfo = BibFormatObject('1') self.assertEqual(self.bfo.field('100a'), "Sachdev, Subir") def testarXiv(self): """INSPIRE arXiv format""" from bfe_INSPIRE_arxiv import format_element self.bfo = BibFormatObject('1') string = format_element(self.bfo) self.assert_(re.search(r'0299', string)) self.assert_(not re.search(r'CERN', string)) self.assert_(re.search(r'hep-th', string)) def testDate(self): """INSPIRE date format""" from bfe_INSPIRE_date import format_element, parse_date # Test parse date function self.assert_(not parse_date(None)) self.assert_(not parse_date("")) self.assert_(not parse_date("This is bad input")) self.assert_(not parse_date([1, 2, 4, "test"])) self.assert_(parse_date("2003-05-02") == (2003, 5, 2)) self.assert_(parse_date("20030502") == (2003, 5, 2)) self.assert_(parse_date("2003-05") == (2003, 5)) self.assert_(parse_date("200305") == (2003, 5)) self.assert_(parse_date("2003") == (2003, )) # Expect date from 269__$$c self.bfo = BibFormatObject('1') string = format_element(self.bfo) self.assert_(re.search(r'Dec 2010', string)) def testLinks(self): """testing INSPIRE Links""" from bfe_INSPIRE_links import format_element self.bfo = BibFormatObject('1') string = format_element(self.bfo, separator='</li>\n<li>', prefix="<ul><li>", suffix="</li></ul>") self.assert_(re.search(r'1012.0299">Abstract<', string)) self.assert_( re.search(r'arXiv:1012.0299">PDF</a> from arXiv.org', string))
def format_element(bfo): """ Prints the list of papers containing the dataset by title. """ from invenio.bibformat_engine import BibFormatObject from invenio.config import CFG_BASE_URL, CFG_SITE_RECORD parent_recid = bfo.field("786__w") bfo_parent = BibFormatObject(parent_recid) title = bfo_parent.field("245__a") url = CFG_BASE_URL + '/' + CFG_SITE_RECORD + '/' + str(bfo_parent.recID) out = "This dataset complements the following publication: <br />" out += "<a href=\"" + url + "\">" + title + "</a>" return out
def format_element(bfo): """ Prints the list of papers containing the dataset by title. """ from invenio.bibformat_engine import BibFormatObject from invenio.config import CFG_BASE_URL, CFG_SITE_RECORD parent_recid = int(bfo.field("786__w")) bfo_parent = BibFormatObject(parent_recid) title = bfo_parent.field("245__a") url = CFG_BASE_URL + '/' + CFG_SITE_RECORD + '/' + str(bfo_parent.recID) out = "This dataset complements the following publication: <br />" out += "<a href=\"" + url + "\">" + title + "</a>" return out
class TestInspireFormatElements(unittest.TestCase): """Test cases for INSPIRE format elements. Depends on default inspire test records (~1000)""" def testFieldRetrieval(self): """bfeField retrieval""" self.bfo = BibFormatObject('1') self.assertEqual(self.bfo.field('100a'),"Sachdev, Subir") def testarXiv(self): """INSPIRE arXiv format""" from bfe_INSPIRE_arxiv import format_element self.bfo = BibFormatObject('1') string = format_element(self.bfo) self.assert_(re.search(r'0299',string)) self.assert_(not re.search(r'CERN',string)) self.assert_(re.search(r'hep-th',string)) def testDate(self): """INSPIRE date format""" from bfe_INSPIRE_date import format_element, parse_date # Test parse date function self.assert_(not parse_date(None)) self.assert_(not parse_date("")) self.assert_(not parse_date("This is bad input")) self.assert_(not parse_date([1,2,4,"test"])) self.assert_(parse_date("2003-05-02") == (2003,5,2)) self.assert_(parse_date("20030502") == (2003,5,2)) self.assert_(parse_date("2003-05") == (2003,5)) self.assert_(parse_date("200305") == (2003,5)) self.assert_(parse_date("2003") == (2003,)) # Expect date from 269__$$c self.bfo = BibFormatObject('1') string = format_element(self.bfo) self.assert_(re.search(r'Dec 2010',string)) def testLinks(self): """testing INSPIRE Links""" from bfe_INSPIRE_links import format_element self.bfo=BibFormatObject('1') string = format_element(self.bfo, separator='</li>\n<li>', prefix="<ul><li>",suffix="</li></ul>") self.assert_(re.search(r'1012.0299">Abstract<',string)) self.assert_(re.search(r'arXiv:1012.0299">PDF</a> from arXiv.org',string))
def format_element(bfo, new_articles_first='yes', subject_to_css_class_kb="WebJournalSubject2CSSClass", display_all_category_articles='no', display_category_title='no'): """ List all articles one after the other, on the same page. Similar to bfe_webjournal_articles_overview, but displays full articles. Note that you cannot use both bfe_webjournal_articles_overview and bfe_webjournal_articles: you have to choose one of them, as they use the same cache location (It would also not make sense to use both...). @param new_articles_first: if 'yes', display new articles before other articles @param subject_to_css_class_kb: knowledge base that maps 595__a to a CSS class @param display_all_category_articles: if yes, display all articles, whatever category is selected @param display_category_title: if yes, display category title (useful if display_all_category_articles is enabled) @see: bfe_webjournal_articles_overview.py """ 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 = args["ln"] _ = gettext_set_language(ln) # 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 # Shall we display current category, or all? categories = [category_name] if display_all_category_articles.lower() == 'yes': categories = get_journal_categories(journal_name, this_issue_number) out = '' for category_name in categories: if display_category_title.lower() == 'yes': out += '<h2>' + _(category_name) + '</h2>' 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() 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') # Finally create the output. Two different outputs # depending on if we have text to display or not text = [] if ln == "fr": text = temp_rec.fields('590__b') if not text or \ (len(text) == 1 and \ (text[0].strip() in ['', '<br />', '<!--HTML--><br />'])): text = temp_rec.fields('520__b') else: text = temp_rec.fields('520__b') if not text or \ (len(text) == 1 and \ (text[0].strip() in ['', '<br />', '<!--HTML--><br />'])): text = temp_rec.fields('590__b') text = '<br/>'.join(text) out += ''' <tr><td class="article"> <h%(header_tag_size)s class="%(css_classes)s articleTitle" style="clear:both;"> %(title)s </h%(header_tag_size)s> <div class="articleBody"> <div class="articleText"> %(text)s </div> </div> </td></tr> ''' % {'title': title, 'text': text, 'header_tag_size': (display_category_title.lower() == 'yes') and '3' or '2', 'css_classes': ' '.join(css_classes)} out += '</table>' if verbose == 0 and not CFG_ACCESS_CONTROL_LEVEL_SITE == 2 : cache_index_page(out, journal_name, category_name, this_issue_number, ln) return out
def format_marcxml_file(marcxml, is_file=False): ''' Parse the given marcxml file to retreive the metadata needed by the forward of the document to ArXiv.org @param marcxml: marxml file that contains metadata from Invenio @return: (dictionnary) couple of key value needed for the push ''' #init the return tuple marcxml_values = { 'id': '', 'title': '', 'summary': '', 'contributors': [], 'journal_refs': [], 'report_nos': [], 'comment': '', 'doi': '' } # check if the marcxml is not empty if marcxml == '': marcxml_values['error'] = "MARCXML string is empty !" return marcxml_values #get the tag id and code from tag table main_report_number = CFG_MARC_REPORT_NUMBER add_report_number = CFG_MARC_ADDITIONAL_REPORT_NUMBER main_title = CFG_MARC_TITLE main_summary = CFG_MARC_ABSTRACT main_author = CFG_MARC_AUTHOR_NAME main_author_affiliation = CFG_MARC_AUTHOR_AFFILIATION add_author = CFG_MARC_CONTRIBUTOR_NAME add_author_affiliation = CFG_MARC_CONTRIBUTOR_AFFILIATION main_comment = CFG_MARC_COMMENT doi = CFG_MARC_DOI journal_ref_code = CFG_MARC_JOURNAL_REF_CODE journal_ref_title = CFG_MARC_JOURNAL_REF_TITLE journal_ref_page = CFG_MARC_JOURNAL_REF_PAGE journal_ref_year = CFG_MARC_JOURNAL_REF_YEAR #init tmp values contributor = {'name': '', 'email': '', 'affiliation': []} try: bfo = BibFormatObject(recID=None, xml_record=marcxml) except: marcxml_values['error'] = "Unable to open marcxml file !" return marcxml_values marcxml_values = { 'id': bfo.field(main_report_number), 'title': bfo.field(main_title), 'summary': bfo.field(main_summary), 'report_nos': bfo.fields(add_report_number), 'contributors': [], 'journal_refs': [], 'comment': bfo.field(main_comment), 'doi': bfo.field(doi) } authors = bfo.fields(main_author[:-1], repeatable_subfields_p=True) for author in authors: name = author.get(main_author[-1], [''])[0] affiliation = author.get(main_author_affiliation[-1], []) author = {'name': name, 'email': '', 'affiliation': affiliation} marcxml_values['contributors'].append(author) authors = bfo.fields(add_author[:-1], repeatable_subfields_p=True) for author in authors: name = author.get(add_author[-1], [''])[0] affiliation = author.get(add_author_affiliation[-1], []) author = {'name': name, 'email': '', 'affiliation': affiliation} marcxml_values['contributors'].append(author) journals = bfo.fields(journal_ref_title[:-1]) for journal in journals: journal_title = journal.get(journal_ref_title[-1], '') journal_page = journal.get(journal_ref_page[-1], '') journal_code = journal.get(journal_ref_code[-1], '') journal_year = journal.get(journal_ref_year[-1], '') journal = "%s: %s (%s) pp. %s" % (journal_title, journal_code, journal_year, journal_page) marcxml_values['journal_refs'].append(journal) return marcxml_values
def format_element(bfo, separator=", "): """ Prints full conference link @param separator a separator between links """ return_links = [] links = [link for link in bfo.fields('962__') \ if link.has_key('b')] collection = bfo.field('980__a') for link in links: # Sysno is 9 digits + 3 letters, and starts with '00'. # Recid is digits only and never starts with 0. # For sysno it can happen that the 3 ending letters are # dropped in the case they are CER recid_of_related_record = None if link['b'].isdigit() and not link['b'].startswith("0"): # This is a recid url = "%s/record/%s" % (CFG_SITE_URL, link['b']) recid_of_related_record = int(link['b']) else: # This is an Aleph sysno. aleph_sysno = link['b'] if len(aleph_sysno) <= 9 and \ not aleph_sysno.lower().endswith('cer'): aleph_sysno += 'cer' if len(aleph_sysno) <= 9: aleph_sysno = aleph_sysno.zfill(12) url = "%s/search?sysno=%s" % (CFG_SITE_URL, aleph_sysno) if not link.get("t", ""): # There is no link label. We'll need to extract # information from related record. So fetch recid now try: recid_of_related_record = search_pattern( p=aleph_sysno, f='sysno').tolist()[0] except: # Too bad, no link will be displayed continue # Build link address out = '<a href="%s">' % url # Build link label if link.get("t", "") != "": out += "%s</a>" % link.get("t", "") else: try: related_bfo = BibFormatObject(recid_of_related_record) except: # In case not related record was found continue if collection not in ["STANDARD", "ARC0201"]: meeting_title = related_bfo.field('111__a') meeting_location = related_bfo.field('111__c') meeting_date = related_bfo.field('111__d') publication_name = related_bfo.field('260__b') publisher_place = related_bfo.field('260__a') publication_date = related_bfo.field('260__c') serie_statement = related_bfo.field('490__a') volume = related_bfo.field('490__v') report_number = related_bfo.field('088__a') out += meeting_title + ' ' + \ meeting_location + ' ' + \ meeting_date + ' ' + \ publication_name + ' ' + \ publisher_place + ' ' + \ publication_date + ' ' + \ serie_statement + ' ' + \ volume + ' ' + \ report_number + '</a>' else: publication_title = related_bfo.field('245__a') publication_place = related_bfo.field('260__a') out += publication_title + ' ' + \ publication_place + '</a>' return_links.append(out) if link.has_key('k'): return_links.append(" - pp " + link['k'].replace('PR %%c', ' ')) if link.has_key('n') and link['n'] != 'book': return_links.append(' <small>(list <a href="%s/search?p=%s&f=962__n\">conference papers</a>)</small>' % \ (CFG_SITE_URL, link['n'])) return separator.join(return_links)
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 (local_img, headers) = urllib.urlretrieve(img, local_img) img_file = Image.open(local_img) 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 format_marcxml_file(marcxml, is_file=False): ''' Parse the given marcxml file to retreive the metadata needed by the forward of the document to ArXiv.org @param marcxml: marxml file that contains metadata from Invenio @return: (dictionnary) couple of key value needed for the push ''' #init the return tuple marcxml_values = { 'id' : '', 'title' : '', 'summary' : '', 'contributors' : [], 'journal_refs' : [], 'report_nos' : [], 'comment' : '', 'doi' : '' } # check if the marcxml is not empty if marcxml == '': marcxml_values['error'] = "MARCXML string is empty !" return marcxml_values #get the tag id and code from tag table main_report_number = CFG_MARC_REPORT_NUMBER add_report_number = CFG_MARC_ADDITIONAL_REPORT_NUMBER main_title = CFG_MARC_TITLE main_summary = CFG_MARC_ABSTRACT main_author = CFG_MARC_AUTHOR_NAME main_author_affiliation = CFG_MARC_AUTHOR_AFFILIATION add_author = CFG_MARC_CONTRIBUTOR_NAME add_author_affiliation = CFG_MARC_CONTRIBUTOR_AFFILIATION main_comment = CFG_MARC_COMMENT doi = CFG_MARC_DOI journal_ref_code = CFG_MARC_JOURNAL_REF_CODE journal_ref_title = CFG_MARC_JOURNAL_REF_TITLE journal_ref_page = CFG_MARC_JOURNAL_REF_PAGE journal_ref_year = CFG_MARC_JOURNAL_REF_YEAR #init tmp values contributor = {'name' : '', 'email' : '', 'affiliation' : []} try: bfo = BibFormatObject(recID=None, xml_record=marcxml) except: marcxml_values['error'] = "Unable to open marcxml file !" return marcxml_values marcxml_values = { 'id' : bfo.field(main_report_number), 'title' : bfo.field(main_title), 'summary' : bfo.field(main_summary), 'report_nos' : bfo.fields(add_report_number), 'contributors' : [], 'journal_refs' : [], 'comment' : bfo.field(main_comment), 'doi' : bfo.field(doi)} authors = bfo.fields(main_author[:-1], repeatable_subfields_p=True) for author in authors: name = author.get(main_author[-1], [''])[0] affiliation = author.get(main_author_affiliation[-1], []) author = {'name': name, 'email': '', 'affiliation': affiliation} marcxml_values['contributors'].append(author) authors = bfo.fields(add_author[:-1], repeatable_subfields_p=True) for author in authors: name = author.get(add_author[-1], [''])[0] affiliation = author.get(add_author_affiliation[-1], []) author = {'name': name, 'email': '', 'affiliation': affiliation} marcxml_values['contributors'].append(author) journals = bfo.fields(journal_ref_title[:-1]) for journal in journals: journal_title = journal.get(journal_ref_title[-1], '') journal_page = journal.get(journal_ref_page[-1], '') journal_code = journal.get(journal_ref_code[-1], '') journal_year = journal.get(journal_ref_year[-1], '') journal = "%s: %s (%s) pp. %s" % (journal_title, journal_code, journal_year, journal_page) marcxml_values['journal_refs'].append(journal) return marcxml_values
def format_element(bfo, new_articles_first='yes', subject_to_css_class_kb="WebJournalSubject2CSSClass", display_all_category_articles='no'): """ Creates a navigation for articles in the same issue and category. @param new_articles_first: if 'yes', display new articles before other articles @param subject_to_css_class_kb: knowledge base that maps 595__a to a CSS class @param display_all_category_articles: if yes, display all articles, whatever category is selected """ # get variables args = parse_url_string(bfo.user_info['uri']) this_recid = bfo.control_field('001') this_issue_number = args["issue"] category_name = args["category"] journal_name = args["journal_name"] ln = bfo.lang _ = gettext_set_language(ln) this_title = "" if ln == "fr": if bfo.fields('246_1a'): this_title = bfo.fields('246_1a')[0] elif bfo.fields('245__a'): this_title = bfo.fields('245__a')[0] else: if bfo.fields('245__a'): this_title = bfo.fields('245__a')[0] elif bfo.fields('246_1a'): this_title = bfo.fields('246_1a')[0] journal_categories = [category_name] if display_all_category_articles.lower() == 'yes': # Let's retrieve all categories. Ok, we are not supposed to do # that with that element, but if journal editor wants... journal_categories = get_journal_categories(journal_name, this_issue_number) menu_out = '' for category in journal_categories: ordered_articles = get_journal_articles( journal_name, this_issue_number, category, 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 menu_out += '<div class="subNavigationMenu">' order_numbers = ordered_articles.keys() order_numbers.sort() 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) if str(article_id) == this_recid: # Mark as active # Get CSS class (if relevant) notes = bfo.fields('595__a') css_classes = [bfo.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') separator = bfo.field('594__a') if separator == "YES": menu_out += '''<hr/>''' menu_out += '''<div class="active"> <div class="subNavigationMenuItem %s">%s</div></div>''' % \ (' '.join(css_classes), this_title) else: 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') separator = temp_rec.field('594__a') if separator == "YES": menu_out += '''<hr/>''' menu_out += '''<div class="subNavigationMenuItem %s"> <a href="%s">%s</a></div> ''' % (' '.join(css_classes), make_journal_url( bfo.user_info['uri'], { 'recid': article_id, 'ln': bfo.lang, 'category': category }), title) menu_out += '</div>' return menu_out
def VoyagerHoldings(recid): from invenio.bibformat_engine import BibFormatObject from invenio.bibformat_elements import bfe_ILO_links from invenio.messages import gettext_set_language # prepare variables from flask import g bfo = BibFormatObject(recid) _ = gettext_set_language(g.ln) # load the right message language holdings = {} out_table = [] out_html = '' row = '' callno = '' issues_info = '' HQ = False conv = bfo.field('970__a') item_type = bfo.field("996__a") holdings = bfo.fields("964") kept = bfo.field("866_0a") kept_note = bfo.field("866_0z") voyager_sysno = bfo.field("970__a") voyager_sysno = re.sub('^LABORDOC-', '', voyager_sysno) links = bfe_ILO_links.format_element(bfo, style='', prefix_en='', suffix='', separator='<br />', show_icons='no', focus_on_main_file='yes') #request_url = '''http://golf.ilo.org/cgi-bin/Pwebrecon.cgi?bbid=%s&BIB=%s&PAGE=REQUESTBIB" onclick="newWin(this.href); return false;''' % (voyager_sysno, voyager_sysno) request_url = '''http://ringo.ilo.org:7008/vwebv/patronRequests?&sk=en_ILO&bibId=%s" onclick="newWin(this.href); return false;''' % ( voyager_sysno) # Start of the html, request text and link plus holdings table headings out_html = """ <script language="JavaScript" src="http://www.ilo.org/webcommon/s-includes/popups.js" type="text/javascript"></script> <div class="span8"> <div> ILO staff may request this item by clicking on the blue Request button. Enter your client number and last name and click Log in. If you do not have a Client number, contact the Loans Service at tel. +(4122)799 8705; Email: <a href="mailto:[email protected]">[email protected]</a><br /><br /> If you are not ILO staff and would like to see this item, you may wish to contact your library to ask for an inter-library loan or visit an ILO Library near you. </div>""" out_html += """<div class="pull-left tableHoldings"> <table> <thead> <tr> <th>%s</th> <th>%s</th> </tr> </thead> <tbody> """ % ("Location", "Call Number") # iterate through holdings and make rows for the table for out in holdings: location = str(out.get("m", " ")) callno = str(out.get("e", " ")) if callno.find('NYP') >= 1: callno = callno.replace('NYP', 'not yet published') callno = ' ' + callno + ' ' if callno.find('NYP') >= 1: callno = callno.replace('NYP', 'not yet published') row = "<tr><td>" + location + "</td><td>" + callno + "</td></tr>" if row.find('Main collection') >= 1 and HQ == False: row = row.replace('Library - Main collection', 'HQ Library') if kept != 0 or kept_note != 0: issues_info = 'HQ Library' + kept + ' ' + kept_note row = row.replace('HQ Library', issues_info) out_table.append(row) HQ = True elif row.find('Electronic') >= 1: links = bfe_ILO_links.format_element(bfo, style='', prefix_en='', suffix='', separator='<br /', show_icons='no', focus_on_main_file='yes') links = '</td><td>' + links + '</td></tr>' row = re.sub('</td><td>.*</td></tr>', links, row) out_table.append(row) elif row.find('Main collection') >= 1 and HQ: pass else: out_table.append(row) if conv.startswith('ILOCONV'): row = "<tr><td>" + 'Electronic documents' + "</td><td>" + links + "</td></tr>" out_table.append(row) out_table.sort() out_html += ''.join(out_table) + '</tbody></table></div>' out_html += """<div class="span2 requestButton"> <a href="%s"> <h4><i class="icon-book"> </i> %s </h4></a> </div></div>""" % ( request_url, _("Request item")) return out_html
def format_element(bfo, latest_issue_only='yes', newest_articles_only='yes', link_category_headers='yes', display_categories='', hide_when_only_new_records="no"): """ Display the index to the newest articles (of the latest issue, or of the displayed issue) @param latest_issue_only: if 'yes', always display articles of the latest issue, even if viewing a past issue @param newest_articles_only: only display new articles, not those that also appeared in previous issues @param link_category_headers: if yes, category headers link to index page of that category @param display_categories: comma-separated list of categories to display. If none, display all @param hide_when_only_new_records: if 'yes' display new articles only if old articles exist in this issue """ args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] ln = args["ln"] _ = gettext_set_language(ln) if latest_issue_only.lower() == 'yes': issue_number = get_current_issue(bfo.lang, journal_name) else: issue_number = args["issue"] # Try to get HTML from cache if args['verbose'] == 0: cached_html = _get_whatsNew_from_cache(journal_name, issue_number, ln) if cached_html: return cached_html # No cache? Build from scratch # 1. Get the articles journal_categories = get_journal_categories(journal_name, issue_number) if display_categories: display_categories = display_categories.lower().split(',') journal_categories = [category for category in journal_categories \ if category.lower() in display_categories] whats_new_articles = {} for category in journal_categories: whats_new_articles[category] = get_journal_articles(journal_name, issue_number, category, newest_only=newest_articles_only.lower() == 'yes') # Do we want to display new articles only if they have been added # to an issue that contains non-new records? if hide_when_only_new_records.lower() == "yes": # First gather all articles in this issue all_whats_new_articles = {} for category in journal_categories: all_whats_new_articles[category] = get_journal_articles(journal_name, issue_number, category, newest_first=True, newest_only=False) # Then check if we have some articles at position > -1 has_old_articles = False for articles in all_whats_new_articles.values(): if len([order for order in articles.keys() if order > -1]) > 0: has_old_articles = True break if not has_old_articles: # We don't have old articles? Thend don't consider any for category in journal_categories: whats_new_articles[category] = {} # 2. Build the HTML html_out = u'' html_out += _get_breaking_news(ln, journal_name) for category in journal_categories: articles_in_category = whats_new_articles[category] html_articles_in_category = u"" # Generate the list of articles in this category order_numbers = articles_in_category.keys() order_numbers.sort() for order in order_numbers: articles = articles_in_category[order] for recid in articles: link = make_journal_url(bfo.user_info['uri'], {'journal_name': journal_name, 'issue_number': issue_number.split('/')[0], 'issue_year': issue_number.split('/')[1], 'category': category, 'recid': recid, 'ln': bfo.lang}) temp_rec = BibFormatObject(recid) if ln == 'fr': try: title = temp_rec.fields('246_1a')[0] except: continue else: try: title = temp_rec.field('245__a') except: continue try: html_articles_in_category += u'<li><a href="%s">%s</a></li>' % \ (link, title.decode('utf-8')) except: pass if html_articles_in_category: # Good, we found some new articles for this category. # Then insert the genereated results into a larger list # with category as "parent". html_out += '<li>' if link_category_headers.lower() == 'yes': html_out += '<a href="' html_out += make_journal_url(bfo.user_info['uri'], {'journal_name': journal_name, 'issue_number': issue_number.split('/')[0], 'issue_year': issue_number.split('/')[1], 'category': category, 'recid': '', 'ln': bfo.lang}) html_out += '" class="whatsNewCategory">%s</a>' % category else: html_out += '<span class="whatsNewCategory">%s</span>' % category html_out += '<ul class="whatsNewItem">' html_out += html_articles_in_category html_out += '</ul></li>' if not html_out: html_out = '<i>' + _('There are no new articles for the moment') + '</i>' else: html_out = '<ul class="whatsNew">' + html_out + '</ul>' if args['verbose'] == 0: cache_whatsNew(html_out.encode('utf-8'), journal_name, issue_number, ln) return html_out.encode('utf-8')
def format_element(bfo, new_articles_first='yes', subject_to_css_class_kb="WebJournalSubject2CSSClass", display_all_category_articles='no', display_category_title='no'): """ List all articles one after the other, on the same page. Similar to bfe_webjournal_articles_overview, but displays full articles. Note that you cannot use both bfe_webjournal_articles_overview and bfe_webjournal_articles: you have to choose one of them, as they use the same cache location (It would also not make sense to use both...). @param new_articles_first: if 'yes', display new articles before other articles @param subject_to_css_class_kb: knowledge base that maps 595__a to a CSS class @param display_all_category_articles: if yes, display all articles, whatever category is selected @param display_category_title: if yes, display category title (useful if display_all_category_articles is enabled) @see: bfe_webjournal_articles_overview.py """ 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) # 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 # Shall we display current category, or all? categories = [category_name] if display_all_category_articles.lower() == 'yes': categories = get_journal_categories(journal_name, this_issue_number) out = '' for category_name in categories: if display_category_title.lower() == 'yes': out += '<h2>' + _(category_name) + '</h2>' 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() 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') # Finally create the output. Two different outputs # depending on if we have text to display or not text = [] if ln == "fr": text = temp_rec.fields('590__b') if not text or \ (len(text) == 1 and \ (text[0].strip() in ['', '<br />', '<!--HTML--><br />'])): text = temp_rec.fields('520__b') else: text = temp_rec.fields('520__b') if not text or \ (len(text) == 1 and \ (text[0].strip() in ['', '<br />', '<!--HTML--><br />'])): text = temp_rec.fields('590__b') text = '<br/>'.join(text) out += ''' <tr><td class="article"> <h%(header_tag_size)s class="%(css_classes)s articleTitle" style="clear:both;"> %(title)s </h%(header_tag_size)s> <div class="articleBody"> <div class="articleText"> %(text)s </div> </div> </td></tr> ''' % {'title': title, 'text': text, 'header_tag_size': (display_category_title.lower() == 'yes') and '3' or '2', 'css_classes': ' '.join(css_classes)} out += '</table>' if verbose == 0 and not CFG_ACCESS_CONTROL_LEVEL_SITE == 2 : cache_index_page(out, journal_name, category_name, this_issue_number, ln) return out
def format_element(bfo, latest_issue_only='yes', newest_articles_only='yes', link_category_headers='yes', display_categories='', hide_when_only_new_records="no"): """ Display the index to the newest articles (of the latest issue, or of the displayed issue) @param latest_issue_only: if 'yes', always display articles of the latest issue, even if viewing a past issue @param newest_articles_only: only display new articles, not those that also appeared in previous issues @param link_category_headers: if yes, category headers link to index page of that category @param display_categories: comma-separated list of categories to display. If none, display all @param hide_when_only_new_records: if 'yes' display new articles only if old articles exist in this issue """ args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] ln = args["ln"] _ = gettext_set_language(ln) if latest_issue_only.lower() == 'yes': issue_number = get_current_issue(bfo.lang, journal_name) else: issue_number = args["issue"] # Try to get HTML from cache if args['verbose'] == 0: cached_html = _get_whatsNew_from_cache(journal_name, issue_number, ln) if cached_html: return cached_html # No cache? Build from scratch # 1. Get the articles journal_categories = get_journal_categories(journal_name, issue_number) if display_categories: display_categories = display_categories.lower().split(',') journal_categories = [category for category in journal_categories \ if category.lower() in display_categories] whats_new_articles = {} for category in journal_categories: whats_new_articles[category] = get_journal_articles( journal_name, issue_number, category, newest_only=newest_articles_only.lower() == 'yes') # Do we want to display new articles only if they have been added # to an issue that contains non-new records? if hide_when_only_new_records.lower() == "yes": # First gather all articles in this issue all_whats_new_articles = {} for category in journal_categories: all_whats_new_articles[category] = get_journal_articles( journal_name, issue_number, category, newest_first=True, newest_only=False) # Then check if we have some articles at position > -1 has_old_articles = False for articles in all_whats_new_articles.values(): if len([order for order in articles.keys() if order > -1]) > 0: has_old_articles = True break if not has_old_articles: # We don't have old articles? Thend don't consider any for category in journal_categories: whats_new_articles[category] = {} # 2. Build the HTML html_out = _get_breaking_news(ln, journal_name) for category in journal_categories: articles_in_category = whats_new_articles[category] html_articles_in_category = "" # Generate the list of articles in this category order_numbers = articles_in_category.keys() order_numbers.sort() for order in order_numbers: articles = articles_in_category[order] for recid in articles: link = make_journal_url( bfo.user_info['uri'], { 'journal_name': journal_name, 'issue_number': issue_number.split('/')[0], 'issue_year': issue_number.split('/')[1], 'category': category, 'recid': recid, 'ln': bfo.lang }) temp_rec = BibFormatObject(recid) if ln == 'fr': try: title = temp_rec.fields('246_1a')[0] except: continue else: try: title = temp_rec.field('245__a') except: continue try: html_articles_in_category += '<li><a href="%s">%s</a></li>' % \ (link, title) except: pass if html_articles_in_category: # Good, we found some new articles for this category. # Then insert the genereated results into a larger list # with category as "parent". html_out += '<li>' if link_category_headers.lower() == 'yes': html_out += '<a href="' html_out += make_journal_url( bfo.user_info['uri'], { 'journal_name': journal_name, 'issue_number': issue_number.split('/')[0], 'issue_year': issue_number.split('/')[1], 'category': category, 'recid': '', 'ln': bfo.lang }) html_out += '" class="whatsNewCategory">%s</a>' % category else: html_out += '<span class="whatsNewCategory">%s</span>' % category html_out += '<ul class="whatsNewItem">' html_out += html_articles_in_category html_out += '</ul></li>' if not html_out: html_out = '<i>' + _( 'There are no new articles for the moment') + '</i>' else: html_out = '<ul class="whatsNew">' + html_out + '</ul>' if args['verbose'] == 0: cache_whatsNew(html_out, journal_name, issue_number, ln) return html_out
def format(bfo, new_articles_first='yes', subject_to_css_class_kb="WebJournalSubject2CSSClass", display_all_category_articles='no'): """ Creates a navigation for articles in the same issue and category. @param new_articles_first: if 'yes', display new articles before other articles @param subject_to_css_class_kb: knowledge base that maps 595__a to a CSS class @param display_all_category_articles: if yes, display all articles, whatever category is selected """ # get variables args = parse_url_string(bfo.user_info['uri']) this_recid = bfo.control_field('001') this_issue_number = args["issue"] category_name = args["category"] journal_name = args["journal_name"] ln = args["ln"] _ = gettext_set_language(ln) this_title = "" if ln == "fr": if bfo.fields('246_1a'): this_title = bfo.fields('246_1a')[0] elif bfo.fields('245__a'): this_title = bfo.fields('245__a')[0] else: if bfo.fields('245__a'): this_title = bfo.fields('245__a')[0] elif bfo.fields('246_1a'): this_title = bfo.fields('246_1a')[0] journal_categories = [category_name] if display_all_category_articles.lower() == 'yes': # Let's retrieve all categories. Ok, we are not supposed to do # that with that element, but if journal editor wants... journal_categories = get_journal_categories(journal_name, this_issue_number) menu_out = '' for category in journal_categories: ordered_articles = get_journal_articles(journal_name, this_issue_number, category, 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 menu_out += '<div class="subNavigationMenu">' order_numbers = ordered_articles.keys() order_numbers.sort() 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) if str(article_id) == this_recid: # Mark as active # Get CSS class (if relevant) notes = bfo.fields('595__a') css_classes = [bfo.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') menu_out += '''<div class="active"> <div class="subNavigationMenuItem %s">%s</div></div>''' % \ (' '.join(css_classes), this_title) else: 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') menu_out += '''<div class="subNavigationMenuItem %s"> <a href="%s">%s</a></div> ''' % (' '.join(css_classes), make_journal_url(bfo.user_info['uri'], {'recid': article_id, 'ln': bfo.lang, 'category': category}), title) menu_out += '</div>' return menu_out