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/%s/%s?ln=%s" style="display:block">
            <img src="%s" alt="" width="100" class="phr" />
            %s
        </a>
        """
            % (CFG_SITE_URL, CFG_SITE_RECORD, recid, bfo.lang, img_url, title)
        )

    return "<br/><br/>".join(lines)
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/%s/%s?ln=%s" style="display:block">
            <img src="%s" alt="" width="100" class="phr" />
            %s
        </a>
        ''' % (CFG_SITE_URL, CFG_SITE_RECORD, recid, bfo.lang, img_url, title))

    return '<br/><br/>'.join(lines)
def format_element(bfo, indico_baseurl="https://indico.cern.ch", indico_what='categ', indico_loc="", indico_id="1l7", indico_key="", indico_sig="", indico_onlypublic='yes', indico_from="today", indico_to='today', indico_credential_path=""):
    """
    Display the list of seminar from the given Indico instance

    See Indico HTTP Export APIs:
    http://indico.cern.ch/ihelp/html/ExportAPI/index.html

    @param indico_baseurl: Indico base URL from which to retrieve information
    @param indico_what: element to export
    @type indico_what: one of the strings: C{categ}, C{event}, C{room}, C{reservation}
    @param indico_loc: location of the element(s) specified by ID (only used for some elements)
    @param indico_id: ID of the element to be exported
    @type indico_id: a string or a list/tuple of strings
    @param indico_type: output format
    @type indico_type: one of the strings: C{json}, C{jsonp}, C{xml}, C{html}, C{ics}, C{atom}
    @param indico_params: parameters of the query. See U{http://indico.cern.ch/ihelp/html/ExportAPI/common.html}
    @param indico_key: API key provided for the given Indico instance
    @param indico_sig: API secret key (signature) provided for the given Indico instance
    @param indico_credential_path: if provided, load 'indico_key' and 'indico_sig' from this path
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    cached_filename = "webjournal_widget_seminars_%s.xml" % journal_name
    out = get_widget_html(bfo, indico_baseurl, indico_what, indico_loc, indico_id,
                          indico_onlypublic, indico_from, indico_to,
                          indico_key, indico_sig, indico_credential_path,
                          cached_filename, bfo.lang)
    return out
Example #4
0
def format_element(bfo, var=''):
    """
    Print several journal specific variables.
    @param var: the name of the desired variable. Can be one of: WEBJOURNAL_CSS_URL, WEBJOURNAL_NAME, WEBJOURNAL_NAME_INTL, WEBJOURNAL_CURRENT_ISSUE_NUMBER, WEBJOURNAL_ISSUE_NUMBER, WEBJOURNAL_URL
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    this_issue_number = args["issue"]

    if var == '':
        out =  ''
    elif var == 'WEBJOURNAL_NAME':
        out = journal_name
    elif var == 'WEBJOURNAL_NAME_INTL':
        out = get_journal_name_intl(journal_name, bfo.lang)
    elif var == 'WEBJOURNAL_ISSUE_NUMBER':
        out = this_issue_number
    elif var == 'WEBJOURNAL_CURRENT_ISSUE_NUMBER':
        out = get_current_issue(bfo.lang, journal_name)
    elif var == 'WEBJOURNAL_URL':
        out = make_journal_url(bfo.user_info['uri'], {'ln': bfo.lang})
    elif var == 'WEBJOURNAL_CSS_URL':
        out = get_journal_css_url(journal_name)
    elif var == 'WEBJOURNAL_USER_LANG':
        out = bfo.lang

    return out
Example #5
0
def format_element(bfo, var=''):
    """
    Print several journal specific variables.
    @param var: the name of the desired variable. Can be one of: WEBJOURNAL_CSS_URL, WEBJOURNAL_NAME, WEBJOURNAL_NAME_INTL, WEBJOURNAL_CURRENT_ISSUE_NUMBER, WEBJOURNAL_ISSUE_NUMBER, WEBJOURNAL_URL
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    this_issue_number = args["issue"]

    if var == '':
        out = ''
    elif var == 'WEBJOURNAL_NAME':
        out = journal_name
    elif var == 'WEBJOURNAL_NAME_INTL':
        out = get_journal_name_intl(journal_name, bfo.lang)
    elif var == 'WEBJOURNAL_ISSUE_NUMBER':
        out = this_issue_number
    elif var == 'WEBJOURNAL_CURRENT_ISSUE_NUMBER':
        out = get_current_issue(bfo.lang, journal_name)
    elif var == 'WEBJOURNAL_URL':
        out = make_journal_url(bfo.user_info['uri'], {'ln': bfo.lang})
    elif var == 'WEBJOURNAL_CSS_URL':
        out = get_journal_css_url(journal_name)
    elif var == 'WEBJOURNAL_USER_LANG':
        out = bfo.lang

    return out
def format_element(bfo, category_prefix, category_suffix, separator=" | ",
           display_all_categories='no'):
    """
    Creates the main navigation menu of the journal

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

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

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

    navigation = '<div id="navigationMenu">'
    navigation += separator.join([category_prefix + \
                                  category_link + \
                                  category_suffix for category_link \
                                  in categories_links])
    navigation += '</div>'
    return navigation
def 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
Example #8
0
def format_element(bfo):
    """
    Return trackback auto discovery tag if recid != -1, will return "" for recid == -1 like index pages
    """
    html = ""
    if CFG_WEBLINKBACK_TRACKBACK_ENABLED:
        # Retrieve context (journal, issue and category) from URI
        args = parse_url_string(bfo.user_info['uri'])
        recid = args["recid"]

        if recid != -1:
            html = get_trackback_auto_discovery_tag(recid)

    return html
def format_element(bfo):
    """
    Return trackback auto discovery tag if recid != -1, will return "" for recid == -1 like index pages
    """
    html = ""
    if CFG_WEBLINKBACK_TRACKBACK_ENABLED:
        # Retrieve context (journal, issue and category) from URI
        args = parse_url_string(bfo.user_info['uri'])
        recid = args["recid"]

        if recid != -1:
            html = get_trackback_auto_discovery_tag(recid)

    return html
def format_element(bfo,
                   location='782041',
                   degree_unit='c',
                   display_weather_icon='false',
                   weather_icon_only='false'):
    """
    Display the latest weather forecast from Yahoo Weather

    (See http://developer.yahoo.com/weather/)

    @param location: Yahoo location code for the forecast
    @param degree_unit: Degree unit ('f'=Fahrenheit or 'c'=Celsius)
    @param display_weather_icon: if 'true', display weather icon inside the forecasts
    @param weather_icon_only: it 'true' display only the wheater icon (without text)
    """
    if not feedparser_available:
        return ""

    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    cached_filename = "webjournal_widget_weather_%s.rss" % journal_name
    expire_time_filename = "webjournal_widget_weather_%s_RSS_expires" % \
                           journal_name

    out = get_widget_html(yahoo_weather_rss_base_url % \
                          {'location': location, 'degree_unit': degree_unit},
                          cached_filename,
                          expire_time_filename,
                          journal_name)

    if weather_icon_only == 'true':
        try:
            out = '<img alt="" src="%s" align="bottom" />' % \
                  re_image_pattern.findall(out)[0][1]
        except:
            register_exception(req=bfo.req)
            out = ''
    elif display_weather_icon == 'false':
        try:
            out = re.sub(re_image_pattern, "", out)
        except:
            register_exception(req=bfo.req)
            out = ''

    return out
def format_element(bfo, location='782041', degree_unit='c' ,
           display_weather_icon='false', weather_icon_only='false'):
    """
    Display the latest weather forecast from Yahoo Weather

    (See http://developer.yahoo.com/weather/)

    @param location: Yahoo location code for the forecast
    @param degree_unit: Degree unit ('f'=Fahrenheit or 'c'=Celsius)
    @param display_weather_icon: if 'true', display weather icon inside the forecasts
    @param weather_icon_only: it 'true' display only the wheater icon (without text)
    """
    if not feedparser_available:
        return ""

    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    cached_filename = "webjournal_widget_weather_%s.rss" % journal_name
    expire_time_filename = "webjournal_widget_weather_%s_RSS_expires" % \
                           journal_name

    out = get_widget_html(yahoo_weather_rss_base_url % \
                          {'location': location, 'degree_unit': degree_unit},
                          cached_filename,
                          expire_time_filename,
                          journal_name)

    if weather_icon_only == 'true':
        try:
            out = '<img alt="" src="%s" align="bottom" />' % \
                  re_image_pattern.findall(out)[0][1]
        except:
            register_exception(req=bfo.req)
            out = ''
    elif display_weather_icon == 'false':
        try:
            out = re.sub(re_image_pattern, "", out)
        except:
            register_exception(req=bfo.req)
            out = ''

    return out
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"> &gt;&gt; </a>
                        ''' % (article_link)

            # If we should display an image along with the text,
            # prepare it here
            img = ''
            if (number_of_articles_with_image > 0 and \
                   not article_is_new) or display_image_on_index:
                img = _get_feature_image(temp_rec, ln)
                if img != "":
                    # Now we will try to identify image size in order
                    # to resize it in the HTML for a nicer rendering
                    # of the HTML alert in email clients (Outlook wants
                    # both height and width)
                    img_width = None
                    img_height = None
                    small_img_width = None
                    small_img_height = None
                    width_and_height = ''
                    if PIL_imported:
                        try:
                            local_img = os.path.join(CFG_TMPDIR,
                                                     'webjournal_' + \
                                                     ''.join([char for char in img \
                                                              if char.isalnum()]))
                            if len(local_img) > 255:
                                # Shorten to 255 chars
                                local_img = local_img[0:100] + '_' + local_img[156:]
                            if not os.path.exists(local_img):
                                # Too bad, must download entire image for PIL
                                content_type = get_content_type(img)
                                if 'image' in content_type:
                                    (local_img, headers) = urllib.urlretrieve(img, local_img)
                                    img_file = Image.open(local_img) # IOError if not readable image
                                else:
                                    raise IOError('Not an image')
                            else:
                                img_file = Image.open(local_img) # IOError if not readable image
                        except IOError as 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>&nbsp;&nbsp;
                               %(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}
    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, lowest_issue):
    """
    Prints a form that redirects to specified journal issue

    You should specify <code>lowest_issue</code> only if it is not
    possible for WebJourbal to retrieved released issues (eg. when you
    have imported journal articles that have not been released with
    this WebJournal, and therefore not record in the database)

    @param lowest_issue: earliest existing issue. If not given, find out by checking released issues
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    archive_year = args["archive_year"]  # None if not specified
    # Note that you can also access the argument 'archive_search'
    ln = bfo.lang
    _ = gettext_set_language(ln)

    released_issues = get_all_released_issues(journal_name)

    # If we do not have any clue about lowest issue, return nothing
    if not lowest_issue and not released_issues:
        return ''

    # Collect released issues by year
    issues_by_year = {}
    for issue_number in released_issues:
        number, year = issue_number.split('/')
        year = int(year)
        if year not in issues_by_year:
            issues_by_year[year] = []
        issues_by_year[year].append(issue_number)

    # If lowest issue was specified, then it means that some issues
    # are archived even if they have not been released in the DB (that
    # happens when some records have been imported from another
    # system, but not declared as released). We need to 'invent' these
    # issues
    if lowest_issue:
        min_number, min_year = lowest_issue.split('/')
        min_number = int(min_number)
        min_year = int(min_year)

        # If we have some released issues in DB, create up to the
        # first release. Else up to now
        years = issues_by_year.keys()
        if years:
            max_year = min(years)
        else:
            max_year = datetime.datetime.now().year

        max_issues = get_journal_nb_issues_per_year(journal_name)
        for year in range(min_year, max_year + 1):
            for number in range(1, max_issues + 1):
                if year not in issues_by_year:
                    issues_by_year[year] = []
                issue_number = ("%0" + str(len(str(max_issues))) + "i/%i") % \
                               (number, year)
                if not issue_number in issues_by_year[year]:
                    issues_by_year[year].append(issue_number)

    journal_years = issues_by_year.keys()
    journal_years.sort()

    if archive_year is None:
        archive_year = max(journal_years)

    journal_years_issues = issues_by_year[archive_year]
    journal_years_issues.sort(compare_issues)

    # FIXME: Submit the form with id instead of form nr.
    archive_title = "<h2>%s</h2>" % _("Archive")
    archive_form = '''
    <form id="archiveselectform" class="archiveform" action="%(CFG_SITE_URL)s/journal/search" name="searchbyissue" method="get">
        <em>%(select_year_label)s </em>
        <select name="archive_year" onchange="document.searchbyissue.submit();">
            %(select_year_list)s
        </select>
        <br />
        <br />
        <em>%(select_issue_label)s </em>
        <select name="archive_issue">
                %(select_issue_list)s
        </select>
        <input type="hidden" value="%(journal_name)s" name="name" />
        <input type="hidden" value="%(ln)s" name="ln" />
        <input type="submit" value="Go" name="archive_select" />
    </form>
    <hr />
    <form class="archiveform" action="%(CFG_SITE_URL)s/journal/search" name="searchbydate" method="get">
        <em>%(custom_date_label)s <small>(dd/mm/yyyy  -> e.g. 01/03/2006)</small>: </em>
        <input type="text" value="" maxlength="10" size="10" name="archive_date" />
        <input type="hidden" value="%(journal_name)s" name="name" />
        <input type="hidden" value="%(ln)s" name="ln" />
        <input type="submit" value="Go" name="archive_search" />
    </form>
    ''' % {'CFG_SITE_URL': CFG_SITE_URL,
           'journal_name': journal_name,
           'select_year_label': _("Select Year:"),
           'select_year_list' : "\n".join(['<option value="%s" %s>%s</option>' % \
                                           (year,
                                            (year == archive_year) and 'selected="selected"' or "",
                                            year)
                                           for year in journal_years]),
           'select_issue_label': _("Select Issue:"),
           'select_issue_list' : "\n".join(['<option value="%s">%s</option>' % (issue, issue) \
                                            for issue in journal_years_issues]),
           'ln': bfo.lang,
           'custom_date_label': _("Select Date:"),
           }

    return archive_title + archive_form
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):
    """
    Display administration links for this articles when user is an
    editor of the journal
    """
    out = ''
    stats_admin_link = ''
    if bfo.user_info['uri'].startswith('/journal'):
        # Print editing links
        args = parse_url_string(bfo.user_info['uri'])
        journal_name = args["journal_name"]
        editor = False
        if acc_authorize_action(bfo.user_info['uid'], 'cfgwebjournal',
                                name="%s" % journal_name)[0] == 0:
            editor = True
        issue_number = args["issue"]

        if editor:
            recid = bfo.control_field('001')
            (doctype, identifier_element, identifier_field) = \
                      get_journal_submission_params(journal_name)
            if identifier_field.startswith('00'):
                identifier = bfo.control_field(identifier_field)
            else:
                identifier = bfo.field(identifier_field)

            (auth_code, auth_msg) = acc_authorize_action(bfo.user_info, 'runwebstatadmin')
            if not auth_code:
                # User will be allowed to see stats
                stats_admin_link = '''
                <p>
                    <a href="%(CFG_SITE_URL)s/stats/customevent?ids=journals&amp;cols0=articleid&col_value0=%(recid)s&amp;timespan=last+month"> &raquo; statistics</a>
                </p>
                ''' % {'CFG_SITE_URL': CFG_SITE_URL,
                       'recid': recid}

            out += '''
<div style="float:right;margin-left:5px;font-weight:700;">
  <p>
    <a href="%(CFG_SITE_URL)s/submit/direct?%(identifier_element)s=%(identifier)s&amp;sub=MBI%(doctype)s" target="_blank"> &raquo; edit article</a>
  </p>
  <p>
    <a href="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/%(recid)s" target="_blank"> &raquo; record in %(CFG_SITE_NAME_INTL)s</a>
  </p>
  <p>
    <a href="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/regenerate?journal_name=%(journal_name)s&amp;issue=%(issue_number)s"> &raquo; publish changes</a>
  </p>
  %(stats_admin_link)s
</div>''' % {'CFG_SITE_URL': CFG_SITE_URL,
             'CFG_SITE_RECORD': CFG_SITE_RECORD,
             'identifier': identifier,
             'recid': recid,
             'journal_name': journal_name,
             'issue_number': issue_number,
             'doctype': doctype,
             'identifier_element': identifier_element,
             'CFG_SITE_NAME_INTL': CFG_SITE_NAME_INTL.get(bfo.lang,
                                                          CFG_SITE_NAME),
             'stats_admin_link': stats_admin_link}

    return out
Example #16
0
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,
                   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"> &gt;&gt; </a>
                        ''' % (article_link)

            # If we should display an image along with the text,
            # prepare it here
            img = ''
            if (number_of_articles_with_image > 0 and \
                   not article_is_new) or display_image_on_index:
                img = _get_feature_image(temp_rec, ln)
                if img != "":
                    # Now we will try to identify image size in order
                    # to resize it in the HTML for a nicer rendering
                    # of the HTML alert in email clients (Outlook wants
                    # both height and width)
                    img_width = None
                    img_height = None
                    small_img_width = None
                    small_img_height = None
                    width_and_height = ''
                    if PIL_imported:
                        try:
                            local_img = os.path.join(CFG_TMPDIR,
                                                     'webjournal_' + \
                                                     ''.join([char for char in img \
                                                              if char.isalnum()]))
                            if len(local_img) > 255:
                                # Shorten to 255 chars
                                local_img = local_img[0:100] + '_' + local_img[
                                    156:]
                            if not os.path.exists(local_img):
                                # Too bad, must download entire image for PIL
                                content_type = get_content_type(img)
                                if 'image' in content_type:
                                    (local_img, headers) = urllib.urlretrieve(
                                        img, local_img)
                                    img_file = Image.open(
                                        local_img
                                    )  # IOError if not readable image
                                else:
                                    raise IOError('Not an image')
                            else:
                                img_file = Image.open(
                                    local_img)  # IOError if not readable image
                        except IOError as 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>&nbsp;&nbsp;
                               %(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
                }
    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 = bfo.lang
    _ = 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:
                        try:
                            title = temp_rec.field('245__a')
                        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_element(bfo, display_date='yes', display_issue_number='yes',
           estimate_release_date='No', granularity='',
           group_issues_date='yes', display_month='long',
           display_week_day='long'):
    """
    Returns the string used for the issue number in the format:<br/>
    Issue No.<is1>-<is2>/<year> - <date>, <br/>
    e.g. Issue No.32-33/2007 – Tuesday 6 August 2007

    if <code>estimate_release_date</code> is set to <code>yes</code>,
    a 'theoretical' release date is shown instead of the release date:
    if issue if released on Friday, display next week date. Also if
    journal has not been released, display an approximative release
    date (based on history and config)

    @param display_date: if 'yes', display issue date
    @param display_issue_number: if 'yes', display issue date
    @param estimate_release_date: if 'yes', display the theoretical release date
    @param granularity: <code>day</code>, <code>week</code> or <code>month</code>
    @param group_issues_date: if 'yes' and issue are grouped, display first issue date of the group
    @param display_month: type of display for month: 'short' ('Jan', 'Feb', etc.) or 'long' ('January', 'February', etc.)
    @param display_week_day: Can display day of the week ('Monday', etc.). Parameter can be 'short' ('Mon', 'Tue' etc), 'long' ('Monday', 'Tuesday', etc.) or '' (no value displayed)
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    issue_number = args["issue"]
    ln = bfo.lang
    _ = gettext_set_language(ln)

    try:
        issue_display = get_issue_number_display(issue_number,
                                                 journal_name,
                                                 ln)
    except InvenioWebJournalJournalIdNotFoundDBError as e:
        return e.user_box()
    except Exception as e:
        issue_display = issue_number

    issues = issue_display.split("/")[0]
    year = issue_display.split("/")[1]
    week_numbers = issues.split("-")

    if group_issues_date.lower() == 'yes':
        # Get release time of this issue (do not consider issue
        # "updates": take the earliest issue number of this group of
        # issues)
        grouped_issues = get_grouped_issues(journal_name, issue_number)
        if grouped_issues:
            issue_number = grouped_issues[0]

    if estimate_release_date.lower() == 'yes':
        # Get theoretical release date
        if granularity.lower() == 'day':
            granularity = DAILY
        elif granularity.lower() == 'week':
            granularity = WEEKLY
        elif granularity.lower() == 'month':
            granularity = MONTHLY
        else:
            granularity = None
        issue_release_time = issue_to_datetime(issue_number,
                                               journal_name,
                                               granularity)
    else:
        issue_release_time = get_release_datetime(issue_number,
                                                  journal_name)

    # Get a nice internationalized representation of this date
    date_text = ''
    if issue_release_time:
        if display_week_day:
            date_text = get_i18n_day_name(issue_release_time.isoweekday(),
                                          display_week_day,
                                          ln) + ' '
        month = get_i18n_month_name(issue_release_time.month,
                                    display_month,
                                    ln=ln)
        date_text += issue_release_time.strftime("%d " + month + " %Y").lstrip('0')

    issue_url = make_journal_url(bfo.user_info['uri'],
                                 {'recid': '',
                                  'ln': bfo.lang,
                                  'category': ''})
    out = '<a class="issue" href="%s">' % issue_url
    if display_issue_number.lower() == 'yes':
        out += _("Issue No.") + ' ' + issue_display + ' - '

    if display_date.lower() == 'yes':
        out += date_text

    out += '</a>'

    return out
Example #20
0
def format_element(bfo, only_public_records=1, sites="linkedin,twitter,facebook,google,delicious,sciencewise"):
    """
    Return a snippet of JavaScript needed for displaying a bookmark toolbar

    @param only_public_records: if set to 1 (the default), prints the box only
        if the record is public (i.e. if it belongs to the root colletion and is
        accessible to the world).

    @param sites: which sites to enable (default is 'linkedin,twitter,facebook,google,delicious,sciencewise'). This should be a
        comma separated list of strings.
        Valid values are available on:
            <http://keith-wood.name/bookmark.html#sites>
        Note that 'sciencewise' is an ad-hoc service that will be displayed
        only in case the record has an arXiv reportnumber and will always
        be displayed last.
    """
    if int(only_public_records) and not record_public_p(bfo.recID):
        return ""

    sitelist = sites.split(',')
    sitelist = [site.strip().lower() for site in sitelist]

    sciencewise = False
    if 'sciencewise' in sitelist:
        sciencewise = True
        sitelist.remove('sciencewise')

    sites_js = ", ".join("'%s'" % site for site in sitelist)

    title = bfo.field('245__a')
    description = bfo.field('520__a')

    sciencewise_script = ""
    if sciencewise:
        reportnumber = get_arxiv_reportnumber(bfo)
        sciencewise_url = ""
        if reportnumber:
            sciencewise_url = create_sciencewise_url(reportnumber)
        if not sciencewise_url and CFG_CERN_SITE:
            sciencewise_url = create_sciencewise_url(bfo.recID, cds=True)
        if sciencewise_url:
            sciencewise_script = """\
$.bookmark.addSite('sciencewise', 'ScienceWise.info', '%(siteurl)s/img/sciencewise.png', 'en', 'bookmark', '%(url)s');
$('#bookmark_sciencewise').bookmark({sites: ['sciencewise']});
""" % {
                'siteurl': CFG_SITE_URL,
                'url': sciencewise_url.replace("'", r"\'"),
            }

    url = '%(siteurl)s/%(record)s/%(recid)s' % \
          {'recid': bfo.recID,
           'record': CFG_SITE_RECORD,
           'siteurl': CFG_SITE_URL}

    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    if journal_name and \
       (journal_name in [info.get('journal_name', '') for info in get_journals_ids_and_names()]):
        # We are displaying a WebJournal article: URL is slightly different
        url = make_journal_url(bfo.user_info['uri'])

    return """\
<!-- JQuery Bookmark Button BEGIN -->
<div id="bookmark"></div><div id="bookmark_sciencewise"></div>
<style type="text/css">
    #bookmark_sciencewise, #bookmark { float: left; }
    #bookmark_sciencewise li { padding: 2px; width: 25px}
    #bookmark_sciencewise ul, #bookmark ul { list-style-image: none; }
</style>
<script type="text/javascript" src="%(siteurl)s/js/jquery.bookmark.min.js"></script>
<style type="text/css">@import "%(siteurl)s/css/jquery.bookmark.css";</style>
<script type="text/javascript">// <![CDATA[
    %(sciencewise)s
    $('#bookmark').bookmark({
        sites: [%(sites_js)s],
        icons: '%(siteurl)s/img/bookmarks.png',
        url: '%(url)s',
        addEmail: true,
        title: "%(title)s",
        description: "%(description)s"
    });
// ]]>
</script>
<!-- JQuery Bookmark Button END -->
""" % {
        'siteurl': CFG_SITE_URL,
        'sciencewise': sciencewise_script,
        'title': escape_javascript_string(title,
                                          escape_for_html=False,
                                          escape_CDATA=True),
        'description': escape_javascript_string(description,
                                                escape_for_html=False,
                                                escape_CDATA=True),
        'sites_js': sites_js,
        'url': url,
    }
Example #21
0
def format_element(
        bfo,
        only_public_records=1,
        sites="linkedin,twitter,facebook,google,delicious,sciencewise"):
    """Return a snippet of JavaScript needed for displaying a bookmark toolbar.

    :param only_public_records: if set to 1 (the default), prints the box only
        if the record is public (i.e. if it belongs to the root colletion and
        is accessible to the world).

    :param sites: which sites to enable (default is
        'linkedin,twitter,facebook,google,delicious,sciencewise').
        This should be a comma separated list of strings.
        Valid values are available on:
            <http://keith-wood.name/bookmark.html#sites>
        Note that 'sciencewise' is an ad-hoc service that will be displayed
        only in case the record has an arXiv reportnumber and will always
        be displayed last.
    """
    if int(only_public_records) and \
            bfo.recID not in get_all_restricted_recids():
        return ""

    sitelist = sites.split(',')
    sitelist = [site.strip().lower() for site in sitelist]

    sciencewise = False
    if 'sciencewise' in sitelist:
        sciencewise = True
        sitelist.remove('sciencewise')

    sites_js = ", ".join("'%s'" % site for site in sitelist)

    title = bfo.field('245__a')
    description = bfo.field('520__a')

    sciencewise_script = ""
    if sciencewise:
        reportnumber = get_arxiv_reportnumber(bfo)
        sciencewise_url = ""
        if reportnumber:
            sciencewise_url = create_sciencewise_url(reportnumber)
        if not sciencewise_url and CFG_CERN_SITE:
            sciencewise_url = create_sciencewise_url(bfo.recID, cds=True)
        if sciencewise_url:
            sciencewise_script = """\
$.bookmark.addSite('sciencewise', 'ScienceWise.info', '%(siteurl)s/img/sciencewise.png', 'en', 'bookmark', '%(url)s');
$('#bookmark_sciencewise').bookmark({sites: ['sciencewise']});
""" % {
                'siteurl': CFG_SITE_URL,
                'url': sciencewise_url.replace("'", r"\'"),
            }

    url = '%(siteurl)s/%(record)s/%(recid)s' % \
          {'recid': bfo.recID,
           'record': CFG_SITE_RECORD,
           'siteurl': CFG_BASE_URL}

    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    if journal_name and \
       (journal_name in [info.get('journal_name', '') for info in get_journals_ids_and_names()]):
        # We are displaying a WebJournal article: URL is slightly different
        url = make_journal_url(bfo.user_info['uri'])

    return """\
<!-- JQuery Bookmark Button BEGIN -->
<div id="bookmark"></div><div id="bookmark_sciencewise"></div>
<style type="text/css">
    #bookmark_sciencewise, #bookmark { float: left; }
    #bookmark_sciencewise li { padding: 2px; width: 25px}
    #bookmark_sciencewise ul, #bookmark ul { list-style-image: none; }
</style>
<script type="text/javascript" src="%(siteurl)s/vendors/jquery.bookmark/jquery.bookmark.min.js"></script>
<style type="text/css">@import "%(siteurl)s/vendors/jquery.bookmark/jquery.bookmark.css";</style>
<script type="text/javascript">// <![CDATA[
    %(sciencewise)s
    $('#bookmark').bookmark({
        sites: [%(sites_js)s],
        icons: '%(siteurl)s/vendors/jquery.bookmark/bookmarks.png',
        url: '%(url)s',
        addEmail: true,
        title: "%(title)s",
        description: "%(description)s"
    });
// ]]>
</script>
<!-- JQuery Bookmark Button END -->
""" % {
        'siteurl':
        CFG_BASE_URL,
        'sciencewise':
        sciencewise_script,
        'title':
        escape_javascript_string(
            title, escape_for_html=False, escape_CDATA=True),
        'description':
        escape_javascript_string(
            description, escape_for_html=False, escape_CDATA=True),
        'sites_js':
        sites_js,
        'url':
        url,
    }
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, 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
Example #24
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 = 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
Example #25
0
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, lowest_issue):
    """
    Prints a form that redirects to specified journal issue

    You should specify <code>lowest_issue</code> only if it is not
    possible for WebJourbal to retrieved released issues (eg. when you
    have imported journal articles that have not been released with
    this WebJournal, and therefore not record in the database)

    @param lowest_issue: earliest existing issue. If not given, find out by checking released issues
    """
    args = parse_url_string(bfo.user_info["uri"])
    journal_name = args["journal_name"]
    archive_year = args["archive_year"]  # None if not specified
    # Note that you can also access the argument 'archive_search'
    ln = bfo.lang
    _ = gettext_set_language(ln)

    released_issues = get_all_released_issues(journal_name)

    # If we do not have any clue about lowest issue, return nothing
    if not lowest_issue and not released_issues:
        return ""

    # Collect released issues by year
    issues_by_year = {}
    for issue_number in released_issues:
        number, year = issue_number.split("/")
        year = int(year)
        if year not in issues_by_year:
            issues_by_year[year] = []
        issues_by_year[year].append(issue_number)

    # If lowest issue was specified, then it means that some issues
    # are archived even if they have not been released in the DB (that
    # happens when some records have been imported from another
    # system, but not declared as released). We need to 'invent' these
    # issues
    if lowest_issue:
        min_number, min_year = lowest_issue.split("/")
        min_number = int(min_number)
        min_year = int(min_year)

        # If we have some released issues in DB, create up to the
        # first release. Else up to now
        years = issues_by_year.keys()
        if years:
            max_year = min(years)
        else:
            max_year = datetime.datetime.now().year

        max_issues = get_journal_nb_issues_per_year(journal_name)
        for year in range(min_year, max_year + 1):
            for number in range(1, max_issues + 1):
                if year not in issues_by_year:
                    issues_by_year[year] = []
                issue_number = ("%0" + str(len(str(max_issues))) + "i/%i") % (number, year)
                if not issue_number in issues_by_year[year]:
                    issues_by_year[year].append(issue_number)

    journal_years = issues_by_year.keys()
    journal_years.sort()

    if archive_year is None:
        archive_year = max(journal_years)

    journal_years_issues = issues_by_year[archive_year]
    journal_years_issues.sort(compare_issues)

    # FIXME: Submit the form with id instead of form nr.
    archive_title = "<h2>%s</h2>" % _("Archive")
    archive_form = """
    <form id="archiveselectform" class="archiveform" action="%(CFG_SITE_URL)s/journal/search" name="searchbyissue" method="get">
        <em>%(select_year_label)s </em>
        <select name="archive_year" onchange="document.searchbyissue.submit();">
            %(select_year_list)s
        </select>
        <br />
        <br />
        <em>%(select_issue_label)s </em>
        <select name="archive_issue">
                %(select_issue_list)s
        </select>
        <input type="hidden" value="%(journal_name)s" name="name" />
        <input type="hidden" value="%(ln)s" name="ln" />
        <input type="submit" value="Go" name="archive_select" />
    </form>
    <hr />
    <form class="archiveform" action="%(CFG_SITE_URL)s/journal/search" name="searchbydate" method="get">
        <em>%(custom_date_label)s <small>(dd/mm/yyyy  -> e.g. 01/03/2006)</small>: </em>
        <input type="text" value="" maxlength="10" size="10" name="archive_date" />
        <input type="hidden" value="%(journal_name)s" name="name" />
        <input type="hidden" value="%(ln)s" name="ln" />
        <input type="submit" value="Go" name="archive_search" />
    </form>
    """ % {
        "CFG_SITE_URL": CFG_SITE_URL,
        "journal_name": journal_name,
        "select_year_label": _("Select Year:"),
        "select_year_list": "\n".join(
            [
                '<option value="%s" %s>%s</option>'
                % (year, (year == archive_year) and 'selected="selected"' or "", year)
                for year in journal_years
            ]
        ),
        "select_issue_label": _("Select Issue:"),
        "select_issue_list": "\n".join(
            ['<option value="%s">%s</option>' % (issue, issue) for issue in journal_years_issues]
        ),
        "ln": bfo.lang,
        "custom_date_label": _("Select Date:"),
    }

    return archive_title + archive_form
Example #27
0
def format_element(bfo):
    """
    Display administration links for this articles when user is an
    editor of the journal
    """
    out = ''
    stats_admin_link = ''
    if bfo.user_info['uri'].startswith('/journal'):
        # Print editing links
        args = parse_url_string(bfo.user_info['uri'])
        journal_name = args["journal_name"]
        editor = False
        if acc_authorize_action(bfo.user_info['uid'],
                                'cfgwebjournal',
                                name="%s" % journal_name)[0] == 0:
            editor = True
        issue_number = args["issue"]

        if editor:
            recid = bfo.control_field('001')
            (doctype, identifier_element, identifier_field) = \
                      get_journal_submission_params(journal_name)
            if identifier_field.startswith('00'):
                identifier = bfo.control_field(identifier_field)
            else:
                identifier = bfo.field(identifier_field)

            (auth_code,
             auth_msg) = acc_authorize_action(bfo.user_info, 'runwebstatadmin')
            if not auth_code:
                # User will be allowed to see stats
                stats_admin_link = '''
                <p>
                    <a href="%(CFG_SITE_URL)s/stats/customevent?ids=journals&amp;cols0=articleid&col_value0=%(recid)s&amp;timespan=last+month"> &raquo; statistics</a>
                </p>
                ''' % {
                    'CFG_SITE_URL': CFG_SITE_URL,
                    'recid': recid
                }

            out += '''
<div style="float:right;margin-left:5px;font-weight:700;">
  <p>
    <a href="%(CFG_SITE_URL)s/submit/direct?%(identifier_element)s=%(identifier)s&amp;sub=MBI%(doctype)s" target="_blank"> &raquo; edit article</a>
  </p>
  <p>
    <a href="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/%(recid)s" target="_blank"> &raquo; record in %(CFG_SITE_NAME_INTL)s</a>
  </p>
  <p>
    <a href="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/regenerate?journal_name=%(journal_name)s&amp;issue=%(issue_number)s"> &raquo; publish changes</a>
  </p>
  %(stats_admin_link)s
</div>''' % {
                'CFG_SITE_URL':
                CFG_SITE_URL,
                'CFG_SITE_RECORD':
                CFG_SITE_RECORD,
                'identifier':
                identifier,
                'recid':
                recid,
                'journal_name':
                journal_name,
                'issue_number':
                issue_number,
                'doctype':
                doctype,
                'identifier_element':
                identifier_element,
                'CFG_SITE_NAME_INTL':
                CFG_SITE_NAME_INTL.get(bfo.lang, CFG_SITE_NAME),
                'stats_admin_link':
                stats_admin_link
            }

    return out
Example #28
0
def format_element(bfo, display_date='yes', display_issue_number='yes',
           estimate_release_date='No', granularity='',
           group_issues_date='yes', display_month='long',
           display_week_day='long'):
    """
    Returns the string used for the issue number in the format:<br/>
    Issue No.<is1>-<is2>/<year> - <date>, <br/>
    e.g. Issue No.32-33/2007 – Tuesday 6 August 2007

    if <code>estimate_release_date</code> is set to <code>yes</code>,
    a 'theoretical' release date is shown instead of the release date:
    if issue if released on Friday, display next week date. Also if
    journal has not been released, display an approximative release
    date (based on history and config)

    @param display_date: if 'yes', display issue date
    @param display_issue_number: if 'yes', display issue date
    @param estimate_release_date: if 'yes', display the theoretical release date
    @param granularity: <code>day</code>, <code>week</code> or <code>month</code>
    @param group_issues_date: if 'yes' and issue are grouped, display first issue date of the group
    @param display_month: type of display for month: 'short' ('Jan', 'Feb', etc.) or 'long' ('January', 'February', etc.)
    @param display_week_day: Can display day of the week ('Monday', etc.). Parameter can be 'short' ('Mon', 'Tue' etc), 'long' ('Monday', 'Tuesday', etc.) or '' (no value displayed)
    """
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    issue_number = args["issue"]
    ln = bfo.lang
    _ = gettext_set_language(ln)

    try:
        issue_display = get_issue_number_display(issue_number,
                                                 journal_name,
                                                 ln)
    except InvenioWebJournalJournalIdNotFoundDBError as e:
        return e.user_box()
    except Exception as e:
        issue_display = issue_number

    issues = issue_display.split("/")[0]
    year = issue_display.split("/")[1]
    week_numbers = issues.split("-")

    if group_issues_date.lower() == 'yes':
        # Get release time of this issue (do not consider issue
        # "updates": take the earliest issue number of this group of
        # issues)
        grouped_issues = get_grouped_issues(journal_name, issue_number)
        if grouped_issues:
            issue_number = grouped_issues[0]

    if estimate_release_date.lower() == 'yes':
        # Get theoretical release date
        if granularity.lower() == 'day':
            granularity = DAILY
        elif granularity.lower() == 'week':
            granularity = WEEKLY
        elif granularity.lower() == 'month':
            granularity = MONTHLY
        else:
            granularity = None
        issue_release_time = issue_to_datetime(issue_number,
                                               journal_name,
                                               granularity)
    else:
        issue_release_time = get_release_datetime(issue_number,
                                                  journal_name)

    # Get a nice internationalized representation of this date
    date_text = ''
    if issue_release_time:
        if display_week_day:
            date_text = get_i18n_day_name(issue_release_time.isoweekday(),
                                          display_week_day,
                                          ln) + ' '
        month = get_i18n_month_name(issue_release_time.month,
                                    display_month,
                                    ln=ln)
        date_text += issue_release_time.strftime("%d " + month + " %Y").lstrip('0')

    issue_url = make_journal_url(bfo.user_info['uri'],
                                 {'recid': '',
                                  'ln': bfo.lang,
                                  'category': ''})
    out = '<a class="issue" href="%s">' % issue_url
    if display_issue_number.lower() == 'yes':
        out += _("Issue No.") + ' ' + issue_display + ' - '

    if display_date.lower() == 'yes':
        out += date_text

    out += '</a>'

    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 = bfo.lang
    _ = 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:
                        try:
                            title = temp_rec.field('245__a')
                        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