def get_user_collections(req):
    """
    Return collections for which the user is moderator
    """
    user_info = collect_user_info(req)
    res = []
    collections = run_sql('SELECT name FROM collection')
    for collection in collections:
        collection_emails = acc_get_authorized_emails('moderatecomments', collection=collection[0])
        if user_info['email'] in collection_emails or isUserAdmin(user_info):
            res.append(collection[0])
    return res
def get_user_collections(req):
    """
    Return collections for which the user is moderator
    """
    user_info = collect_user_info(req)
    res = []
    collections = run_sql('SELECT name FROM collection')
    for collection in collections:
        collection_emails = acc_get_authorized_emails('moderatecomments', collection=collection[0])
        if user_info['email'] in collection_emails or isUserAdmin(user_info):
            res.append(collection[0])
    return res
Example #3
0
    def _precache(self, info, force=False):
        """
        Calculate prermitions for user actions.

        FIXME: compatibility layer only !!!
        """
        # get autorization key
        acc_key = self.get_acc_key()
        acc = cache.get(acc_key)
        if not force and acc_key is not None and acc is not None:
            return acc

        #FIXME: acc_authorize_action should use flask request directly
        user_info = info
        user_info.update(self.req)

        from invenio.webuser import isUserSubmitter, isUserReferee, \
            isUserAdmin, isUserSuperAdmin
        from invenio.access_control_engine import acc_authorize_action
        from invenio.access_control_admin import acc_get_role_id, \
            acc_is_user_in_role
        from invenio.search_engine import get_permitted_restricted_collections

        data = {}
        data['precached_permitted_restricted_collections'] = \
            get_permitted_restricted_collections(user_info)
        data['precached_usebaskets'] = acc_authorize_action(
            user_info, 'usebaskets')[0] == 0
        data['precached_useloans'] = acc_authorize_action(
            user_info, 'useloans')[0] == 0
        data['precached_usegroups'] = acc_authorize_action(
            user_info, 'usegroups')[0] == 0
        data['precached_usealerts'] = acc_authorize_action(
            user_info, 'usealerts')[0] == 0
        data['precached_usemessages'] = acc_authorize_action(
            user_info, 'usemessages')[0] == 0
        data['precached_usestats'] = acc_authorize_action(
            user_info, 'runwebstatadmin')[0] == 0
        data['precached_viewsubmissions'] = isUserSubmitter(user_info)
        data['precached_useapprove'] = isUserReferee(user_info)
        data['precached_useadmin'] = isUserAdmin(user_info)
        data['precached_usesuperadmin'] = isUserSuperAdmin(user_info)
        data['precached_canseehiddenmarctags'] = acc_authorize_action(
            user_info, 'runbibedit')[0] == 0
        usepaperclaim = False
        usepaperattribution = False
        viewclaimlink = False

        if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(
                user_info, acc_get_role_id("paperclaimviewers"))):
            usepaperclaim = True

        if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(
                user_info, acc_get_role_id("paperattributionviewers"))):
            usepaperattribution = True

        viewlink = False
        try:
            viewlink = session['personinfo']['claim_in_process']
        except (KeyError, TypeError):
            pass

        if (CFG_BIBAUTHORID_ENABLED and usepaperattribution and viewlink):
            viewclaimlink = True


#                if (CFG_BIBAUTHORID_ENABLED
#                    and ((usepaperclaim or usepaperattribution)
#                         and acc_is_user_in_role(data, acc_get_role_id("paperattributionlinkviewers")))):
#                    viewclaimlink = True

        data['precached_viewclaimlink'] = viewclaimlink
        data['precached_usepaperclaim'] = usepaperclaim
        data['precached_usepaperattribution'] = usepaperattribution

        cache.set(acc_key,
                  data,
                  timeout=CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT * 3600)
        return data
