def test_get_journal_categories(self):
        """webjournal - returns all categories for a given issue"""
        journal1 = wju.get_journal_categories('AtlantisTimes', '03/2009')
        self.assertEqual(journal1[0], 'News')
        self.assertEqual(journal1[1], 'Science')

        journal2 = wju.get_journal_categories('AtlantisTimes', )
        self.assertEqual(journal2[0], 'News')
        self.assertEqual(journal2[1], 'Science')
        self.assertEqual(journal2[2], 'Arts')
    def test_get_journal_categories(self):
        """webjournal - returns all categories for a given issue"""
        journal1 = wju.get_journal_categories("AtlantisTimes", "03/2009")
        self.assertEqual(journal1[0], "News")
        self.assertEqual(journal1[1], "Science")

        journal2 = wju.get_journal_categories("AtlantisTimes")
        self.assertEqual(journal2[0], "News")
        self.assertEqual(journal2[1], "Science")
        self.assertEqual(journal2[2], "Arts")
    def test_get_journal_categories(self):
        """webjournal - returns all categories for a given issue"""
        journal1 = wju.get_journal_categories('AtlantisTimes', '03/2009')
        self.assertEqual(journal1[0], 'News')
        self.assertEqual(journal1[1], 'Science')

        journal2 = wju.get_journal_categories('AtlantisTimes', )
        self.assertEqual(journal2[0], 'News')
        self.assertEqual(journal2[1], 'Science')
        self.assertEqual(journal2[2], 'Arts')
def format_element(bfo,
                   category_prefix,
                   category_suffix,
                   separator=" | ",
                   display_all_categories='no'):
    """
    Creates the main navigation menu of the journal

    @param category_prefix: value printed before each category
    @param category_suffix: value printed after each category
    @param separator: value printed between each category
    @param display_all_categories: if 'yes', show categories even when there is no corresponding article
    """
    # Retrieve context (journal, issue and category) from URI
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    selected_category = args["category"]
    this_issue_number = args["issue"]
    ln = args["ln"]
    _ = gettext_set_language(ln)

    # Retrieve categories for this journal and issue
    journal_categories = get_journal_categories(journal_name,
                                                display_all_categories.lower() != 'yes' and \
                                                this_issue_number or None)

    # Build the links to categories
    categories_links = []
    for category in journal_categories:
        # Create URL
        category_url = make_journal_url(bfo.user_info['uri'], {
            'category': category,
            'recid': '',
            'ln': bfo.lang
        })
        # Create HTML link
        linkattrd = {}
        if category.lower() == selected_category.lower():
            linkattrd = {'class': 'selectedNavigationPage'}
        if journal_name == 'CERNBulletin' and \
               category == 'Training and Development':
            category = 'Training'
        category_link = create_html_link(category_url, {},
                                         _(category),
                                         linkattrd=linkattrd)
        # Append to list of links
        categories_links.append(category_link)

    navigation = '<div id="navigationMenu">'
    navigation += separator.join([category_prefix + \
                                  category_link + \
                                  category_suffix for category_link \
                                  in categories_links])
    navigation += '</div>'
    return navigation
def wash_category(ln, category, journal_name, issue):
    """
    Washes a category name.
    """
    categories = get_journal_categories(journal_name, issue=None)
    if category in categories:
        return category
    elif category == "" and len(categories) > 0:
        return categories[0]
    else:
        raise InvenioWebJournalNoCategoryError(ln, category, categories)
