Пример #1
0
    def tmpl_papers_box(self, req, pubs, bibauthorid_data, num_downloads, ln, add_box=True, loading=False):
        _ = gettext_set_language(ln)
        if not loading and pubs:
            ib_pubs = intbitset(pubs)
            if bibauthorid_data["cid"]:
                baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"])
            elif bibauthorid_data["pid"] > -1:
                baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"])
            baid_query = baid_query + " "

            rec_query = baid_query
            searchstr = create_html_link(websearch_templates.build_search_url(p=rec_query),
                                         {}, "<strong>" + "All papers (" + str(len(pubs)) + ")" + "</strong>",)

            line2 = searchstr

            if CFG_BIBRANK_SHOW_DOWNLOAD_STATS and num_downloads:
                line2 += " (" + _("downloaded") + " "
                line2 += str(num_downloads) + " " + _("times") + ")"

            if CFG_INSPIRE_SITE:
                CFG_COLLS = ['Book',
                             'ConferencePaper',
                             'Introductory',
                             'Lectures',
                             'Preprint',
                             'Published',
                             'Review',
                             'Thesis']
            else:
                CFG_COLLS = ['Article',
                             'Book',
                             'Preprint', ]
            collsd = {}
            for coll in CFG_COLLS:
                coll_papers = list(ib_pubs & intbitset(perform_request_search(rg=0, f="collection", p=coll)))
                if coll_papers:
                    collsd[coll] = coll_papers
            colls = collsd.keys()
            colls.sort(lambda x, y: cmp(len(collsd[y]), len(collsd[x]))) # sort by number of papers
            for coll in colls:
                rec_query = baid_query + 'collection:' + wrap_author_name_in_quotes_if_needed(coll)
                line2 += "<br />" + create_html_link(websearch_templates.build_search_url(p=rec_query),
                                                                           {}, coll + " (" + str(len(collsd[coll])) + ")",)

        elif not pubs and not loading:
            line2 = _("No Papers")

        elif loading:
            line2 = self.loading_html()

        else:
            line2 = 'This is a bug and should be corrected'

        if not add_box:
            return line2
        line1 = "<strong>" + _("Papers") + "</strong>"
        papers_box = self.tmpl_print_searchresultbox("papers", line1, line2)
        return papers_box
Пример #2
0
def print_timeout(req, lang, engine, name, url):
    """Print info line for timeout."""
    _ = gettext_set_language(lang)
    req.write('<a name="%s"></a>' % get_link_name(engine.name))
    print_info_line(req,
                    create_html_link(url, {}, name, {}, False, False),
                    '',
                    _('Search timed out.'))
    message = _("The external search engine has not responded in time. You can check its results here:")
    req.write(message + ' ' + create_html_link(url, {}, name, {}, False, False) + '<br />')
Пример #3
0
def print_timeout(req, lang, engine, name, url):
    """Print info line for timeout."""
    _ = gettext_set_language(lang)
    req.write('<a name="%s"></a>' % get_link_name(engine.name))
    print_info_line(req, create_html_link(url, {}, name, {}, False, False), '',
                    _('Search timed out.'))
    message = _(
        "The external search engine has not responded in time. You can check its results here:"
    )
    req.write(message + ' ' +
              create_html_link(url, {}, name, {}, False, False) + '<br />')
Пример #4
0
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    CFG_SITE_URL = current_app.config['CFG_SITE_URL']

    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    linkattrd = {}
    if style != '':
        linkattrd['style'] = style
    if css_class != '':
        linkattrd['class'] = css_class

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label,
                            linkattrd=linkattrd)
Пример #5
0
def format_element(bfo, style, css_class):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    @param css_class: the CSS class to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(current_app.config['CFG_SITE_SECURE_URL'] +
               '/%s/edit/?ln=%s#state=edit&recid=%s' % (current_app.config['CFG_SITE_RECORD'], bfo.lang, str(bfo.recID)),
               {},
               link_label="<i class=\"icon-pencil\"></i> %s" % _("Edit"),
               linkattrd=linkattrd)

    return out
Пример #6
0
def format_element(bfo, style):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style

        out += create_html_link(CFG_BASE_URL + '/%s/managedocfiles' % CFG_SITE_RECORD,
                                urlargd={'ln': bfo.lang,
                                         'recid': str(bfo.recID)},
                                link_label=_("Manage Files of This Record"),
                                linkattrd=linkattrd)
    return out
Пример #7
0
def format_element(bfo, style, css_class):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(
            current_app.config['CFG_SITE_SECURE_URL'] +
            '/%s/managedocfiles' % current_app.config['CFG_SITE_RECORD'],
            urlargd={
                'ln': bfo.lang,
                'recid': str(bfo.recID)
            },
            link_label="""<i class="icon-file"></i> %s""" % _("Manage Files"),
            linkattrd=linkattrd)
    return out
Пример #8
0
def format_element(bfo, style, html_class='', link_label=None):
    """Print a link to BibEdit, if authorization is granted.

    :param style: the CSS style to be applied to the link.
    :param html_class: the class attribute to be applied to the link.
    :param link_label: Localized link label. Default: "Edit This Record"
                       (or its translated variant).
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if html_class != '':
            linkattrd['class'] = html_class
        out += create_html_link(
            CFG_BASE_URL + '/%s/edit/?ln=%s#state=edit&recid=%s' %
            (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)), {},
            link_label=link_label or _('Edit This Record'),
            linkattrd=linkattrd)

    return out
Пример #9
0
def format_element(bfo, style, css_class):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    @param css_class: the CSS class to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(current_app.config['CFG_SITE_URL'] +
               '/%s/edit/?ln=%s#state=edit&recid=%s' % (current_app.config['CFG_SITE_RECORD'], bfo.lang, str(bfo.recID)),
               {},
               link_label="<i class=\"icon-pencil\"></i> %s" % _("Edit"),
               linkattrd=linkattrd)

    return out
Пример #10
0
def format_element(bfo, style, html_class='', link_label=None):
    """Print a link to BibEdit, if authorization is granted.

    :param style: the CSS style to be applied to the link.
    :param html_class: the class attribute to be applied to the link.
    :param link_label: Localized link label. Default: "Edit This Record"
                       (or its translated variant).
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if html_class != '':
            linkattrd['class'] = html_class
        out += create_html_link(
            CFG_BASE_URL +
            '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang,
                                                     str(bfo.recID)),
            {},
            link_label=link_label or _('Edit This Record'),
            linkattrd=linkattrd)

    return out
Пример #11
0
def format_element(bfo, style, css_class):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(current_app.config['CFG_SITE_URL'] + '/%s/managedocfiles' % current_app.config['CFG_SITE_RECORD'],
                         urlargd={'ln': bfo.lang,
                                  'recid': str(bfo.recID)},
                         link_label= """<i class="icon-file"></i> %s""" % _("Manage Files"),
                         linkattrd=linkattrd)
    return out
Пример #12
0
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    CFG_SITE_URL = current_app.config['CFG_SITE_URL']

    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    linkattrd = {}
    if style != '':
        linkattrd['style'] = style
    if css_class != '':
        linkattrd['class'] = css_class

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label,
                            linkattrd=linkattrd)
Пример #13
0
    def tmpl_numpaperstitle(self, bibauthorid_data, pubs):
        if bibauthorid_data["cid"]:
            baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"])
        else:
            baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"])

        pubs_to_papers_link = create_html_link(websearch_templates.build_search_url(p=baid_query), {}, str(len(pubs)))

        return  '(%s papers)' % pubs_to_papers_link
Пример #14
0
def format_element(bfo, width="", caption="yes", max="-1"):
    """
    Display image of the plot if we are in selected plots collections

    @param width: the width of the returned image (Eg: '100px')
    @param caption: display the captions or not?
    @param max: the maximum number of plots to display (-1 is all plots)
    """
    ## To achieve this, we take the pngs associated with this document

    img_files = []
    max = int(max)

    bibarchive = BibRecDocs(bfo.recID)

    if width != "":
        width = 'width="%s"' % width

    for doc in bibarchive.list_bibdocs():
        for _file in doc.list_latest_files():
            if _file.get_type() == "Plot":

                try:
                    caption_text = _file.get_description()[5:]
                    index = int(_file.get_description()[:5])
                    img_location = _file.get_url()
                except:
                    # FIXME: we have hit probably a plot context file,
                    # so ignore this document; but it would be safer
                    # to check subformat type, so that we don't mask
                    # other eventual errors here.
                    continue

                img = '<img src="%s" title="%s" %s/>' % \
                      (img_location, caption_text, width)

                link = create_html_link(urlbase='%s/%s/%s/plots#%d' %
                                                (CFG_SITE_URL, CFG_SITE_RECORD, bfo.recID,\
                                                 index),
                                        urlargd={},
                                        link_label=img)

                img_files.append((index, link))

    img_files = sorted(img_files, key=lambda x: x[0])
    if max > 0:
        img_files = img_files[:max]

    for index in range(len(img_files)):
        img_files[index] = img_files[index][1]

    if len(img_files) == 0:
        return ''

    return '<div style="overflow-x:scroll;width=100%;white-space:nowrap">' +\
           " ".join(img_files) + '</div>'
Пример #15
0
 def print_kw(kwtuples):
     keywstr = ""
     for (kw, freq) in kwtuples:
         if keywstr:
             keywstr += '<br>'
         rec_query = baid_query + ' keyword:"' + kw + '" '
         searchstr = kw + ' (' + create_html_link(websearch_templates.build_search_url(p=rec_query),
                                                            {}, str(freq),) + ')'
         keywstr = keywstr + " " + searchstr
     return keywstr
Пример #16
0
 def print_collabs(collabs):
     collabstr = ""
     for (cl, freq) in collabs:
         if collabstr:
             collabstr += '<br>'
         rec_query = baid_query + ' collaboration:"' + cl + '"'
         searchstr = cl + ' (' + create_html_link(websearch_templates.build_search_url(p=rec_query),
                                                            {}, str(freq),) + ')'
         collabstr = collabstr + " " + searchstr
     return collabstr