Example #4
0
def format_element(bfo, default='', separator='; ', style='',
                   show_icons='no', prefix='', suffix=''):
    """ Creates html of links based on metadata
    @param separator (separates instances of links)
    @param prefix
    @param suffix
    @param show_icons default = no
    @param style options CSS style for link
    """
    _ = gettext_set_language(bfo.lang)
    if style != "":
        style = ' class="' + style + '"'

    links = []

    # ADS/CDS/KEKSCAN/HAL links
    # external identifiers in tag 035__a along with service label in 035__9
    identifiers = bfo.fields('035__')
    adslinked = False
    for ident in identifiers:
        provenance = ident.get('9', None)
        extid = ident.get('a', None)
        if provenance is None or extid is None:
            continue

        if provenance == 'KEKSCAN':
            extid = extid.replace("-", "")
            links.append('<a%s href="%s%s"> KEK scanned document</a>' %
                         (style, KEK, extid))
        elif provenance == 'CDS':
            links.append('<a%s href="%s%s"> CERN Document Server</a>' %
                         (style, CDS, extid))
        elif provenance == 'ADS':
            extid = extid.replace('&', '%26')  # A&A etc.
            links.append('<a%s href="%s%s"> ADS Abstract Service</a>' %
                         (style, ADSABS, extid))
            adslinked = True
        elif provenance == 'HAL':
            from invenio.webuser import isUserAdmin
            if isUserAdmin(bfo.user_info):
                links.append('<a %s href="%s%s"> HAL Archives Ouvertes</a>' %
                             (style, HAL, extid))

    # fallback ADS link via arXiv:e-print
    if not adslinked:
        identifiers = bfo.fields('037__')
        eprints = set()  # avoid duplicate links
        for ident in identifiers:
            if ident.get('9', '') == 'arXiv' \
               and ident.get('a', None) is not None:
                eprints.add(ident.get('a', ''))
        if eprints:
            adslinked = True
            for eprint in eprints:
                links.append('<a href="%s%s"> ADS Abstract Service</a>'
                             % (ADSABS, eprint))

    # external identifiers in tag 035__a along with service label in 035__9
    urls = bfo.fields('035__')
    for url in urls:
        provenance = url.get('9', None)
        extid = url.get('a', None)
        if provenance is None or extid is None:
            continue

        provenance = provenance.lower()
        if provenance == "msnet":
            links.append('<a%s href="%s%s"> AMS MathSciNet</a>' %
                         (style, MSNET, extid))
        elif provenance == "zblatt":
            links.append('<a%s href="%s%s"> zbMATH</a>' %
                         (style, ZBLATT, extid))
        elif provenance == "euclid":
            links.append('<a%s href="%s%s"> Project Euclid</a>' %
                         (style, EUCLID, extid))
        elif provenance == "osti":
            links.append('<a%s href="%s%s"> OSTI Information Bridge Server</a>' %
                         (style, OSTI, extid))

    # now look for explicit URLs
    # might want to check that we aren't repeating things from above...
    # Note: excluding self-links
    urls = bfo.fields('8564_')
    allowed_doctypes = ["INSPIRE-PUBLIC", "SCOAP3", "PoS"]
    for url in urls:
        if url.get("y", "").lower() not in \
           ("adsabs", "euclid", "msnet", "osti", "zblatt"):
            if '.png' not in url.get('u', '') and not (
                    url.get('y', '').lower().startswith("fermilab") and
                    bfo.field("710__g").lower() in
                    ('atlas collaboration', 'cms collaboration')):
                if url.get('y', '').upper() != "DURHAM":
                    if url.get("u", '') and \
                       url.get('y', 'Fulltext').upper() != "DOI" and not \
                       url.get('u', '').startswith(CFG_SITE_URL):
                        links.append('<a %s href="%s">%s</a>' %
                                     (style, url.get("u", ''),
                                      _lookup_url_name(bfo, url.get(
                                          'y', 'Fulltext'))))
                    elif url.get("u", '').startswith(CFG_SITE_URL) and \
                        (url.get("u", '').lower().endswith(".pdf") or
                         url.get("u", '').lower().endswith(
                             '.pdf?subformat=pdfa')) and \
                            bibdocfile_url_to_bibdoc(url.get('u')).doctype in \
                            allowed_doctypes:
                        links.append('<a %s href="%s">%s</a>' %
                                     (style, url.get("u", ''),
                                      _lookup_url_name(bfo, url.get(
                                          'y', 'Fulltext'))))

    # put it all together
    if links:
        if show_icons.lower() == 'yes':
            img = '<img style="border:none" \
            src="%s/img/file-icon-text-12x16.gif" alt="%s"/>' \
            % (CFG_BASE_URL, _("Download fulltext"))
            links = [img + '<small>' + link + '</small>' for link in links]
        return prefix + separator.join(links) + suffix
    else:
        return default