def move_drafts_articles_to_ready(journal_name, issue):
    """
    Move draft articles to their final "collection".

    To do so we rely on the convention that an admin-chosen keyword
    must be removed from the metadata
    """
    protected_datafields = ['100', '245', '246', '520', '590', '700']
    keyword_to_remove = get_journal_draft_keyword_to_remove(journal_name)
    collections_to_refresh = {}

    categories = get_journal_categories(journal_name, issue)
    for category in categories:
        articles = get_journal_articles(journal_name, issue, category)
        for order, recids in articles.iteritems():
            for recid in recids:
                record_xml = format_record(recid, of='xm')
                if not record_xml:
                    continue
                new_record_xml_path = os.path.join(CFG_TMPDIR,
                                                   'webjournal_publish_' + \
                                                   str(recid) + '.xml')
                if os.path.exists(new_record_xml_path):
                    # Do not modify twice
                    continue
                record_struc = create_record(record_xml)
                record = record_struc[0]
                new_record = update_draft_record_metadata(
                    record, protected_datafields, keyword_to_remove)
                new_record_xml = print_rec(new_record)
                if new_record_xml.find(keyword_to_remove) >= 0:
                    new_record_xml = new_record_xml.replace(
                        keyword_to_remove, '')
                    # Write to file
                    new_record_xml_file = file(new_record_xml_path, 'w')
                    new_record_xml_file.write(new_record_xml)
                    new_record_xml_file.close()
                    # Submit
                    task_low_level_submission('bibupload', 'WebJournal', '-c',
                                              new_record_xml_path)
                    task_low_level_submission('bibindex', 'WebJournal', '-i',
                                              str(recid))
                    for collection in get_all_collections_of_a_record(recid):
                        collections_to_refresh[collection] = ''

    # Refresh collections
    collections_to_refresh.update([
        (c, '')
        for c in get_journal_collection_to_refresh_on_release(journal_name)
    ])
    for collection in collections_to_refresh.keys():
        task_low_level_submission('webcoll', 'WebJournal', '-f', '-p', '2',
                                  '-c', collection)
def move_drafts_articles_to_ready(journal_name, issue):
    """
    Move draft articles to their final "collection".

    To do so we rely on the convention that an admin-chosen keyword
    must be removed from the metadata
    """
    protected_datafields = ['100', '245', '246', '520', '590', '700']
    keyword_to_remove = get_journal_draft_keyword_to_remove(journal_name)
    collections_to_refresh = {}

    categories = get_journal_categories(journal_name, issue)
    for category in categories:
        articles = get_journal_articles(journal_name, issue, category)
        for order, recids in articles.iteritems():
            for recid in recids:
                record_xml = format_record(recid, of='xm')
                if not record_xml:
                    continue
                new_record_xml_path = os.path.join(CFG_TMPDIR,
                                                   'webjournal_publish_' + \
                                                   str(recid) + '.xml')
                if os.path.exists(new_record_xml_path):
                    # Do not modify twice
                    continue
                record_struc = create_record(record_xml)
                record = record_struc[0]
                new_record = update_draft_record_metadata(record,
                                                          protected_datafields,
                                                          keyword_to_remove)
                new_record_xml = print_rec(new_record)
                if new_record_xml.find(keyword_to_remove) >= 0:
                    new_record_xml = new_record_xml.replace(keyword_to_remove, '')
                    # Write to file
                    new_record_xml_file = file(new_record_xml_path, 'w')
                    new_record_xml_file.write(new_record_xml)
                    new_record_xml_file.close()
                    # Submit
                    task_low_level_submission('bibupload',
                                              'WebJournal',
                                              '-c', new_record_xml_path)
                    task_low_level_submission('bibindex',
                                              'WebJournal',
                                              '-i', str(recid))
                    for collection in get_all_collections_of_a_record(recid):
                        collections_to_refresh[collection] = ''

    # Refresh collections
    collections_to_refresh.update([(c, '') for c in get_journal_collection_to_refresh_on_release(journal_name)])
    for collection in collections_to_refresh.keys():
        task_low_level_submission('webcoll',
                                  'WebJournal',
                                  '-f', '-p', '2','-c', collection)