Пример #17
0
def perform_request_touchset(oai_set_id=None, ln=CFG_SITE_LANG, func=0):
    """creates html form to touch an OAI set"""
    _ = gettext_set_language(ln)
    out = ""

    if oai_set_id:
        oai_set = get_oai_set(oai_set_id)
        if not oai_set:
            return "ERROR: oai_set_id %s seems invalid" % oai_set_id

        oai_set = get_oai_set(oai_set_id)
        oai_set_spec = oai_set[0][1]
        oai_set_name = oai_set[0][2]
        oai_set_collection = oai_set[0][3]
        oai_set_p1 = oai_set[0][5]
        oai_set_f1 = oai_set[0][6]
        oai_set_m1 = oai_set[0][7]
        oai_set_p2 = oai_set[0][8]
        oai_set_f2 = oai_set[0][9]
        oai_set_m2 = oai_set[0][10]
        oai_set_p3 = oai_set[0][11]
        oai_set_f3 = oai_set[0][12]
        oai_set_m3 = oai_set[0][13]
        oai_set_op1 = oai_set[0][14]
        oai_set_op2 = oai_set[0][15]

        if func in ["0", 0]:

            if oai_set:
                question = _(
                    """Do you want to touch the OAI set %(x_name)s? Note that this will force all clients to re-harvest the whole set.""",
                    x_name=cgi.escape(oai_set_spec))
                text = oaiharvest_templates.tmpl_print_info(ln, question)
                out += createform(action="touchset",
                                  text=text,
                                  button="Touch",
                                  oai_set_id=oai_set_id,
                                  func=1)
            else:
                return oaiharvest_templates.tmpl_print_info(
                    ln, _("OAI set does not exist."))
        elif func in ["1", 1]:
            touch_oai_set(oai_set_spec)
            out += oaiharvest_templates.tmpl_print_info(
                ln,
                _("OAI set %(x_name)s touched.",
                  x_name=cgi.escape(oai_set_spec)))
    out += "<br />"
    out += "<br /><br />"
    out += create_html_link(urlbase=oai_rep_admin_url + \
                "/index",
                urlargd={'ln': ln},
                link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #18
0
    def detailed_record_container_bottom(self, recid, tabs, ln=CFG_SITE_LANG,
                                         show_similar_rec_p=True,
                                         creationdate=None,
                                         modificationdate=None, show_short_rec_p=True):
        """Prints the box displayed in detailed records pages, with tabs at the top.

        Returns content as it is if the number of tabs for this record
        is smaller than 2

           Parameters:

         - recid *int* - the id of the displayed record
         - tabs ** - the tabs displayed at the top of the box.
         - ln *string* - the language of the page in which the box is displayed
         - show_similar_rec_p *bool* print 'similar records' link in the box
         - creationdate *string* - the creation date of the displayed record
         - modificationdate *string* - the last modification date of the displayed record
         - show_short_rec_p *boolean* - prints a very short version of the record as reminder.
        """
        # If no tabs, returns nothing
        if len(tabs) <= 1:
            return ''

        # load the right message language
        _ = gettext_set_language(ln)

        similar = ""

        if show_similar_rec_p and not CFG_INSPIRE_SITE:
            similar = create_html_link(
                websearch_templates.build_search_url(p='recid:%d' % \
                                                     recid,
                                                     rm='wrd',
                                                     ln=ln),
                {}, _("Similar records"),{'class': "moreinfo"})

        out = """
            <div class="bottom-left-folded">%(dates)s</div>
            <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;">
                <span class="moreinfo" style="margin-right:10px;">%(similar)s</span></div>
          </div>
      </div>
    </div>
    <br/>
    """ % {'similar' : similar,
           'dates' : creationdate and '<div class="recordlastmodifiedbox" style="position:relative;margin-left:1px">&nbsp;%(dates)s</div>' % {
                'dates': _("Record created %(x_date_creation)s, last modified %(x_date_modification)s",
                           x_date_creation=creationdate,
                           x_date_modification=modificationdate),
                } or ''
           }

        return out
Пример #19
0
 def tmpl_navtrail(self, ln=CFG_SITE_LANG, title=""):
     """
     display the navtrail, e.g.:
     Your account > Your messages > title
     @param title: the last part of the navtrail. Is not a link
     @param ln: language
     return html formatted navtrail
     """
     _ = gettext_set_language(ln)
     nav_h1 = create_html_link(CFG_SITE_URL + '/youraccount/display',
                               {'ln': ln},
                               _("Your Account"),
                               {'class': 'navtrail'})
     nav_h2 = ""
     if (title != ""):
         nav_h2 += create_html_link(CFG_SITE_URL + '/yourmessages/display',
                                    {'ln': ln},
                                    _("Your Messages"),
                                    {'class': 'navtrail'})
         return nav_h1 + ' &gt; ' + nav_h2
     return nav_h1
def format_element(bfo, category_prefix, category_suffix, separator=" | ",
           display_all_categories='no'):
    """
    Creates the main navigation menu of the journal

    @param category_prefix: value printed before each category
    @param category_suffix: value printed after each category
    @param separator: value printed between each category
    @param display_all_categories: if 'yes', show categories even when there is no corresponding article
    """
    # Retrieve context (journal, issue and category) from URI
    args = parse_url_string(bfo.user_info['uri'])
    journal_name = args["journal_name"]
    selected_category = args["category"]
    this_issue_number = args["issue"]
    ln = 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
Пример #22
0
def perform_request_addset(oai_set_name='',
                           oai_set_spec='',
                           oai_set_collection='',
                           oai_set_description='',
                           oai_set_p1='',
                           oai_set_f1='',
                           oai_set_m1='',
                           oai_set_p2='',
                           oai_set_f2='',
                           oai_set_m2='',
                           oai_set_p3='',
                           oai_set_f3='',
                           oai_set_m3='',
                           oai_set_op1='a',
                           oai_set_op2='a',
                           ln=CFG_SITE_LANG,
                           func=0):
    """add a new OAI set"""
    _ = gettext_set_language(ln)
    out = ""

    if func in ["0", 0]:
        text = input_form(oai_set_name, oai_set_spec, oai_set_collection,
                          oai_set_p1, oai_set_f1, oai_set_m1, oai_set_p2,
                          oai_set_f2, oai_set_m2, oai_set_p3, oai_set_f3,
                          oai_set_m3, oai_set_op1, oai_set_op2)
        out = createform(action="addset",
                         text=text,
                         ln=ln,
                         button="Add new OAI set definition line",
                         func=1)

    if func in ["1", 1]:
        out += "<br />"

        res = add_oai_set(oai_set_name, oai_set_spec, oai_set_collection,
                          oai_set_description, oai_set_p1, oai_set_f1,
                          oai_set_m1, oai_set_p2, oai_set_f2, oai_set_m2,
                          oai_set_p3, oai_set_f3, oai_set_m3, oai_set_op1,
                          oai_set_op2)
        if res[0] == 1:
            out += oaiharvest_templates.tmpl_print_info(ln,
                                                        "OAI set definition %s added." % \
                                                        cgi.escape(oai_set_name))
            out += "<br />"

        out += "<br /><br />"
        out += create_html_link(urlbase=oai_rep_admin_url + \
                                "/index",
                                urlargd={'ln': ln},
                                link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #23
0
 def tmpl_history_day_details_link(self, ln, date, oai_src_id):
     """Return link to detailed history for the day"""
     _ = gettext_set_language(ln)
     return create_html_link(urlbase=oai_harvest_admin_url + \
                             "/viewhistoryday",
                             urlargd={'ln':ln,
                                      'oai_src_id': str(oai_src_id),
                                      'year': str(date.year),
                                      'month': str(date.month),
                                      'day': str(date.day),
                                      'start': str(10)},
                              link_label=_("View next entries..."))
Пример #24
0
def build_report_number_link(report_number, link_p=True):
    """
    Build HTML link out of given report number when it make sense (or
    is possible) and/or escape report number.
    @param report_number: the report number to consider
    @param link_p: if True, build link, otherwise just escape
    """
    if link_p and report_number.lower().startswith('arxiv:'):
        return create_html_link('http://arxiv.org/abs/' + report_number,
                                urlargd={}, link_label=report_number)
    else:
        return cgi.escape(report_number)
Пример #25
0
def build_report_number_link(report_number, link_p=True):
    """
    Build HTML link out of given report number when it make sense (or
    is possible) and/or escape report number.
    @param report_number: the report number to consider
    @param link_p: if True, build link, otherwise just escape
    """
    if link_p and report_number.lower().startswith('arxiv:'):
        return create_html_link('http://arxiv.org/abs/' + report_number,
                                urlargd={},
                                link_label=report_number)
    else:
        return cgi.escape(report_number)
Пример #26
0
 def print_aff(aff_pubdict):
     authoraff = ""
     for a in aff_pubdict:
         print_a = a[0]
         if (print_a == ' '):
             print_a = _("unknown affiliation")
         if authoraff:
             authoraff += '<br>'
         authoraff += (print_a + ' (' + create_html_link(
                      websearch_templates.build_search_url(p=' or '.join(
                                                     ["%s" % x for x in a[1]]),
                                     f='recid'),
                                     {}, str(len(a[1])),) + ')')
     return authoraff
Пример #27
0
 def tmpl_output_month_selection_bar(self, oai_src_id, ln, current_year=None, current_month=None):
     """constructs the month selection bar"""
     _ = gettext_set_language(ln)
     if current_month == None or current_year == None:
         current_month = datetime.datetime.today().month
         current_year = datetime.datetime.today().year
     prev_year = current_year
     prev_month = current_month
     prev_month -= 1
     if prev_month == 0:
         prev_year -= 1
         prev_month = 12
     next_year = current_year
     next_month = current_month
     next_month += 1
     if next_month == 13:
         next_year += 1
         next_month = 1
     current_date = datetime.datetime(current_year, current_month, 1)
     prevurl = create_html_link(urlbase=oai_harvest_admin_url + \
                                "/viewhistory",
                                urlargd={'ln':ln,
                                         'oai_src_id': str(oai_src_id),
                                         'year': str(prev_year),
                                         'month': str(prev_month)},
                                link_label="&lt;&lt; " + _("previous month"))
     nexturl = create_html_link(urlbase=oai_harvest_admin_url + \
                                "/viewhistory",
                                urlargd={'ln':ln,
                                         'oai_src_id': str(oai_src_id),
                                         'year': str(next_year),
                                         'month': str(next_month)},
                                link_label=_("next month") + " &gt;&gt;")
     result = prevurl + """&nbsp;&nbsp;&nbsp;&nbsp;"""
     result += "<b>Current month: " + self.format_ym(current_date) + "</b>"
     result += """&nbsp;&nbsp;&nbsp;&nbsp;""" + nexturl
     return result
Пример #28
0
def perform_request_touchset(oai_set_id=None, ln=CFG_SITE_LANG, func=0):
    """creates html form to touch an OAI set"""
    _ = gettext_set_language(ln)
    out = ""

    if oai_set_id:
        oai_set = get_oai_set(oai_set_id)
        if not oai_set:
            return "ERROR: oai_set_id %s seems invalid" % oai_set_id

        oai_set = get_oai_set(oai_set_id)
        oai_set_spec = oai_set[0][1]
        oai_set_name = oai_set[0][2]
        oai_set_collection = oai_set[0][3]
        oai_set_p1 = oai_set[0][5]
        oai_set_f1 = oai_set[0][6]
        oai_set_m1 = oai_set[0][7]
        oai_set_p2 = oai_set[0][8]
        oai_set_f2 = oai_set[0][9]
        oai_set_m2 = oai_set[0][10]
        oai_set_p3 = oai_set[0][11]
        oai_set_f3 = oai_set[0][12]
        oai_set_m3 = oai_set[0][13]
        oai_set_op1 = oai_set[0][14]
        oai_set_op2 = oai_set[0][15]

        if func in ["0", 0]:

            if oai_set:
                question = _("""Do you want to touch the OAI set %(x_name)s? Note that this will force all clients to re-harvest the whole set.""", x_name=cgi.escape(oai_set_spec))
                text = oaiharvest_templates.tmpl_print_info(ln, question)
                out += createform(action="touchset",
                                    text=text,
                                    button="Touch",
                                    oai_set_id=oai_set_id,
                                    func=1)
            else:
                return oaiharvest_templates.tmpl_print_info(ln, _("OAI set does not exist."))
        elif func in ["1", 1]:
            touch_oai_set(oai_set_spec)
            out += oaiharvest_templates.tmpl_print_info(ln, _("OAI set %(x_name)s touched.", x_name=cgi.escape(oai_set_spec)))
    out += "<br />"
    out += "<br /><br />"
    out += create_html_link(urlbase=oai_rep_admin_url + \
                "/index",
                urlargd={'ln': ln},
                link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #29
0
def perform_request_addset(oai_set_name='', oai_set_spec='',
                           oai_set_collection='',
                           oai_set_description='',
                           oai_set_p1='', oai_set_f1='',oai_set_m1='',
                           oai_set_p2='', oai_set_f2='',
                           oai_set_m2='', oai_set_p3='',
                           oai_set_f3='', oai_set_m3='',
                           oai_set_op1='a', oai_set_op2='a',
                           ln=CFG_SITE_LANG, func=0):
    """add a new OAI set"""
    _ = gettext_set_language(ln)
    out  = ""

    if func in ["0", 0]:
        text = input_form(oai_set_name, oai_set_spec,
                          oai_set_collection,
                          oai_set_p1, oai_set_f1,oai_set_m1,
                          oai_set_p2, oai_set_f2,oai_set_m2,
                          oai_set_p3, oai_set_f3, oai_set_m3,
                          oai_set_op1, oai_set_op2)
        out = createform(action="addset",
                         text=text,
                         ln=ln,
                         button="Add new OAI set definition line",
                         func=1)

    if func in ["1", 1]:
        out += "<br />"

        res = add_oai_set(oai_set_name, oai_set_spec,
                          oai_set_collection, oai_set_description,
                          oai_set_p1, oai_set_f1, oai_set_m1,
                          oai_set_p2, oai_set_f2, oai_set_m2,
                          oai_set_p3, oai_set_f3, oai_set_m3,
                          oai_set_op1, oai_set_op2)
        if res[0] == 1:
            out += oaiharvest_templates.tmpl_print_info(ln,
                                                        "OAI set definition %s added." % \
                                                        cgi.escape(oai_set_name))
            out += "<br />"

        out += "<br /><br />"
        out += create_html_link(urlbase=oai_rep_admin_url + \
                                "/index",
                                urlargd={'ln': ln},
                                link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #30
0
 def tmpl_account_new_mail(self, nb_new_mail=0, total_mail=0, ln=CFG_SITE_LANG):
     """
     display infos about inbox (used by myaccount.py)
     @param nb_new_mail: number of new mails
     @param ln: language
     return: html output.
     """
     _ = gettext_set_language(ln)
     out = _("You have %(x_nb_new)s new messages out of %(x_nb_total)s messages") % \
           {'x_nb_new': '<b>' + str(nb_new_mail) + '</b>',
            'x_nb_total': create_html_link(CFG_SITE_URL + '/yourmessages/',
                                           {'ln': ln},
                                           str(total_mail),
                                           {},
                                           False, False)}
     return out + '.'
Пример #31
0
    def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG):
        """Take URLARGS and LANGUAGE and return textual language
           selection box for the given page.

           Parameters:

          - 'req' - The mod_python request object

          - 'language' *string* - The selected language

        """

        # load the right message language
        _ = gettext_set_language(language)

        # Work on a copy in order not to bork the arguments of the caller
        argd = {}
        if req and req.args:
            argd.update(cgi.parse_qs(req.args))

        parts = []

        for (lang, lang_namelong) in language_list_long():
            if lang == language:
                parts.append('<span class="langinfo">%s</span>' %
                             lang_namelong)
            else:
                # Update the 'ln' argument in the initial request
                argd['ln'] = lang
                if req and req.uri:
                    args = urllib.quote(
                        req.uri, '/:?') + make_canonical_urlargd(argd, {})
                else:
                    args = ""
                parts.append(
                    create_html_link(args, {}, lang_namelong,
                                     {'class': "langinfo"}))
        if len(parts) > 1:
            return _("This site is also available in the following languages:") + \
                 "<br />" + ' &nbsp;'.join(parts)
        else:
            ## There is only one (or zero?) languages configured,
            ## so there so need to display language alternatives.
            return ""
Пример #32
0
    def tmpl_language_selection_box(self, req, language=CFG_SITE_LANG):
        """Take URLARGS and LANGUAGE and return textual language
           selection box for the given page.

           Parameters:

          - 'req' - The mod_python request object

          - 'language' *string* - The selected language

        """

        # load the right message language
        _ = gettext_set_language(language)

        # Work on a copy in order not to bork the arguments of the caller
        argd = {}
        if req and req.args:
            argd.update(cgi.parse_qs(req.args))

        parts = []

        for (lang, lang_namelong) in language_list_long():
            if lang == language:
                parts.append('<span class="langinfo">%s</span>' % lang_namelong)
            else:
                # Update the 'ln' argument in the initial request
                argd['ln'] = lang
                if req and req.uri:
                    args = urllib.quote(req.uri, '/:?') + make_canonical_urlargd(argd, {})
                else:
                    args = ""
                parts.append(create_html_link(args,
                                              {}, lang_namelong,
                                              {'class': "langinfo"}))
        if len(parts) > 1:
            return _("This site is also available in the following languages:") + \
                 "<br />" + ' &nbsp;'.join(parts)
        else:
            ## There is only one (or zero?) languages configured,
            ## so there so need to display language alternatives.
            return ""
Пример #33
0
def format_element(bfo, style):
    """Print a link to BibEdit, if authorization is granted.

    :param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        out += create_html_link(
            CFG_BASE_URL + '/%s/edit/?ln=%s#state=edit&recid=%s' %
            (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)), {},
            link_label=_("Edit This Record"),
            linkattrd=linkattrd)

    return out
Пример #34
0
    def tmpl_author_name_variants_box(self, req, names_dict, bibauthorid_data, ln, add_box=True, loading=False):
        '''
        names_dict - a dict of {name: frequency}
        '''
        _ = gettext_set_language(ln)

        if bibauthorid_data["cid"]:
            baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["cid"])
        elif bibauthorid_data["pid"] > -1:
            baid_query = 'exactauthor:%s' % wrap_author_name_in_quotes_if_needed(bibauthorid_data["pid"])
        else:
            baid_query = ''

        sorted_names_list = sorted(iteritems(names_dict), key=itemgetter(1),
                                   reverse=True)
        header = "<strong>" + _("Name variants") + "</strong>"
        content = []

        for name, frequency in sorted_names_list:
            if not name:
                name = ''

            prquery = baid_query + ' exactauthor:"' + name + '"'
            name_lnk = create_html_link(websearch_templates.build_search_url(p=prquery),
                                                              {},
                                                              str(frequency),)
            content.append("%s (%s)" % (cgi.escape(name), name_lnk))

        if not content:
            content = [_("No Name Variants")]

        if loading:
            content = self.loading_html()
        else:
            content = "<br />\n".join(content)
        if not add_box:
            return content
        names_box = self.tmpl_print_searchresultbox("name_variants", header, content)

        return names_box
Пример #35
0
def format_element(bfo, style):
    """
    Prints a link to BibEdit, if authorization is granted

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    if user_can_edit_record_collection(user_info, bfo.recID):
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        out += create_html_link(CFG_SITE_URL +
               '/%s/edit/?ln=%s#state=edit&recid=%s' % (CFG_SITE_RECORD, bfo.lang, str(bfo.recID)),
               {},
               link_label=_("Edit This Record"),
               linkattrd=linkattrd)

    return out
Пример #36
0
    def tmpl_output_menu(self, ln, oai_src_id, guideurl):
        """
           Function which displays menu
        """
        _ = gettext_set_language(ln)
        link_default_argd = {'ln': ln}

        main_link = create_html_link(urlbase=oai_harvest_admin_url,
                                     urlargd=link_default_argd,
                                     link_label=_("main Page"))

        link_default_argd['oai_src_id'] = str(oai_src_id)

        edit_link = create_html_link(urlbase=oai_harvest_admin_url + \
                                     "/editsource",
                                     urlargd=link_default_argd,
                                     link_label=_("edit"))
        delete_link = create_html_link(urlbase=oai_harvest_admin_url + \
                                     "/delsource",
                                     urlargd=link_default_argd,
                                     link_label=_("delete"))
        test_link = create_html_link(urlbase=oai_harvest_admin_url + \
                                     "/testsource",
                                     urlargd=link_default_argd,
                                     link_label=_("test"))
        hist_link = create_html_link(urlbase=oai_harvest_admin_url + \
                                     "/viewhistory",
                                     urlargd=link_default_argd,
                                     link_label=_("history"))
        harvest_link = create_html_link(urlbase=oai_harvest_admin_url + \
                                        "/harvest",
                                        urlargd=link_default_argd,
                                        link_label=_("harvest"))
        separator = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        menu_header = self.tmpl_draw_titlebar(ln, title="Menu" , guideurl=guideurl)
        # Putting everything together
        result = menu_header + main_link
        if oai_src_id != None:
            result += separator + edit_link + separator + \
                      delete_link + separator + test_link + \
                      separator + hist_link + separator + \
                      harvest_link + separator

        result += self.tmpl_print_brs(ln, 2)
        return result
Пример #37
0
def format_element(bfo, remote_server_id, link_label="Push via Sword"):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info,
                                                   'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang, 'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    return create_html_link(CFG_BASE_URL + '/bibsword', sword_arguments,
                            link_label)
Пример #38
0
def format_element(bfo, remote_server_id, link_label="Push via Sword"):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label)
Пример #39
0
    def tmpl_list_alerts(self, ln, alerts, guest, guesttxt):
        """
        Displays the list of alerts

        Parameters:

          - 'ln' *string* - The language to display the interface in

          - 'alerts' *array* - The existing alerts:

              - 'queryid' *string* - The id of the associated query

              - 'queryargs' *string* - The query string

              - 'textargs' *string* - The textual description of the query string

              - 'userid' *string* - The user id

              - 'basketid' *string* - The basket id

              - 'basketname' *string* - The basket name

              - 'alertname' *string* - The alert name

              - 'frequency' *string* - The frequency of alert running ('day', 'week', 'month')

              - 'notification' *string* - If notification should be sent by email ('y', 'n')

              - 'created' *string* - The date of alert creation

              - 'lastrun' *string* - The last running date

          - 'guest' *bool* - If the user is a guest user

          - 'guesttxt' *string* - The HTML content of the warning box for guest users (produced by webaccount.tmpl_warning_guest_user)
        """

        # load the right message language
        _ = gettext_set_language(ln)

        out = '<p>'
        out += _("Set a new alert from %(x_url1_open)syour searches%(x_url1_close)s, the %(x_url2_open)spopular searches%(x_url2_close)s, or the input form.", **{
            'x_url1_open': '<a href="display?ln=' + ln + '">',
            'x_url1_close': '</a>',
            'x_url2_open': '<a href="display?ln=' + ln + '&amp;p=y">',
            'x_url2_close': '</a>',
            })
        out += '</p>'
        if len(alerts):
            out += """<table class="alrtTable">
                          <tr class="pageboxlefttop" style="text-align: center;">
                            <td style="font-weight: bold">%(no)s</td>
                            <td style="font-weight: bold">%(name)s</td>
                            <td style="font-weight: bold">%(search_freq)s</td>
                            <td style="font-weight: bold">%(notification)s</td>
                            <td style="font-weight: bold">%(result_basket)s</td>
                            <td style="font-weight: bold">%(date_run)s</td>
                            <td style="font-weight: bold">%(date_created)s</td>
                            <td style="font-weight: bold">%(query)s</td>
                            <td style="font-weight: bold">%(action)s</td></tr>""" % {
                       'no' : _("No"),
                       'name' : _("Name"),
                       'search_freq' : _("Search checking frequency"),
                       'notification' : _("Notification by email"),
                       'result_basket' : _("Result in basket"),
                       'date_run' : _("Date last run"),
                       'date_created' : _("Creation date"),
                       'query' : _("Query"),
                       'action' : _("Action"),
                     }
            i = 0
            for alert in alerts:
                i += 1
                if alert['frequency'] == "day":
                    frequency = _("daily")
                else:
                    if alert['frequency'] == "week":
                        frequency = _("weekly")
                    else:
                        frequency = _("monthly")

                if alert['notification'] == "y":
                    notification = _("yes")
                else:
                    notification = _("no")

                # we clean up the HH:MM part of lastrun, since it is always 00:00
                lastrun = alert['lastrun'].split(',')[0]
                created = alert['created'].split(',')[0]

                out += """<tr>
                              <td style="font-style: italic">#%(index)d</td>
                              <td style="font-weight: bold; text-wrap:none;">%(alertname)s</td>
                              <td>%(frequency)s</td>
                              <td style="text-align:center">%(notification)s</td>
                              <td style="text-wrap:none;">%(basketname)s</td>
                              <td style="text-wrap:none;">%(lastrun)s</td>
                              <td style="text-wrap:none;">%(created)s</td>
                              <td>%(textargs)s</td>
                              <td>
                                 %(remove_link)s<br />
                                 %(modify_link)s<br />
                                 <a href="%(siteurl)s/search?%(queryargs)s&amp;ln=%(ln)s" style="white-space:nowrap">%(search)s</a>
                             </td>
                            </tr>""" % {
                    'index' : i,
                    'alertname' : cgi.escape(alert['alertname']),
                    'frequency' : frequency,
                    'notification' : notification,
                    'basketname' : alert['basketname'] and cgi.escape(alert['basketname']) \
                                                       or "- " + _("no basket") + " -",
                    'lastrun' : lastrun,
                    'created' : created,
                    'textargs' : alert['textargs'],
                    'queryid' : alert['queryid'],
                    'basketid' : alert['basketid'],
                    'freq' : alert['frequency'],
                    'notif' : alert['notification'],
                    'ln' : ln,
                    'modify_link': create_html_link("./modify",
                                                    {'ln': ln,
                                                     'idq': alert['queryid'],
                                                     'name': alert['alertname'],
                                                     'freq': frequency,
                                                     'notif':notification,
                                                     'idb':alert['basketid'],
                                                     'old_idb':alert['basketid']},
                                                    _("Modify")),
                    'remove_link': create_html_link("./remove",
                                                    {'ln': ln,
                                                     'idq': alert['queryid'],
                                                     'name': alert['alertname'],
                                                     'idb':alert['basketid']},
                                                    _("Remove")),
                    'siteurl' : CFG_SITE_URL,
                    'search' : _("Execute search"),
                    'queryargs' : cgi.escape(alert['queryargs'])
                  }

            out += '</table>'

        out += '<p>' + (_("You have defined %(num)s alerts.", num='<b>' + str(len(alerts)) + '</b>')) + '</p>'
        if guest:
            out += guesttxt
        return out
Пример #40
0
def format_element(bfo,
                   separator=" ",
                   style='',
                   img_style='',
                   text_style='font-size:small',
                   print_links='yes',
                   max_photos='',
                   show_comment='yes',
                   img_max_width='250px',
                   display_all_version_links='yes'):
    """
    Lists the photos of a record. Display the icon version, linked to
    its original version.

    This element works for photos appended to a record as BibDoc
    files, for which a preview icon has been generated. If there are
    several formats for one photo, use the first one found.

    @param separator: separator between each photo
    @param print_links: if 'yes', print links to the original photo
    @param style: style attributes of the whole image block. Eg: "padding:2px;border:1px"
    @param img_style: style attributes of the images. Eg: "width:50px;border:none"
    @param text_style: style attributes of the text. Eg: "font-size:small"
    @param max_photos: the maximum number of photos to display
    @param show_comment: if 'yes', display the comment of each photo
    @param display_all_version_links: if 'yes', print links to additional (sub)formats
    """
    photos = []
    bibarchive = BibRecDocs(bfo.recID)
    bibdocs = bibarchive.list_bibdocs()

    if max_photos.isdigit():
        max_photos = int(max_photos)
    else:
        max_photos = len(bibdocs)

    for doc in bibdocs[:max_photos]:
        found_icons = []
        found_url = ''
        for docfile in doc.list_latest_files():
            if docfile.is_icon():
                found_icons.append(
                    (docfile.get_size(), get_relative_url(docfile.get_url())))
            else:
                found_url = get_relative_url(docfile.get_url())
        found_icons.sort()

        if found_icons:
            additional_links = ''
            name = bibarchive.get_docname(doc.id)
            comment = doc.list_latest_files()[0].get_comment()

            preview_url = None
            if len(found_icons) > 1:
                preview_url = get_relative_url(found_icons[1][1])
                additional_urls = [(docfile.get_size(), get_relative_url(docfile.get_url()), \
                                    docfile.get_superformat(), docfile.get_subformat()) \
                                   for docfile in doc.list_latest_files() if not docfile.is_icon()]
                additional_urls.sort()
                additional_links = [create_html_link(url, urlargd={}, \
                                                     linkattrd={'style': 'font-size:x-small'}, \
                                                     link_label="%s %s (%s)" % (format.strip('.').upper(), subformat, format_size(size))) \
                                    for (size, url, format, subformat) in additional_urls]
            img = '<img src="%(icon_url)s" alt="%(name)s" style="max-width:%(img_max_width)s;_width:%(img_max_width)s;%(img_style)s" />' % \
                  {'icon_url': cgi.escape(get_relative_url(found_icons[0][1]), True),
                   'name': cgi.escape(name, True),
                   'img_style': img_style,
                   'img_max_width': img_max_width}

            if print_links.lower() == 'yes':
                img = '<a href="%s">%s</a>' % (cgi.escape(
                    preview_url or found_url, True), img)
            if display_all_version_links.lower() == 'yes' and additional_links:
                img += '<br />' + '&nbsp;'.join(additional_links) + '<br />'

            if show_comment.lower() == 'yes' and comment:
                img += '<div style="margin-auto;text-align:center;%(text_style)s">%(comment)s</div>' % \
                       {'comment': comment.replace('\n', '<br/>'),
                        'text_style': text_style}
            img = '<div style="vertical-align: middle;text-align:center;display:inline-block;display: -moz-inline-stack;zoom: 1;*display: inline;max-width:%(img_max_width)s;_width:%(img_max_width)s;text-align:center;%(style)s">%(img)s</div>' % \
                  {'img_max_width': img_max_width,
                   'style': style,
                   'img': img}

            photos.append(img)

    return '<div>' + separator.join(photos) + '</div>'
Пример #41
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})
Пример #42
0
    def tmpl_bibdocfile_filelist(self, ln, recid, name, version, md,
                                 superformat, subformat, nice_size_f,
                                 description, comment):
        """
        Displays a file in the file list.

        Parameters:

          - 'ln' *string* - The language to display the interface in

          - 'recid' *int* - The id of the record

          - 'name' *string* - The name of the file

          - 'version' *string* - The version

          - 'md' *datetime* - the modification date

          - 'superformat' *string* - The display superformat

          - 'subformat' *string* - The display subformat

          - 'nice_size_f' *string* - The nice_size of the file

          - 'description' *string* - The description that might have been associated
          to the particular file

          - 'comment' *string* - The comment that might have been associated
          to the particular file
        """

        # load the right message language
        _ = gettext_set_language(ln)

        urlbase = '%s/%s/%s/files/%s' % (
            CFG_SITE_URL, CFG_SITE_RECORD, recid, '%s%s' %
            (cgi.escape(urllib.quote(name), True), superformat))

        urlargd = {'version': version}
        if subformat:
            urlargd['subformat'] = subformat

        link_label = '%s%s' % (name, superformat)
        if subformat:
            link_label += ' (%s)' % subformat

        link = create_html_link(urlbase, urlargd, cgi.escape(link_label))

        return """<tr>
                    <td valign="top">
                      <small>%(link)s</small>
                    </td>
                    <td valign="top">
                      <font size="-2" color="green">[%(nice_size)s]</font>
                      <font size="-2"><em>%(md)s</em>
                      %(comment)s
                    </td>
                    <td valign="top"><em>%(description)s</em></td>
                    </tr>""" % {
            'link':
            link,
            'nice_size':
            nice_size_f,
            'md':
            convert_datestruct_to_dategui(md.timetuple(), ln),
            'description':
            cgi.escape(description),
            'comment':
            comment and """<br /><font size="-2"><em>%s</em></font>""" %
            cgi.escape(comment) or '',
        }