Example #5
0
    def tmpl_pagefooter(self,
                        req=None,
                        ln=CFG_SITE_LANG,
                        lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

        Parameters:

        - 'ln' *string* - The language to display

        - 'lastupdated' *string* - when the page was last updated

        - 'pagefooteradd' *string* - additional page footer HTML code

        Output:

        - HTML code of the page headers
        """
        from invenio.search_engine import guess_primary_collection_of_a_record

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

        if lastupdated and lastupdated != '$Date$':
            if lastupdated.startswith("$Date: ") or \
            lastupdated.startswith("$Id: "):
                lastupdated = convert_datestruct_to_dategui(\
                                 convert_datecvs_to_datestruct(lastupdated),
                                 ln=ln)
            msg_lastupdated = _("Last updated") + ": " + lastupdated
        else:
            msg_lastupdated = ""

        # Prepare Piwik custom variables if we are in a detailed record page

        custom_variables = ""
        record_collection = ""
        page_type = ""

        parsed_uri = urlparse(req.unparsed_uri)

        # HACK: I know it's horrible code. :-(
        record_page_match = re.match(
            "^/record/(?P<recid>[0-9]+)(/(?P<page_type>.+)?)?$",
            parsed_uri.path)
        if record_page_match:
            record_collection = guess_primary_collection_of_a_record(
                record_page_match.group('recid'))
            page_type = record_page_match.group('page_type') or 'detailed'
        if re.match("^/search/?$", parsed_uri.path):
            cc = parse_qs(parsed_uri.query).get('cc', [CFG_SITE_NAME])
            record_collection = cc.pop()
        collection_page_match = re.match(
            "^/$|^/collection/(?P<collection>.+)/?$", parsed_uri.path)
        if collection_page_match:
            record_collection = collection_page_match.groupdict().get(
                'collection', CFG_SITE_NAME)
        if record_collection:
            custom_variables = """\
_paq.push(['setCustomVariable',
          1, // Index, the number from 1 to 5 where this custom variable name is stored
          "Collection", // Name, the name of the variable
          %(collection_name)s, // Value
          "page" // Scope of the custom variable
          ]);
          """ % {
                'collection_name': js_escape(record_collection)
            }

        if page_type:
            custom_variables += """\
_paq.push(['setCustomVariable',
          2,
          "Type",
          %(page_type)s,
          "page"
          ]);
_paq.push(['setCustomVariable',
          3,
          "CollectionType",
          %(page_collection_type)s,
          "page"
          ]);
          """ % {
                'page_type': js_escape(page_type),
                'page_collection_type':
                js_escape(record_collection + page_type)
            }

        out = """\
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/terms-of-use">%(msg_terms)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/privacy-policy">%(msg_privacy)s</a>
  <br />
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
 </div>
 <div class="pagefooterstriperight">
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>
""" % {
            'siteurl': CFG_BASE_URL,
            'sitesecureurl': CFG_SITE_SECURE_URL,
            'ln': ln,
            'langlink': '?ln=' + ln,
            'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
            'sitesupportemail': '*****@*****.**',
            'msg_search': _("Search"),
            'msg_help': _("Help"),
            'msg_terms': _("Terms of use"),
            'msg_privacy': _("Privacy policy"),
            'msg_poweredby': _("Powered by"),
            'msg_maintainedby': _("Problems/Questions to"),
            'msg_lastupdated': msg_lastupdated,
            'languagebox': self.tmpl_language_selection_box(req, ln),
            'version': self.trim_version(CFG_VERSION),
            'pagefooteradd': pagefooteradd,
        }
        if not isUserAdmin(collect_user_info(req)):
            out += """\
<!-- Piwik -->
<script type="text/javascript">
  try {
    var _paq = _paq || [];
    _paq.push(['trackPageView']);
    _paq.push(['enableLinkTracking']);
    (function() {
        var u="//piwik.inspirehep.net/";
        _paq.push(['setTrackerUrl', u+'piwik.php']);
        _paq.push(['setSiteId', 8]);
        %(custom_variables)s
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
    })();}
    catch(err) {
        (function() {
            var img = document.createElement('img');
            img.src = '//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1';
            document.body.appendChild(img);
    })();
    }
</script>
<noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
""" % {
                'custom_variables': custom_variables
            }

        out += """\
</body>
</html>
"""
        return out
    def tmpl_pagefooter(self, req=None, ln=CFG_SITE_LANG, lastupdated=None,
                        pagefooteradd=""):
        """Creates a page footer

        Parameters:

        - 'ln' *string* - The language to display

        - 'lastupdated' *string* - when the page was last updated

        - 'pagefooteradd' *string* - additional page footer HTML code

        Output:

        - HTML code of the page headers
        """
        from invenio.search_engine import guess_primary_collection_of_a_record

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

        if lastupdated and lastupdated != '$Date$':
            if lastupdated.startswith("$Date: ") or \
            lastupdated.startswith("$Id: "):
                lastupdated = convert_datestruct_to_dategui(\
                                 convert_datecvs_to_datestruct(lastupdated),
                                 ln=ln)
            msg_lastupdated = _("Last updated") + ": " + lastupdated
        else:
            msg_lastupdated = ""

        # Prepare Piwik custom variables if we are in a detailed record page

        custom_variables = ""
        record_collection = ""
        page_type = ""

        parsed_uri = urlparse(req.unparsed_uri)

        # HACK: I know it's horrible code. :-(
        record_page_match = re.match("^/record/(?P<recid>[0-9]+)(/(?P<page_type>.+)?)?$", parsed_uri.path)
        if record_page_match:
            record_collection = guess_primary_collection_of_a_record(record_page_match.group('recid'))
            page_type = record_page_match.group('page_type') or 'detailed'
        if re.match("^/search/?$", parsed_uri.path):
            cc = parse_qs(parsed_uri.query).get('cc', [CFG_SITE_NAME])
            record_collection = cc.pop()
        collection_page_match = re.match("^/$|^/collection/(?P<collection>.+)/?$", parsed_uri.path)
        if collection_page_match:
            record_collection = collection_page_match.groupdict().get('collection', CFG_SITE_NAME)
        if record_collection:
            custom_variables = """\
_paq.push(['setCustomVariable',
          1, // Index, the number from 1 to 5 where this custom variable name is stored
          "Collection", // Name, the name of the variable
          %(collection_name)s, // Value
          "page" // Scope of the custom variable
          ]);
          """ % {
                'collection_name': js_escape(record_collection)
            }

        if page_type:
            custom_variables += """\
_paq.push(['setCustomVariable',
          2,
          "Type",
          %(page_type)s,
          "page"
          ]);
_paq.push(['setCustomVariable',
          3,
          "CollectionType",
          %(page_collection_type)s,
          "page"
          ]);
          """ % {
                'page_type': js_escape(page_type),
                'page_collection_type': js_escape(record_collection + page_type)
            }

        out = """\
<div class="pagefooter">
%(pagefooteradd)s
<!-- replaced page footer -->
 <div class="pagefooterstripeleft">
  %(sitename)s&nbsp;::&nbsp;<a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/terms-of-use">%(msg_terms)s</a>&nbsp;::&nbsp;
  <a class="footer" href="%(siteurl)s/info/general/privacy-policy">%(msg_privacy)s</a>
  <br />
  %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s
  <br />
  %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a>
  <br />
  %(msg_lastupdated)s
 </div>
 <div class="pagefooterstriperight">
  %(languagebox)s
 </div>
<!-- replaced page footer -->
</div>
""" % {
          'siteurl' : CFG_BASE_URL,
          'sitesecureurl' : CFG_SITE_SECURE_URL,
          'ln' : ln,
          'langlink': '?ln=' + ln,

          'sitename' : CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
          'sitesupportemail' : '*****@*****.**',

          'msg_search' : _("Search"),
          'msg_help' : _("Help"),

          'msg_terms': _("Terms of use"),
          'msg_privacy': _("Privacy policy"),

          'msg_poweredby' : _("Powered by"),
          'msg_maintainedby' : _("Problems/Questions to"),

          'msg_lastupdated' : msg_lastupdated,
          'languagebox' : self.tmpl_language_selection_box(req, ln),
          'version' : self.trim_version(CFG_VERSION),

          'pagefooteradd' : pagefooteradd,
          }
        if not isUserAdmin(collect_user_info(req)):
            out += """\
<!-- Piwik -->
<script type="text/javascript">
  try {
    var _paq = _paq || [];
    _paq.push(['trackPageView']);
    _paq.push(['enableLinkTracking']);
    (function() {
        var u="//piwik.inspirehep.net/";
        _paq.push(['setTrackerUrl', u+'piwik.php']);
        _paq.push(['setSiteId', 8]);
        %(custom_variables)s
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
    })();}
    catch(err) {
        (function() {
            var img = document.createElement('img');
            img.src = '//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1';
            document.body.appendChild(img);
    })();
    }
</script>
<noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=8&amp;rec=1&amp;bots=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
""" % {'custom_variables': custom_variables}

        out += """\
</body>
</html>
"""
        return out
Example #7
0
def format_element(bfo,
                   default='',
                   separator='; ',
                   style='',
                   show_icons='no',
                   prefix='',
                   suffix=''):
    """ Creates html of links based on metadata
    @param separator (separates instances of links)
    @param prefix
    @param suffix
    @param show_icons default = no
    @param style options CSS style for link
    """
    _ = gettext_set_language(bfo.lang)
    if style != "":
        style = ' class="' + style + '"'

    links = []

    # ADS/CDS/KEKSCAN/INIS/HAL links
    # external identifiers in tag 035__a along with service label in 035__9
    identifiers = bfo.fields('035__')
    adslinked = False
    for ident in identifiers:
        provenance = ident.get('9', None)
        extid = ident.get('a', None)
        if provenance is None or extid is None:
            continue

        if provenance == 'KEKSCAN':
            extid = extid.replace("-", "")
            if len(extid) == 7 and not extid.startswith(
                    '19') and not extid.startswith('20'):
                year = '19' + extid[:2]
            elif len(extid) == 9:
                year = extid[:4]
                extid = extid[2:]
            else:
                # likely bad id
                continue
            yymm = extid[:4]
            links.append(
                '<a%s href="%s/%s/%s/%s.pdf"> KEK scanned document</a>' %
                (style, KEK, year, yymm, extid))
        elif provenance == 'CDS':
            links.append('<a%s href="%s%s"> CERN Document Server</a>' %
                         (style, CDS, extid))
        elif provenance == 'ADS':
            extid = extid.replace('&', '%26')  # A&A etc.
            links.append('<a%s href="%s%s"> ADS Abstract Service</a>' %
                         (style, ADSABS, extid))
            adslinked = True
        elif provenance == 'INIS':
            links.append('<a%s href="%s%s"> INIS Repository</a>' %
                         (style, INIS, extid))
        elif provenance == 'HAL':
            from invenio.webuser import isUserAdmin
            if isUserAdmin(bfo.user_info):
                links.append('<a %s href="%s%s"> HAL Archives Ouvertes</a>' %
                             (style, HAL, extid))

    # fallback ADS link via arXiv:e-print
    if not adslinked:
        identifiers = bfo.fields('037__')
        eprints = set()  # avoid duplicate links
        for ident in identifiers:
            if ident.get('9', '') == 'arXiv' \
               and ident.get('a', None) is not None:
                eprints.add(ident.get('a', ''))
        if eprints:
            adslinked = True
            for eprint in eprints:
                links.append('<a href="%s%s"> ADS Abstract Service</a>' %
                             (ADSABS, eprint))

    # external identifiers in tag 035__a along with service label in 035__9
    urls = bfo.fields('035__')
    for url in urls:
        provenance = url.get('9', None)
        extid = url.get('a', None)
        if provenance is None or extid is None:
            continue

        provenance = provenance.lower()
        if provenance == "msnet":
            links.append('<a%s href="%s%s"> AMS MathSciNet</a>' %
                         (style, MSNET, extid))
        elif provenance == "zblatt":
            links.append('<a%s href="%s%s"> zbMATH</a>' %
                         (style, ZBLATT, extid))
        elif provenance == "euclid":
            links.append('<a%s href="%s%s"> Project Euclid</a>' %
                         (style, EUCLID, extid))
        elif provenance == "osti":
            links.append(
                '<a%s href="%s%s"> OSTI Information Bridge Server</a>' %
                (style, OSTI, extid))

    # now look for explicit URLs
    # might want to check that we aren't repeating things from above...
    # Note: excluding self-links
    urls = bfo.fields('8564_')
    allowed_doctypes = ["INSPIRE-PUBLIC", "SCOAP3", "PoS"]
    for url in urls:
        if url.get("y", "").lower() not in \
           ("adsabs", "euclid", "msnet", "osti", "zblatt"):
            if '.png' not in url.get('u', '') and not (
                    url.get('y', '').lower().startswith("fermilab")
                    and bfo.field("710__g").lower() in
                ('atlas collaboration', 'cms collaboration')):
                if url.get('y', '').upper() != "DURHAM":
                    if url.get("u", '') and \
                       url.get('y', 'Fulltext').upper() != "DOI" and not \
                       url.get('u', '').startswith(CFG_SITE_URL):
                        links.append(
                            '<a %s href="%s">%s</a>' %
                            (style, url.get("u", ''),
                             _lookup_url_name(bfo, url.get('y', 'Fulltext'))))
                    elif url.get("u", '').startswith(CFG_SITE_URL) and \
                        (url.get("u", '').lower().endswith(".pdf") or
                         url.get("u", '').lower().endswith(
                             '.pdf?subformat=pdfa')) and \
                            bibdocfile_url_to_bibdoc(url.get('u')).doctype in \
                            allowed_doctypes:
                        links.append(
                            '<a %s href="%s">%s</a>' %
                            (style, url.get("u", ''),
                             _lookup_url_name(bfo, url.get('y', 'Fulltext'))))

    # put it all together
    if links:
        if show_icons.lower() == 'yes':
            img = '<img style="border:none" \
            src="%s/img/file-icon-text-12x16.gif" alt="%s"/>' \
            % (CFG_BASE_URL, _("Download fulltext"))
            links = [img + '<small>' + link + '</small>' for link in links]
        return prefix + separator.join(links) + suffix
    else:
        return default
Example #8
0
def format_element(bfo, default="", separator="; ", style="", show_icons="no", prefix="", suffix=""):
    """ Creates html of links based on metadata
    @param separator (separates instances of links)
    @param prefix
    @param suffix
    @param show_icons default = no
    @param style options CSS style for link
    """
    _ = gettext_set_language(bfo.lang)
    if style != "":
        style = ' class="' + style + '"'

    links = []

    # ADS/CDS/KEKSCAN/INIS/HAL links
    # external identifiers in tag 035__a along with service label in 035__9
    identifiers = bfo.fields("035__")
    adslinked = False
    for ident in identifiers:
        provenance = ident.get("9", None)
        extid = ident.get("a", None)
        if provenance is None or extid is None:
            continue

        if provenance == "KEKSCAN":
            extid = extid.replace("-", "")
            if len(extid) == 7 and not extid.startswith("19") and not extid.startswith("20"):
                year = "19" + extid[:2]
            elif len(extid) == 9:
                year = extid[:4]
                extid = extid[2:]
            else:
                # likely bad id
                continue
            yymm = extid[:4]
            links.append('<a%s href="%s/%s/%s/%s.pdf"> KEK scanned document</a>' % (style, KEK, year, yymm, extid))
        elif provenance == "CDS":
            links.append('<a%s href="%s%s"> CERN Document Server</a>' % (style, CDS, extid))
        elif provenance == "ADS":
            extid = extid.replace("&", "%26")  # A&A etc.
            links.append('<a%s href="%s%s"> ADS Abstract Service</a>' % (style, ADSABS, extid))
            adslinked = True
        elif provenance == "INIS":
            links.append('<a%s href="%s%s"> INIS Repository</a>' % (style, INIS, extid))
        elif provenance == "HAL":
            from invenio.webuser import isUserAdmin

            if isUserAdmin(bfo.user_info):
                links.append('<a %s href="%s%s"> HAL Archives Ouvertes</a>' % (style, HAL, extid))

    # fallback ADS link via arXiv:e-print
    if not adslinked:
        identifiers = bfo.fields("037__")
        eprints = set()  # avoid duplicate links
        for ident in identifiers:
            if ident.get("9", "") == "arXiv" and ident.get("a", None) is not None:
                eprints.add(ident.get("a", ""))
        if eprints:
            adslinked = True
            for eprint in eprints:
                links.append('<a href="%s%s"> ADS Abstract Service</a>' % (ADSABS, eprint))

    # external identifiers in tag 035__a along with service label in 035__9
    urls = bfo.fields("035__")
    for url in urls:
        provenance = url.get("9", None)
        extid = url.get("a", None)
        if provenance is None or extid is None:
            continue

        provenance = provenance.lower()
        if provenance == "msnet":
            links.append('<a%s href="%s%s"> AMS MathSciNet</a>' % (style, MSNET, extid))
        elif provenance == "zblatt":
            links.append('<a%s href="%s%s"> zbMATH</a>' % (style, ZBLATT, extid))
        elif provenance == "euclid":
            links.append('<a%s href="%s%s"> Project Euclid</a>' % (style, EUCLID, extid))
        elif provenance == "osti":
            links.append('<a%s href="%s%s"> OSTI Information Bridge Server</a>' % (style, OSTI, extid))

    # now look for explicit URLs
    # might want to check that we aren't repeating things from above...
    # Note: excluding self-links
    urls = bfo.fields("8564_")
    allowed_doctypes = ["INSPIRE-PUBLIC", "SCOAP3", "PoS"]
    for url in urls:
        if url.get("y", "").lower() not in ("adsabs", "euclid", "msnet", "osti", "zblatt"):
            if ".png" not in url.get("u", "") and not (
                url.get("y", "").lower().startswith("fermilab")
                and bfo.field("710__g").lower() in ("atlas collaboration", "cms collaboration")
            ):
                if url.get("y", "").upper() != "DURHAM":
                    if (
                        url.get("u", "")
                        and url.get("y", "Fulltext").upper() != "DOI"
                        and not url.get("u", "").startswith(CFG_SITE_URL)
                    ):
                        links.append(
                            '<a %s href="%s">%s</a>'
                            % (style, url.get("u", ""), _lookup_url_name(bfo, url.get("y", "Fulltext")))
                        )
                    elif (
                        url.get("u", "").startswith(CFG_SITE_URL)
                        and (
                            url.get("u", "").lower().endswith(".pdf")
                            or url.get("u", "").lower().endswith(".pdf?subformat=pdfa")
                        )
                        and bibdocfile_url_to_bibdoc(url.get("u")).doctype in allowed_doctypes
                    ):
                        links.append(
                            '<a %s href="%s">%s</a>'
                            % (style, url.get("u", ""), _lookup_url_name(bfo, url.get("y", "Fulltext")))
                        )

    # put it all together
    if links:
        if show_icons.lower() == "yes":
            img = (
                '<img style="border:none" \
            src="%s/img/file-icon-text-12x16.gif" alt="%s"/>'
                % (CFG_BASE_URL, _("Download fulltext"))
            )
            links = [img + "<small>" + link + "</small>" for link in links]
        return prefix + separator.join(links) + suffix
    else:
        return default