def format_element(bfo, category_prefix, category_suffix, separator=" | ",
           display_all_categories='no'):
    """
    Creates the main navigation menu of the journal

    @param category_prefix: value printed before each category
    @param category_suffix: value printed after each category
    @param separator: value printed between each category
    @param display_all_categories: if 'yes', show categories even when there is no corresponding article
    """
    # Retrieve context (journal, issue and category) from URI
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    selected_category = args["category"]
    this_issue_number = args["issue"]
    ln = bfo.lang
    _ = gettext_set_language(ln)

    # Retrieve categories for this journal and issue
    journal_categories = get_journal_categories(journal_name,
                                                display_all_categories.lower() != 'yes' and \
                                                this_issue_number or None)

    # Build the links to categories
    categories_links = []
    for category in journal_categories:
        # Create URL
        category_url = make_journal_url(bfo.user_info['uri'],
                                        {'category': category,
                                         'recid': '',
                                         'ln': bfo.lang})
        # Create HTML link
        linkattrd = {}
        if category.lower() == selected_category.lower():
            linkattrd = {'class':'selectedNavigationPage'}
        if journal_name == 'CERNBulletin' and \
               category == 'Training and Development':
            category = 'Training'
            if ln == 'fr':
                category = 'Formations'
        category_link = create_html_link(category_url, {},
                                         _(category),
                                         linkattrd=linkattrd)
        # Append to list of links
        categories_links.append(category_link)

    navigation = '<div id="navigationMenu">'
    navigation += separator.join([category_prefix + \
                                  category_link + \
                                  category_suffix for category_link \
                                  in categories_links])
    navigation += '</div>'
    return navigation
def wash_category(ln, category, journal_name, issue):
    """
    Washes a category name.
    """
    categories = get_journal_categories(journal_name, issue=None)
    if category in categories:
        return category
    elif category == "" and len(categories) > 0:
        return categories[0]
    else:
        raise InvenioWebJournalNoCategoryError(ln,
                                               category,
                                               categories)
def move_drafts_articles_to_ready(journal_name, issue):
    """
    Move draft articles to their final "collection".

    To do so we rely on the convention that an admin-chosen keyword
    must be removed from the metadata
    """
    protected_datafields = ["100", "245", "246", "520", "590", "700"]
    keyword_to_remove = get_journal_draft_keyword_to_remove(journal_name)
    collections_to_refresh = {}

    categories = get_journal_categories(journal_name, issue)
    for category in categories:
        articles = get_journal_articles(journal_name, issue, category)
        for order, recids in articles.iteritems():
            for recid in recids:
                record_xml = format_record(recid, of="xm")
                if not record_xml:
                    continue
                new_record_xml_path = os.path.join(CFG_TMPDIR, "webjournal_publish_" + str(recid) + ".xml")
                if os.path.exists(new_record_xml_path):
                    # Do not modify twice
                    continue
                record_struc = create_record(record_xml)
                record = record_struc[0]
                new_record = update_draft_record_metadata(record, protected_datafields, keyword_to_remove)
                new_record_xml = print_rec(new_record)
                if new_record_xml.find(keyword_to_remove) >= 0:
                    new_record_xml = new_record_xml.replace(keyword_to_remove, "")
                    # Write to file
                    new_record_xml_file = file(new_record_xml_path, "w")
                    new_record_xml_file.write(new_record_xml)
                    new_record_xml_file.close()
                    # Submit
                    task_low_level_submission("bibupload", "WebJournal", "-c", new_record_xml_path)
                    task_low_level_submission("bibindex", "WebJournal", "-i", str(recid))
                    for collection in get_all_collections_of_a_record(recid):
                        collections_to_refresh[collection] = ""

    # Refresh collections
    collections_to_refresh.update([(c, "") for c in get_journal_collection_to_refresh_on_release(journal_name)])
    for collection in collections_to_refresh.keys():
        task_low_level_submission("webcoll", "WebJournal", "-f", "-p", "2", "-c", collection)