Пример #43
0
    def tmpl_list_alerts(self, ln, alerts, guest, guesttxt):
        """
        Displays the list of alerts

        Parameters:

          - 'ln' *string* - The language to display the interface in

          - 'alerts' *array* - The existing alerts:

              - 'queryid' *string* - The id of the associated query

              - 'queryargs' *string* - The query string

              - 'textargs' *string* - The textual description of the query string

              - 'userid' *string* - The user id

              - 'basketid' *string* - The basket id

              - 'basketname' *string* - The basket name

              - 'alertname' *string* - The alert name

              - 'frequency' *string* - The frequency of alert running ('day', 'week', 'month')

              - 'notification' *string* - If notification should be sent by email ('y', 'n')

              - 'created' *string* - The date of alert creation

              - 'lastrun' *string* - The last running date

          - 'guest' *bool* - If the user is a guest user

          - 'guesttxt' *string* - The HTML content of the warning box for guest users (produced by webaccount.tmpl_warning_guest_user)
        """

        # load the right message language
        _ = gettext_set_language(ln)

        out = '<p>'
        out += _(
            "Set a new alert from %(x_url1_open)syour searches%(x_url1_close)s, the %(x_url2_open)spopular searches%(x_url2_close)s, or the input form.",
            **{
                'x_url1_open': '<a href="display?ln=' + ln + '">',
                'x_url1_close': '</a>',
                'x_url2_open': '<a href="display?ln=' + ln + '&amp;p=y">',
                'x_url2_close': '</a>',
            })
        out += '</p>'
        if len(alerts):
            out += """<table class="table table-hover">
                          <tr class="pageboxlefttop" style="text-align: center;">
                            <td style="font-weight: bold">%(no)s</td>
                            <td style="font-weight: bold">%(name)s</td>
                            <td style="font-weight: bold">%(search_freq)s</td>
                            <td style="font-weight: bold">%(notification)s</td>
                            <td style="font-weight: bold">%(result_basket)s</td>
                            <td style="font-weight: bold">%(date_run)s</td>
                            <td style="font-weight: bold">%(date_created)s</td>
                            <td style="font-weight: bold">%(query)s</td>
                            <td style="font-weight: bold">%(action)s</td></tr>""" % {
                'no': _("No"),
                'name': _("Name"),
                'search_freq': _("Search checking frequency"),
                'notification': _("Notification by email"),
                'result_basket': _("Result in basket"),
                'date_run': _("Date last run"),
                'date_created': _("Creation date"),
                'query': _("Query"),
                'action': _("Action"),
            }
            i = 0
            for alert in alerts:
                i += 1
                if alert['frequency'] == "day":
                    frequency = _("daily")
                else:
                    if alert['frequency'] == "week":
                        frequency = _("weekly")
                    else:
                        frequency = _("monthly")

                if alert['notification'] == "y":
                    notification = _("yes")
                else:
                    notification = _("no")

                # we clean up the HH:MM part of lastrun, since it is always 00:00
                lastrun = alert['lastrun'].split(',')[0]
                created = alert['created'].split(',')[0]

                out += """<tr>
                              <td style="font-style: italic">#%(index)d</td>
                              <td style="font-weight: bold; text-wrap:none;">%(alertname)s</td>
                              <td>%(frequency)s</td>
                              <td style="text-align:center">%(notification)s</td>
                              <td style="text-wrap:none;">%(basketname)s</td>
                              <td style="text-wrap:none;">%(lastrun)s</td>
                              <td style="text-wrap:none;">%(created)s</td>
                              <td><span class="label label-info">%(textargs)s</span></td>
                              <td>
                                %(remove_link)s<br />
                                %(modify_link)s<br />
                                <a href="%(siteurl)s/search?%(queryargs)s&amp;ln=%(ln)s" style="white-space:nowrap">%(search)s</a>
                              </td>
                            </tr>""" % {
                    'index' : i,
                    'alertname' : cgi.escape(alert['alertname']),
                    'frequency' : frequency,
                    'notification' : notification,
                    'basketname' : alert['basketname'] and cgi.escape(alert['basketname']) \
                                                       or "- " + _("no basket") + " -",
                    'lastrun' : lastrun,
                    'created' : created,
                    'textargs' : alert['textargs'],
                    'queryid' : alert['queryid'],
                    'basketid' : alert['basketid'],
                    'freq' : alert['frequency'],
                    'notif' : alert['notification'],
                    'ln' : ln,
                    'modify_link': create_html_link("./modify",
                                                    {'ln': ln,
                                                     'idq': alert['queryid'],
                                                     'name': alert['alertname'],
                                                     'freq': frequency,
                                                     'notif':notification,
                                                     'idb':alert['basketid'],
                                                     'old_idb':alert['basketid']},
                                                    _("Modify")),
                    'remove_link': create_html_link("./remove",
                                                    {'ln': ln,
                                                     'idq': alert['queryid'],
                                                     'name': alert['alertname'],
                                                     'idb':alert['basketid']},
                                                    _("Remove")),
                    'siteurl' : CFG_SITE_URL,
                    'search' : _("Execute search"),
                    'queryargs' : cgi.escape(alert['queryargs'])
                  }

            out += '</table>'

        out += '<p>' + (_("You have defined %(num)s alerts.",
                          num='<b>' + str(len(alerts)) + '</b>')) + '</p>'
        if guest:
            out += guesttxt
        return out
Пример #44
0
    def tmpl_display_inbox(self, messages, infos=[], warnings=[], nb_messages=0, no_quota=0, ln=CFG_SITE_LANG):
        """
        Displays a list of messages, with the appropriate links and buttons
        @param messages: a list of tuples:
                         [(message_id,
                           user_from_id,
                           user_from_nickname,
                           subject,
                           sent_date,
                           status=]
        @param infos: a list of informations to print on top of page
        @param warnings: a list of warnings to display
        @param nb_messages: number of messages user has
        @param no_quota: 1 if user has no quota (admin) or 0 else.
        @param ln: language of the page.
        @return: the list in HTML format
        """
        _ = gettext_set_language(ln)
        dummy = 0
        inbox = self.tmpl_warning(warnings, ln)
        inbox += self.tmpl_infobox(infos, ln)
        if not(no_quota):
            inbox += self.tmpl_quota(nb_messages, ln)
        inbox += """
<table class="mailbox">
  <thead class="mailboxheader">
    <tr class="inboxheader">
      <td>%s</td>
      <td>%s</td>
      <td>%s</td>
      <td>%s</td>
    </tr>
  </thead>
  <tfoot>
    <tr style="height:0px;">
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tfoot>
  <tbody class="mailboxbody">""" % (_("Subject"),
                                    _("Sender"),
                                    _("Date"),
                                    _("Action"))
        if len(messages) == 0:
            inbox += """
    <tr class="mailboxrecord" style="height: 100px;">
      <td colspan="4" style="text-align: center;">
        <b>%s</b>
      </td>
    </tr>""" %(_("No messages"),)
        for (msgid, id_user_from, user_from_nick,
             subject, sent_date, status) in messages:
            if not(subject):
                subject = _("No subject")
            subject_link = create_html_link(
                                CFG_SITE_URL + '/yourmessages/display_msg',
                                {'msgid': msgid, 'ln': ln},
                                escape_html(subject))
            if user_from_nick:
                from_link = '%s'% (user_from_nick)
            else:
                from_link = get_user_info(id_user_from, ln)[2]
            action_link = create_html_link(CFG_SITE_URL + '/yourmessages/write',
                                           {'msg_reply_id': msgid, 'ln': ln},
                                           _("Reply"))
            action_link += ' '
            action_link += create_html_link(CFG_SITE_URL + '/yourmessages/delete',
                                            {'msgid': msgid, 'ln': ln},
                                            _("Delete"))
            s_date = convert_datetext_to_dategui(sent_date, ln)
            stat_style = ''
            if (status == CFG_WEBMESSAGE_STATUS_CODE['NEW']):
                stat_style = ' style="font-weight:bold"'
            inbox += """
    <tr class="mailboxrecord">
      <td%s>%s</td>
      <td>%s</td>
      <td>%s</td>
      <td>%s</td>
    </tr>""" %(stat_style, subject_link, from_link, s_date, action_link)
        inbox += """
    <tr class="mailboxfooter">
      <td colspan="2">
        <form name="newMessage" action="%(url_new)s" method="post">
          <input type="submit" name="del_all" value="%(write_label)s" class="formbutton" />
        </form>
      </td>
      <td>&nbsp;</td>
      <td>
        <form name="deleteAll" action="%(url_delete_all)s" method="post">
          <input type="submit" name="del_all" value="%(delete_all_label)s" class="formbutton" />
        </form>
      </td>
    </tr>
  </tbody>
</table>""" % {'url_new': create_url(CFG_SITE_URL + '/yourmessages/write',
                                     {'ln': ln}),
               'url_delete_all': create_url(CFG_SITE_URL + '/yourmessages/delete_all',
                                            {'ln': ln}),
               'write_label': _("Write new message"),
               'delete_all_label': _("Delete All")}
        return inbox