Exemple #11
0
def format_element(bfo,
                   categories,
                   label="Subscribe by RSS",
                   rss_icon_url="/img/rss.png",
                   cc='',
                   css_class="rssLink"):
    """
    Display RSS links to journal articles, in one or several
    categories, or to the whole journal (if 'cc' parameter is used).

    Note about 'cc': if we want an RSS of *all* articles (whathever
    the category is), either we build an RSS url to each of the
    categories/collections of the journal, or we simply link to the
    main collection ('cc') of the journal (which implies that journal
    categories exist as sub-collections of 'cc'). The second option is
    preferred.

    @param categories: comma-separated list of journal categories that will be linked from this RSS. If 'all', use all. If empty, try to use current category.
    @param label: label of the RSS link
    @param rss_icon_url: if provided, display the RSS icon in front of the label
    @param cc: if provided, use as root collection for the journal, and ignore 'categories' parameter.
    @param css_class: CSS class of the RSS link.
    """
    args = parse_url_string(bfo.user_info['uri'])
    category_name = args["category"]
    journal_name = args["journal_name"]
    ln = bfo.lang
    _ = gettext_set_language(ln)

    if cc:
        categories = []
    elif categories.lower() == 'all':
        categories = get_journal_categories(journal_name)
    elif not categories and category_name:
        categories = [category_name]
    else:
        categories = categories.split(',')

    # Build the query definition for selected categories. If a
    # category name can a match collection name, we can simply search
    # in this collection. Otherwise we have to search using the query
    # definition of the category.
    # Note that if there is one category that does not match a
    # collection name, we have to use collections queries for all
    # categories (we cannot display all records of a collection +
    # apply search constraint on other collections)
    collections = []
    pattern = []
    must_use_pattern = False
    for category in categories:
        dbquery = get_category_query(journal_name, category)
        if dbquery:
            pattern.append(dbquery)
            res = None
            if not must_use_pattern:
                res = run_sql("SELECT name FROM collection WHERE dbquery=%s",
                              (dbquery, ))
            if res:
                collections.append(res[0][0])
            else:
                # Could not find corresponding collection. Maybe
                # replace '980__a' by 'collection'?
                if not must_use_pattern:
                    res = run_sql(
                        "SELECT name FROM collection WHERE dbquery=%s",
                        (dbquery.replace('980__a', 'collection'), ))
                if res:
                    collections.append(res[0][0])
                else:
                    # Really no matching collection name
                    # apparently. Use query definition.
                    must_use_pattern = True

    # Build label
    link_label = ''
    if rss_icon_url:
        if rss_icon_url.startswith('/'):
            # Build an absolute URL
            rss_icon_url = CFG_SITE_URL + rss_icon_url
        link_label += '<img src="%s" alt="RSS" border="0"/> ' % rss_icon_url
    if label:
        link_label += _(label)

    # Build link
    rss_url = CFG_SITE_URL + '/rss'
    if cc:
        rss_url += '?cc=' + quote(cc)
    elif must_use_pattern:
        rss_url += '?p=' + quote(' or '.join(pattern))
    else:
        rss_url += '?c=' + '&amp;c='.join([quote(coll) \
                                               for coll in collections])
    rss_url += '&amp;ln=' + ln

    return create_html_link(rss_url, {},
                            link_label=link_label,
                            linkattrd={'class': css_class})
        except InvenioWebJournalNoNameError, e:
            return e.user_box(req)
        except InvenioWebJournalNoJournalOnServerError, e:
            register_exception(req=req)
            return e.user_box(req)

        # If some parameters are missing, deduce them and
        # redirect
        if not journal_issue_year or not journal_issue_number or not category or redirect_p or specific_category:
            if not journal_issue_year or not journal_issue_number:
                journal_issue = get_current_issue(argd["ln"], washed_journal_name)
                journal_issue_year = journal_issue.split("/")[1]
                journal_issue_number = journal_issue.split("/")[0]
            if not category or specific_category:
                categories = get_journal_categories(
                    washed_journal_name, journal_issue_number + "/" + journal_issue_year
                )
                if not categories:
                    # Mmh, it seems that this issue has no
                    # category. Ok get all of them regardless of the
                    # issue
                    categories = get_journal_categories(washed_journal_name)
                    if not categories:
                        # Mmh we really have no category!
                        try:
                            raise InvenioWebJournalIssueNotFoundDBError(argd["ln"], journal_name, "")
                        except InvenioWebJournalIssueNotFoundDBError, e:
                            register_exception(req=req)
                            return e.user_box(req)
                if not category:
                    category = categories[0].replace(" ", "%20")