Пример #45
0
def perform_request_editset(oai_set_id=None, oai_set_name='',
                            oai_set_spec='', oai_set_collection='',
                            oai_set_description='',
                            oai_set_p1='', oai_set_f1='',
                            oai_set_m1='', oai_set_p2='',
                            oai_set_f2='', oai_set_m2='',
                            oai_set_p3='', oai_set_f3='',
                            oai_set_m3='', oai_set_op1='a',
                            oai_set_op2='a', ln=CFG_SITE_LANG,
                            func=0):
    """creates html form to edit an OAI set."""
    _ = gettext_set_language(ln)

    if oai_set_id is None:
        return "No OAI set ID selected."

    out  = ""

    if func in [0, "0"]:

        oai_set = get_oai_set(oai_set_id)
        if not oai_set:
            return "ERROR: oai_set_id %s seems invalid" % oai_set_id
        oai_set_spec = oai_set[0][1]
        oai_set_name = oai_set[0][2]
        oai_set_collection  = oai_set[0][3]
        oai_set_description = oai_set[0][4]
        oai_set_p1 = oai_set[0][5]
        oai_set_f1 = oai_set[0][6]
        oai_set_m1 = oai_set[0][7]
        oai_set_p2 = oai_set[0][8]
        oai_set_f2 = oai_set[0][9]
        oai_set_m2 = oai_set[0][10]
        oai_set_p3 = oai_set[0][11]
        oai_set_f3 = oai_set[0][12]
        oai_set_m3 = oai_set[0][13]
        oai_set_op1 = oai_set[0][14]
        oai_set_op2 = oai_set[0][15]

        text = input_form(oai_set_name,
                          oai_set_spec,
                          oai_set_collection,
                          oai_set_p1,
                          oai_set_f1,
                          oai_set_m1,
                          oai_set_p2,
                          oai_set_f2,
                          oai_set_m2,
                          oai_set_p3,
                          oai_set_f3,
                          oai_set_m3,
                          oai_set_op1,
                          oai_set_op2)

        out += extended_input_form(action="editset",
                                text=text,
                                button="Modify",
                                oai_set_id=oai_set_id,
                                ln=ln,
                                func=1)

    if func in [1, "1"]:
        res = modify_oai_set(oai_set_id,
                             oai_set_name,
                             oai_set_spec,
                             oai_set_collection,
                             oai_set_description,
                             oai_set_p1,
                             oai_set_f1,
                             oai_set_m1,
                             oai_set_p2,
                             oai_set_f2,
                             oai_set_m2,
                             oai_set_p3,
                             oai_set_f3,
                             oai_set_m3,
                             oai_set_op1,
                             oai_set_op2)
        out += "<br />"
        if res[0] == 1:
            out += oaiharvest_templates.tmpl_print_info(ln, "OAI set definition #%s edited." % oai_set_id)
            out += "<br />"
        else:
            out += webstyle_templates.tmpl_write_warning("A problem was encountered: <br/>" + cgi.escape(res[1]))
            out += "<br />"

    out += "<br />"

    out += create_html_link(urlbase=oai_rep_admin_url + \
                            "/index",
                            urlargd={'ln': ln},
                            link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #46
0
def perform_request_delset(oai_set_id=None, ln=CFG_SITE_LANG, func=0):
    """creates html form to delete an OAI set"""
    _ = gettext_set_language(ln)
    out = ""

    if oai_set_id:
        oai_set = get_oai_set(oai_set_id)
        if not oai_set:
            return "ERROR: oai_set_id %s seems invalid" % oai_set_id

        if func in ["0", 0]:

            oai_set = get_oai_set(oai_set_id)
            oai_set_spec = oai_set[0][1]
            oai_set_name = oai_set[0][2]
            oai_set_collection = oai_set[0][3]
            oai_set_p1 = oai_set[0][5]
            oai_set_f1 = oai_set[0][6]
            oai_set_m1 = oai_set[0][7]
            oai_set_p2 = oai_set[0][8]
            oai_set_f2 = oai_set[0][9]
            oai_set_m2 = oai_set[0][10]
            oai_set_p3 = oai_set[0][11]
            oai_set_f3 = oai_set[0][12]
            oai_set_m3 = oai_set[0][13]
            oai_set_op1 = oai_set[0][14]
            oai_set_op2 = oai_set[0][15]

            if oai_set:
                question = """Do you want to delete the OAI definition #%s?""" % oai_set_id
                text = oaiharvest_templates.tmpl_print_info(ln, question)
                text += "<br /><br /><br />"
                text += pagebody_text(
                    cgi.escape("%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s" % \
                               (oai_set_spec,
                                oai_set_name,
                                oai_set_collection,
                                oai_set_p1,
                                oai_set_f1,
                                oai_set_m1,
                                oai_set_op1,
                                oai_set_p2,
                                oai_set_f2,
                                oai_set_m2,
                                oai_set_op2,
                                oai_set_p3,
                                oai_set_f3,
                                oai_set_m3)))

                out += createform(action="delset",
                                       text=text,
                                       button="Delete",
                                       oai_set_id=oai_set_id,
                                       func=1)
            else:
                return oaiharvest_templates.tmpl_print_info(ln, "OAI set does not exist.")
        elif func in ["1", 1]:
            res = delete_oai_set(oai_set_id)
            if res[0] == 1:
                out += oaiharvest_templates.tmpl_print_info(ln, "OAI set definition #%s deleted." % oai_set_id)
                out += "<br />"
            else:
                pass

    out += "<br /><br />"
    out += create_html_link(urlbase=oai_rep_admin_url + \
                                "/index",
                                urlargd={'ln': ln},
                                link_label=_("Return to main selection"))

    return nice_box("", out)
Пример #47
0
    def tmpl_display_msg(self,
                         msg_id="",
                         msg_from_id="",
                         msg_from_nickname="",
                         msg_sent_to="",
                         msg_sent_to_group="",
                         msg_subject="",
                         msg_body="",
                         msg_sent_date="",
                         msg_received_date=datetext_default,
                         ln=CFG_SITE_LANG):
        """
        Displays a given message
        @param msg_id: id of the message
        @param msg_from_id: id of user who sent the message
        @param msg_from_nickname: nickname of the user who sent the message
        @param msg_sent_to: list of users who received the message
                            (comma separated string)
        @param msg_sent_to_group: list of groups who received the message
                                  (comma separated string)
        @param msg_subject: subject of the message
        @param msg_body: body of the message
        @param msg_sent_date: date at which the message was sent
        @param msg_received_date: date at which the message had to be received
                                  (if this argument != 0000-00-00 => reminder
        @param ln: language of the page
        @return: the message in HTML format
        """

        # load the right message language
        _ = gettext_set_language(ln)

        sent_to_link = ''
        tos = msg_sent_to.split(CFG_WEBMESSAGE_SEPARATOR)
        if (tos):
            for to in tos[0:-1]:
                to_display = to
                if to.isdigit():
                    (dummy, to, to_display) = get_user_info(int(to), ln)
                sent_to_link += create_html_link(CFG_SITE_URL + '/yourmessages/write',
                                                 {'msg_to': to, 'ln': ln},
                                                 escape_html(to_display))
                sent_to_link += CFG_WEBMESSAGE_SEPARATOR
            to_display = tos[-1]
            to = tos[-1]
            if to.isdigit():
                (dummy, to, to_display) = get_user_info(int(to), ln)
            sent_to_link += create_html_link(CFG_SITE_URL + '/yourmessages/write',
                                             {'msg_to': to, 'ln': ln},
                                             escape_html(to_display))
        group_to_link = ""
        groups = msg_sent_to_group.split(CFG_WEBMESSAGE_SEPARATOR)
        if (groups):
            for group in groups[0:-1]:
                group_to_link += create_html_link(
                                    CFG_SITE_URL + '/yourmessages/write',
                                    {'msg_to_group': group, 'ln': ln},
                                    escape_html(group))
                group_to_link += CFG_WEBMESSAGE_SEPARATOR
            group_to_link += create_html_link(
                                CFG_SITE_URL + '/yourmessages/write',
                                {'msg_to_group': groups[-1], 'ln': ln},
                                escape_html(groups[-1]))
        # format the msg so that the '>>' chars give vertical lines
        final_body = email_quoted_txt2html(msg_body)

        out = """
<table class="mailbox" style="width: 70%%;">
  <thead class="mailboxheader">
    <tr>
      <td class="inboxheader" colspan="2">
        <table class="messageheader">
          <tr>
            <td class="mailboxlabel">%(from_label)s</td>
            <td>%(from_link)s</td>
          </tr>
          <tr>
            <td class="mailboxlabel">%(subject_label)s</td>
            <td style="width: 100%%;">%(subject)s</td>
          </tr>
          <tr>
            <td class="mailboxlabel">%(sent_label)s</td>
            <td>%(sent_date)s</td>
          </tr>"""
        if (msg_received_date != datetext_default):
            out += """
          <tr>
            <td class="mailboxlabel">%(received_label)s</td>
            <td>%(received_date)s</td>
          </tr>"""
        out += """
          <tr>
            <td class="mailboxlabel">%(sent_to_label)s</td>
            <td>%(sent_to)s</td>
          </tr>"""
        if (msg_sent_to_group != ""):
            out += """
          <tr>
            <td class="mailboxlabel">%(groups_label)s</td>
            <td>%(sent_to_group)s</td>
          </tr>"""
        out += """
        </table>
      </td>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <td></td>
      <td></td>
    </tr>
  </tfoot>
  <tbody class="mailboxbody">
    <tr class="mailboxrecord">
      <td colspan="2">%(body)s</td>
    </tr>
    <tr class="mailboxfooter">
      <td>
        <form name="reply" action="%(reply_url)s" method="post">
          <input class="formbutton" name="reply" value="%(reply_but_label)s" type="submit" />
        </form>
      </td>
      <td>
        <form name="deletemsg" action="%(delete_url)s" method="post">
          <input class="formbutton" name="delete" value="%(delete_but_label)s" type="submit" />
        </form>
      </td>
    </tr>
  </tbody>
</table>
        """
        if msg_from_nickname:
            msg_from_display = msg_from_nickname
        else:
            msg_from_display = get_user_info(msg_from_id, ln)[2]
            msg_from_nickname = msg_from_id

        return out % {'from_link': create_html_link(
                                        CFG_SITE_URL + '/yourmessages/write',
                                        {'msg_to': msg_from_nickname,
                                         'ln': ln},
                                        msg_from_display),
                     'reply_url': create_url(CFG_SITE_URL + '/yourmessages/write',
                                             {'msg_reply_id': msg_id,
                                             'ln':  ln}),
                     'delete_url': create_url(CFG_SITE_URL + '/yourmessages/delete',
                                             {'msgid': msg_id,
                                             'ln':  ln}),
                     'sent_date' : convert_datetext_to_dategui(msg_sent_date, ln),
                     'received_date': convert_datetext_to_dategui(msg_received_date, ln),
                     'sent_to': sent_to_link,
                     'sent_to_group': group_to_link,
                     'subject' : msg_subject,
                     'body' : final_body,
                     'reply_to': msg_from_id,
                     'ln': ln,
                     'from_label':_("From:"),
                     'subject_label':_("Subject:"),
                     'sent_label': _("Sent on:"),
                     'received_label':_("Received on:"),
                     'sent_to_label': _("Sent to:"),
                     'groups_label': _("Sent to groups:"),
                     'reply_but_label':_("REPLY"),
                     'delete_but_label': _("DELETE")}
Пример #48
0
def format_element(bfo,
                   copyrights_separator=", ",
                   licenses_separator=", ",
                   instances_separator=", ",
                   link_to_licenses='yes',
                   auto_link_to_CERN_license='no',
                   remove_link_to_CERN_license='yes',
                   show_licenses='yes',
                   show_material="yes",
                   show_sponsor="yes",
                   license_to_url_kb='LICENSE2URL'):
    """
    Print copyright information

    Run this element to start the unit tests embedded within this element

    @param copyrights_separator: a separator between the copyrights of a bibdoc
    @param licenses_separator: a separator between the licenses of a bibdoc
    @param instances_separator: a separator between the licenses/copyrights of each BibDoc
    @param link_to_licenses: if 'yes', print the links to the licenses (otherwise just the name)
    @param auto_link_to_CERN_license: if 'yes', automatically add a link to CERN license when applicable (even if not in metadata)
    @param remove_link_to_CERN_license: if 'yes', remove link to CERN license when existing in the metadata. This option is ignored when auto_link_to_CERN_license is set to 'yes'
    @param show_licenses: if 'no', completely ignore license information
    @param show_material: if 'yes', material to which license/copyright applies ($3 subfield) is displayed
    @param license_to_url_kb: knowledge base used to map a license (as found in 540__a) to a URL
    """
    if auto_link_to_CERN_license.lower() == 'yes':
        # These option are mutually exclusive
        remove_link_to_CERN_license = 'no'
    add_CERN_license_link_to_bibdocs = []

    copyrights_info = bfo.fields('542__', escape=1)
    licenses_info = bfo.fields('540__', escape=1)

    copyrights_and_licenses_list = {}
    if copyrights_info or licenses_info:
        out = set()

        for copyright_info in copyrights_info:

            # Check to which bibdoc ID this copyright applies
            bibdoc_id = 0
            material = None
            if '8' in copyright_info:
                try:
                    bibdoc_id = int(copyright_info['8'])
                except:
                    pass
            elif '3' in copyright_info:
                # in that case, map using subfield $3
                material = copyright_info['3']

            # Retrieve what to display to user
            label = ''
            if 'f' in copyright_info:
                # Copyright message. Use this as label
                label = copyright_info['f']
            elif 'd' in copyright_info:
                # Copyright holder
                year = ''
                if 'g' in copyright_info:
                    # Year was given. Use it too
                    year = "%s " % copyright_info['g']
                label = "&copy; " + year + copyright_info['d']
                if copyright_info['d'] == 'CERN' and \
                   len(licenses_info) == 0 and \
                   auto_link_to_CERN_license.lower() == 'yes':
                    # There is not license, it is a CERN copyright and
                    # we would like to add a link to the "license
                    # page"
                    add_CERN_license_link_to_bibdocs.append(bibdoc_id)

            elif 'e' in copyright_info:
                # There is no copyright information available here?
                # Display contact person
                label = "Copyright info: " + copyright_info['e']
            else:
                continue

            # Append our copyright to the list, for given BibDoc
            if bibdoc_id not in copyrights_and_licenses_list and not (
                    material and bibdoc_id == 0):
                copyrights_and_licenses_list[bibdoc_id] = {
                    'copyright': [],
                    'license': []
                }
            elif material and material not in copyrights_and_licenses_list:
                copyrights_and_licenses_list[material] = {
                    'copyright': [],
                    'license': []
                }
            if not (material and bibdoc_id == 0):
                copyrights_and_licenses_list[bibdoc_id]['copyright'].append(
                    (label, copyright_info.get('d', '')))
            elif material in copyrights_and_licenses_list:
                copyrights_and_licenses_list[material]['copyright'].append(
                    (label, copyright_info.get('d', '')))

        # Now get the licenses. Try to map to a copyright
        for license_info in licenses_info:

            # Check to which bibdoc ID this license applies
            bibdoc_id = 0
            material = None
            sponsor_info = license_info.get('f', '')
            if license_info.has_key('8'):
                try:
                    bibdoc_id = int(license_info['8'])
                except:
                    pass
            elif '3' in license_info:
                # in that case, map using subfield $3
                material = license_info['3']
            label = ''
            url = ''
            license_body = ''
            if 'a' in license_info:
                # Terms governing use
                label = license_info['a']
            if 'b' in license_info:
                # Body imposing the license
                license_body = license_info['b']
            if not url and \
                   ((label in ('&copy; CERN', 'CERN')) or ('CERN' in license_body)) and \
                   auto_link_to_CERN_license.lower() == 'yes':
                url = CFG_CERN_LICENSE_URL
            if not url and license_to_url_kb:
                # Look for URL in knowledge base
                url = bfo.kb(license_to_url_kb, label)
            if 'u' in license_info:
                # License URL
                url = license_info['u']

            # Append our license to the list, for given BibDoc
            if bibdoc_id not in copyrights_and_licenses_list and not (
                    material and bibdoc_id == 0):
                copyrights_and_licenses_list[bibdoc_id] = {
                    'copyright': [],
                    'license': []
                }
            elif material and material not in copyrights_and_licenses_list:
                copyrights_and_licenses_list[material] = {
                    'copyright': [],
                    'license': []
                }
            if not (material and bibdoc_id == 0):
                copyrights_and_licenses_list[bibdoc_id]['license'].append(
                    [label, license_body, url, sponsor_info])
            elif copyrights_and_licenses_list.has_key(material):
                copyrights_and_licenses_list[material]['license'].append(
                    [label, license_body, url, sponsor_info])

        # We also need to add the auto CERN licenses to specified BibDocs
        for bibdoc_id in add_CERN_license_link_to_bibdocs:
            copyrights_and_licenses_list[bibdoc_id]['license'].append(
                ['', '', CFG_CERN_LICENSE_URL, ''])

        for linkage, copyright_and_license in iteritems(
                copyrights_and_licenses_list):
            copyrights = copyright_and_license['copyright']
            licenses = copyright_and_license['license']
            if len(copyrights) == 1 and len(licenses) == 1:
                # Great that is one particular case we can maybe handle
                copyright_label, copyright_holder = copyrights[0]
                license_label, license_body, license_url, dummy = licenses[0]
                if not license_label or copyright_holder in (
                        "&copy; " + license_label, license_label):
                    # Cool, we can squash things
                    if remove_link_to_CERN_license.lower() == 'yes' and \
                           license_url == CFG_CERN_LICENSE_URL:
                        # Thou must not display the license
                        license_url = ''
                    if show_material == 'yes' and not isinstance(linkage, int):
                        linkage_prefix = linkage + ': '
                    else:
                        linkage_prefix = ''
                    if license_url and link_to_licenses.lower() == 'yes':
                        out.add(
                            linkage_prefix +
                            create_html_link(license_url, {}, copyright_label))
                    else:
                        out.add(linkage_prefix + copyright_label)
                    continue

            # that is an 'else' for all other cases...
            # First print simply the copyrights
            copyright_tmp = copyrights_separator.join([
                copyright_label
                for (copyright_label, copyright_holder) in copyrights
            ])
            if show_material == 'yes' and not isinstance(linkage, int):
                copyright_tmp = linkage + ': ' + copyright_tmp

            license_tmp = []
            # Then do the licenses.

            # Check if we should prefix with "License(s):", i.e. when
            # keyword license is missing from license labels

            prefix_license = ''
            prefix_license_p = len([
                license_info for license_info in licenses
                if not 'license' in license_info[0].lower()
            ])
            if prefix_license_p:
                if len(licenses) == 1:
                    prefix_license = 'License: '
                else:
                    prefix_license = 'Licenses: '

            sponsor_tmp = []
            for license_label, license_body, license_url, sponsor_info in licenses:
                if sponsor_info:
                    sponsor_tmp.append(sponsor_info)
                if not license_label and license_url and link_to_licenses.lower(
                ) == 'yes':
                    license_tmp.append(
                        create_html_link(license_url, {}, 'License'))
                    prefix_license = ''  # no longer needed
                elif license_label and license_url and link_to_licenses.lower(
                ) == 'yes':
                    license_tmp.append(
                        create_html_link(license_url, {}, license_label))
                elif license_label:
                    license_tmp.append(license_label)

            if sponsor_tmp and show_sponsor == "yes" and 'SCOAP3' in sponsor_tmp:
                sponsored_by = 'sponsored by <a href="http://scoap3.org">SCOAP&#179;</a>'
            else:
                sponsored_by = ''

            if show_licenses.lower() != 'yes':
                # All that work for nothing!
                license_tmp = []
            if copyright_tmp and license_tmp:
                out.add('%s (%s%s)%s' % \
                         (copyright_tmp, \
                          prefix_license, \
                          licenses_separator.join(license_tmp), \
                          sponsored_by and ', %s' % sponsored_by or '' \
                         )\
                       )
            else:
                out.add(copyright_tmp + licenses_separator.join(license_tmp))

        return instances_separator.join(out).replace('©', '&copy;')
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
Пример #50
0
    def detailed_record_container_bottom(self,
                                         recid,
                                         tabs,
                                         ln=CFG_SITE_LANG,
                                         show_similar_rec_p=True,
                                         creationdate=None,
                                         modificationdate=None,
                                         show_short_rec_p=True):
        """Prints the box displayed in detailed records pages, with tabs at the top.

        Returns content as it is if the number of tabs for this record
        is smaller than 2

           Parameters:

         - recid *int* - the id of the displayed record
         - tabs ** - the tabs displayed at the top of the box.
         - ln *string* - the language of the page in which the box is displayed
         - show_similar_rec_p *bool* print 'similar records' link in the box
         - creationdate *string* - the creation date of the displayed record
         - modificationdate *string* - the last modification date of the displayed record
         - show_short_rec_p *boolean* - prints a very short version of the record as reminder.
        """
        # If no tabs, returns nothing
        if len(tabs) <= 1:
            return ''

        # load the right message language
        _ = gettext_set_language(ln)

        similar = ""

        if show_similar_rec_p and not CFG_INSPIRE_SITE:
            similar = create_html_link(
                websearch_templates.build_search_url(p='recid:%d' % \
                                                     recid,
                                                     rm='wrd',
                                                     ln=ln),
                {}, _("Similar records"),{'class': "moreinfo"})

        out = """
            <div class="bottom-left-folded">%(dates)s</div>
            <div class="bottom-right-folded" style="text-align:right;padding-bottom:2px;">
                <span class="moreinfo" style="margin-right:10px;">%(similar)s</span></div>
          </div>
      </div>
    </div>
    <br/>
    """ % {
            'similar': similar,
            'dates': creationdate and
            '<div class="recordlastmodifiedbox" style="position:relative;margin-left:1px">&nbsp;%(dates)s</div>'
            % {
                'dates':
                _("Record created %(x_date_creation)s, last modified %(x_date_modification)s",
                  x_date_creation=creationdate,
                  x_date_modification=modificationdate),
            } or ''
        }

        return out
Пример #51
0
def format_element(bfo, separator=" ", style='', img_style='', text_style='font-size:small',
                   print_links='yes', max_photos='', show_comment='yes',
                   img_max_width='250px', display_all_version_links='yes'):
    """
    Lists the photos of a record. Display the icon version, linked to
    its original version.

    This element works for photos appended to a record as BibDoc
    files, for which a preview icon has been generated. If there are
    several formats for one photo, use the first one found.

    @param separator: separator between each photo
    @param print_links: if 'yes', print links to the original photo
    @param style: style attributes of the whole image block. Eg: "padding:2px;border:1px"
    @param img_style: style attributes of the images. Eg: "width:50px;border:none"
    @param text_style: style attributes of the text. Eg: "font-size:small"
    @param max_photos: the maximum number of photos to display
    @param show_comment: if 'yes', display the comment of each photo
    @param display_all_version_links: if 'yes', print links to additional (sub)formats
    """
    photos = []
    bibarchive = BibRecDocs(bfo.recID)
    bibdocs = bibarchive.list_bibdocs()

    if max_photos.isdigit():
        max_photos = int(max_photos)
    else:
        max_photos = len(bibdocs)

    for doc in bibdocs[:max_photos]:
        found_icons = []
        found_url = ''
        for docfile in doc.list_latest_files():
            if docfile.is_icon():
                found_icons.append((
                                   docfile.get_size(),
                                   get_relative_url(docfile.get_url())
                                  ))
            else:
                found_url = get_relative_url(docfile.get_url())
        found_icons.sort()

        if found_icons:
            additional_links = ''
            name = bibarchive.get_docname(doc.id)
            comment = doc.list_latest_files()[0].get_comment()

            preview_url = None
            if len(found_icons) > 1:
                preview_url = get_relative_url(found_icons[1][1])
                additional_urls = [(docfile.get_size(), get_relative_url(docfile.get_url()), \
                                    docfile.get_superformat(), docfile.get_subformat()) \
                                   for docfile in doc.list_latest_files() if not docfile.is_icon()]
                additional_urls.sort()
                additional_links = [create_html_link(url, urlargd={}, \
                                                     linkattrd={'style': 'font-size:x-small'}, \
                                                     link_label="%s %s (%s)" % (format.strip('.').upper(), subformat, format_size(size))) \
                                    for (size, url, format, subformat) in additional_urls]
            img = '<img src="%(icon_url)s" alt="%(name)s" style="max-width:%(img_max_width)s;_width:%(img_max_width)s;%(img_style)s" />' % \
                  {'icon_url': cgi.escape(get_relative_url(found_icons[0][1]), True),
                   'name': cgi.escape(name, True),
                   'img_style': img_style,
                   'img_max_width': img_max_width}

            if print_links.lower() == 'yes':
                img = '<a href="%s">%s</a>' % (cgi.escape(preview_url or found_url, True), img)
            if display_all_version_links.lower() == 'yes' and additional_links:
                img += '<br />' + '&nbsp;'.join(additional_links) + '<br />'

            if show_comment.lower() == 'yes' and comment:
                img += '<div style="margin-auto;text-align:center;%(text_style)s">%(comment)s</div>' % \
                       {'comment': comment.replace('\n', '<br/>'),
                        'text_style': text_style}
            img = '<div style="vertical-align: middle;text-align:center;display:inline-block;display: -moz-inline-stack;zoom: 1;*display: inline;max-width:%(img_max_width)s;_width:%(img_max_width)s;text-align:center;%(style)s">%(img)s</div>' % \
                  {'img_max_width': img_max_width,
                   'style': style,
                   'img': img}

            photos.append(img)

    return '<div>' + separator.join(photos) + '</div>'
Пример #52
0
def format_element(bfo, width="", caption="yes", max_plots="3"):
    """
    Display image of the plot if we are in selected plots collections

    To achieve this, we take the pngs associated with this document

    @param width: the width of the returned image (Eg: '100px')
    @param caption: display the captions or not?
    @param max_plots: the maximum number of plots to display (-1 is all plots)
    """
    _ = gettext_set_language(bfo.lang)

    img_files = []
    try:
        max_plots = int(max_plots)
    except ValueError:
        # Someone tried to squeeze in something non-numerical. Hah!
        max_plots = 3

    link = ""
    bibarchive = BibRecDocs(bfo.recID)

    if width != "":
        width = 'width="%s"' % width

    for doc in bibarchive.list_bibdocs(doctype="Plot"):
        for _file in doc.list_latest_files():
            if _file.subformat == "context":
                # Ignore context files
                continue

            caption_text = _file.get_description()[5:]
            index = int(_file.get_description()[:5])
            img_location = _file.get_url()

            img = '<img style="vertical-align:middle;" src="%s" title="%s" %s/>' % \
                  (img_location, caption_text, width)

            plotlink = create_html_link(
                urlbase='%s/%s/%s/plots#%d' %
                (CFG_BASE_URL, CFG_SITE_RECORD, bfo.recID, index),
                urlargd={},
                link_label=img)

            img_files.append((index, plotlink))

    img_files = sorted(img_files, key=lambda x: x[0])
    if max_plots > 0:
        img_files = img_files[:max_plots]

    if len(img_files) >= max_plots:
        link = "<a href='/%s/%s/plots'>%s</a>" % \
               (CFG_SITE_RECORD, bfo.recID, _("Show more plots"))

    for index in range(len(img_files)):
        img_files[index] = img_files[index][1]

    if len(img_files) == 0:
        return ''

    return '<div style="overflow-x:auto;display:inline;width:100%;">' +\
           " ".join(img_files) + ' ' + link + '</div>'