def format_element(bfo, categories, label="Subscribe by RSS",
                   rss_icon_url="/img/rss.png", cc='', css_class="rssLink",
                   rss_icon_width='16px', rss_icon_height='16px'):
    """
    Display RSS links to journal articles, in one or several
    categories, or to the whole journal (if 'cc' parameter is used).

    Note about 'cc': if we want an RSS of *all* articles (whathever
    the category is), either we build an RSS url to each of the
    categories/collections of the journal, or we simply link to the
    main collection ('cc') of the journal (which implies that journal
    categories exist as sub-collections of 'cc'). The second option is
    preferred.

    @param categories: comma-separated list of journal categories that will be linked from this RSS. If 'all', use all. If empty, try to use current category.
    @param label: label of the RSS link
    @param rss_icon_url: if provided, display the RSS icon in front of the label
    @param rss_icon_width: if provided, declared width for the RSS icon
    @param rss_icon_height: if provided, declared height for the RSS icon
    @param cc: if provided, use as root collection for the journal, and ignore 'categories' parameter.
    @param css_class: CSS class of the RSS link.
    """
    args = parse_url_string(bfo.user_info['uri'])
    category_name = args["category"]
    journal_name = args["journal_name"]
    ln = bfo.lang
    _ = gettext_set_language(ln)


    if cc:
        categories = []
    elif categories.lower() == 'all':
        categories = get_journal_categories(journal_name)
    elif not categories and category_name:
        categories = [category_name]
    else:
        categories = categories.split(',')

    # Build the query definition for selected categories. If a
    # category name can a match collection name, we can simply search
    # in this collection. Otherwise we have to search using the query
    # definition of the category.
    # Note that if there is one category that does not match a
    # collection name, we have to use collections queries for all
    # categories (we cannot display all records of a collection +
    # apply search constraint on other collections)
    collections = []
    pattern = []
    must_use_pattern = False
    for category in categories:
        dbquery = get_category_query(journal_name, category)
        if dbquery:
            pattern.append(dbquery)
            res = None
            if not must_use_pattern:
                res = run_sql("SELECT name FROM collection WHERE dbquery=%s",
                              (dbquery,))
            if res:
                collections.append(res[0][0])
            else:
                # Could not find corresponding collection. Maybe
                # replace '980__a' by 'collection'?
                if not must_use_pattern:
                    res = run_sql("SELECT name FROM collection WHERE dbquery=%s",
                                  (dbquery.replace('980__a', 'collection'),))
                if res:
                    collections.append(res[0][0])
                else:
                    # Really no matching collection name
                    # apparently. Use query definition.
                    must_use_pattern = True

    # Build label
    link_label = ''
    if rss_icon_url:
        if rss_icon_url.startswith('/'):
            # Build an absolute URL
            rss_icon_url = CFG_SITE_URL + rss_icon_url
        link_label += '<img src="%s" alt="RSS" border="0"%s%s/> ' % \
                      (rss_icon_url, rss_icon_width and ' width="%s"' % rss_icon_width or '',
                       rss_icon_height and ' height="%s"' % rss_icon_height or '')
    if label:
        link_label += _(label)

    # Build link
    rss_url = CFG_SITE_URL + '/rss'
    if cc:
        rss_url += '?cc=' + quote(cc)
    elif must_use_pattern:
        rss_url += '?p=' + quote(' or '.join(pattern))
    else:
        rss_url += '?c=' + '&amp;c='.join([quote(coll) \
                                               for coll in collections])
    rss_url += '&amp;ln=' + ln

    return create_html_link(rss_url, {},
                            link_label=link_label,
                            linkattrd={'class': css_class})
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 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')
            return e.user_box(req)

        # If some parameters are missing, deduce them and
        # redirect
        if not journal_issue_year or \
           not journal_issue_number or \
           not category or \
           redirect_p or \
           specific_category:
            if not journal_issue_year or not journal_issue_number:
                journal_issue = get_current_issue(argd['ln'], washed_journal_name)
                journal_issue_year = journal_issue.split('/')[1]
                journal_issue_number = journal_issue.split('/')[0]
            if not category or specific_category:
                categories = get_journal_categories(washed_journal_name,
                                                    journal_issue_number + \
                                                    '/' + journal_issue_year)
                if not categories:
                    # Mmh, it seems that this issue has no
                    # category. Ok get all of them regardless of the
                    # issue
                    categories = get_journal_categories(washed_journal_name)
                    if not categories:
                        # Mmh we really have no category!
                        try:
                            raise InvenioWebJournalIssueNotFoundDBError(argd['ln'],
                                                                        journal_name,
                                                                        '')
                        except InvenioWebJournalIssueNotFoundDBError, e:
                            register_exception(req=req)
                            return e.user_box(req)
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
Exemple #18
0
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
Exemple #19
0
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_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