Exemplo n.º 1
0
def create_year_selectbox(name, from_year=-1, length=10, selected_year=0, ln=None):
    """Creates an HTML menu (dropdownbox) for year selection.

    @param name: name of control( i.e. name of the variable you'll get)
    @param from_year: year on which to begin. if <0 assume it is current year
    @param length: number of items in menu
    @param selected_year: initial selected year (if in range), else: label is
                          selected
    @param ln: language
    @return: html as string
    """
    ln = default_ln(ln)
    _ = gettext_set_language(ln)
    if from_year < 0:
        from_year = time.localtime()[0]
    out = '<select name="%s">\n' % name
    out += '  <option value="0"'
    if selected_year == 0:
        out += ' selected="selected"'
    out += ">%s</option>\n" % _("Year")
    for i in range(from_year, from_year + length):
        out += '<option value="%i"' % i
        if i == selected_year:
            out += ' selected="selected"'
        out += ">%i</option>\n" % i
    out += "</select>\n"
    return out
Exemplo n.º 2
0
    def tmpl_format_list_of_keywords(
        self, keywords, ln=None, generate=None, sorting=None, type=None, numbering=None, showall=None
    ):
        """Formats the list of keywords"""

        _ = gettext_set_language(ln)
        format_link = self.tmpl_href

        sorted_keywords = _get_sorted_keywords(keywords)

        _numbering = numbering is "on"
        out = []
        for type in ("composite", "single"):
            if sorted_keywords["unweighted"][type]:
                out.append("<b>%s</b>" % _("Unweighted %(x_name)s keywords:", x_name=type))
                for keyword, info in sorted_keywords["unweighted"][type]:
                    out.append(format_link(keyword, ln))

        for type in ("composite", "single"):
            if sorted_keywords["weighted"][type]:
                out.append("<b>%s</b>" % _("Weighted %(x_name)s keywords:", x_name=type))
                for keyword, info in sorted_keywords["weighted"][type]:
                    if _numbering:
                        out.append("%s (%d)" % (format_link(keyword, ln), len(info[0])))
                    else:
                        out.append(format_link(keyword, ln))

        return """
        <div class="cloud">
          %s
        </div>""" % (
            "<br/>".join(out)
        )
Exemplo n.º 3
0
 def tmpl_page_list(
     self, keywords, req=None, ln=None, generate=None, sorting=None, type=None, numbering=None, showall=None
 ):
     """Page with keywords as a list"""
     _ = gettext_set_language(ln)
     kw = self.tmpl_list_of_keywords(
         keywords, ln=ln, generate=generate, sorting=sorting, type=type, numbering=numbering, showall=showall
     )
     msg = _(
         _(
             'Automatically generated <span class="keyword single">single</span>,\
     <span class="keyword composite">composite</span>, <span class="keyword author-kw">author</span>,\
     and <span class="keyword other-kw">other keywords</span>.'
         )
     )
     return self.tmpl_page(
         keywords=keywords,
         middle=kw,
         bottom=msg,
         req=req,
         ln=ln,
         generate=generate,
         sorting=sorting,
         type=type,
         numbering=numbering,
         showall=showall,
     )
Exemplo n.º 4
0
    def external_collection_overview(self, lang=CFG_SITE_LANG, engine_list=()):
        """Prints results overview box with links to particular collections below.
        lang: The language to display
        engine_list: The external engines to be used"""

        if len(engine_list) < 1:
            return ""

        _ = gettext_set_language(lang)

        out = """
  <table class="externalcollectionsresultsbox">
    <thead>
      <tr>
        <th class="externalcollectionsresultsboxheader"><strong>%s</strong></th>
      </tr>
    </thead>
      <tbody>
        <tr>
          <td class="externalcollectionsresultsboxbody"> """ % _("External collections results overview:")

        for engine in engine_list:
            internal_name = get_link_name(engine.name)
            name = _(engine.name)
            out += """<strong><a href="#%(internal_name)s">%(name)s</a></strong><br />""" % locals()
        out += """
        </td>
      </tr>
    </tbody>
  </table>
  """
        return out
Exemplo n.º 5
0
def perform_request_delete_msg(uid, msgid, ln=CFG_SITE_LANG):
    """
    Delete a given message from user inbox
    @param uid: user id (int)
    @param msgid: message id (int)
    @param ln: language
    @return: body with warnings
    """
    _ = gettext_set_language(ln)

    warnings = []
    infos = []
    body = ""

    if (db.check_user_owns_message(uid, msgid) == 0):
        # The user doesn't own this message
        try:
            raise InvenioWebMessageError(_('Sorry, this message in not in your mailbox.'))
        except InvenioWebMessageError as exc:
            register_exception()
            body = webmessage_templates.tmpl_error(exc.message, ln)
            return body
    else:
        if (db.delete_message_from_user_inbox(uid, msgid) == 0):
            warnings.append(_("The message could not be deleted."))
        else:
            infos.append(_("The message was successfully deleted."))
    return perform_request_display(uid, warnings, infos, ln)
Exemplo n.º 6
0
def format_element(bfo):
    ln = bfo.lang
    _ = gettext_set_language(ln)

    info = bfo.field('711__')

    if not info:
        return ""

    ret = []
    if 'a' in info and 'g' in info:
        ret.append("%(a)s (%(g)s)")
    elif 'a' in info:
        ret.append("%(a)s")

    if 'c' in info:
        ret.append("%(c)s")
    if 'w' in info:
        ret.append("%(w)s")
    if 'd' in info:
        ret.append("%(d)s")

    ret = ", ".join(ret)
    ret = "%s." % ret

    return ret % info
Exemplo n.º 7
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
Exemplo n.º 8
0
def users(req, ln=CFG_SITE_LANG):
    """
    View a list of all the users that have been reported, sorted by most reported
    @param req: request object to obtain user information
    @param ln: language
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    try:
        uid = getUid(req)
    except Error:
        return page(title=_("Internal Error"),
                    body = create_error_box(req, verbose=0, ln=ln),
                    description="%s - Internal Error" % CFG_SITE_NAME,
                    keywords="%s, Internal Error" % CFG_SITE_NAME,
                    language=ln,
                    req=req)

    (auth_code, auth_msg) = check_user(req,'cfgwebcomment')
    if (auth_code != 'false'):
        return page(title=_("View all reported users"),
                    body=perform_request_users(ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
    else:

        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
Exemplo n.º 9
0
def index(req, ln=CFG_SITE_LANG):
    """
    Menu of admin options
    @param ln: language
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links +=' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    try:
        uid = getUid(req)
    except Error:
        return page(title=_("Internal Error"),
                    body = create_error_box(req, verbose=0, ln=ln),
                    description="%s - Internal Error" % CFG_SITE_NAME,
                    keywords="%s, Internal Error" % CFG_SITE_NAME,
                    language=ln,
                    req=req)

    (auth_code, auth_msg) = check_user(req, 'cfgwebcomment')
    if (auth_code != 'false'):
        return page(title=_("WebComment Admin"),
                body=perform_request_index(ln=ln),
                uid=uid,
                language=ln,
                navtrail = navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
    else:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
Exemplo n.º 10
0
def hot(req, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    View most active comments/reviews
    @param req: request object to obtain user information
    @param ln: language
    @param comments: boolean enabled for comments, disabled for reviews
    @param top: number of results to be shown
    @param collection: filter results by collection
    """
    ln = wash_language(ln)
    collection = wash_url_argument(collection, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgwebcomment')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    return page(title=(comments=='0' and _("View most reviewed records") or
                           _("View most commented records")),
                    body=perform_request_hot(req, ln=ln, comments=comments, top=top, collection=collection),
                    uid=user_info['uid'],
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
Exemplo n.º 11
0
    def tmpl_account_list_alerts(self, ln, alerts):
        """
        Displays all the alerts in the main "Your account" page

        Parameters:

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

          - 'alerts' *array* - The existing alerts IDs ('id' + 'name' pairs)
        """

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

        out = """<form name="displayalert" action="../youralerts/list" method="post">
                 %(you_own)s:
                <select name="id_alert">
                  <option value="0">- %(alert_name)s -</option>""" % {
                 'you_own' : _("You own the following alerts:"),
                 'alert_name' : _("alert name"),
               }
        for alert in alerts :
            out += """<option value="%(id)s">%(name)s</option>""" % \
                   {'id': alert['id'], 'name': cgi.escape(alert['name'])}
        out += """</select>
                &nbsp;<input class="formbutton" type="submit" name="action" value="%(show)s" />
                </form>""" % {
                  'show' : _("SHOW"),
                }
        return out
Exemplo n.º 12
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
Exemplo n.º 13
0
    def daemon(self, req, form):
        """ Display content of folders where the daemon will look into """
        argd = wash_urlargd(form, {})
        _ = gettext_set_language(argd['ln'])

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized
        docs = get_daemon_doc_files()
        metadata = get_daemon_meta_files()

        uid = getUid(req)
        body = batchuploader_templates.tmpl_display_menu(argd['ln'],
                                                         ref="daemon")
        body += batchuploader_templates.tmpl_daemon_content(argd['ln'], docs,
                                                            metadata)
        title = _("Batch Uploader: Daemon monitor")
        return page(title = title,
                    body = body,
                    metaheaderadd = batchuploader_templates.tmpl_styles(),
                    uid = uid,
                    lastupdated = __lastupdated__,
                    req = req,
                    language = argd['ln'],
                    navmenuid = "batchuploader")
Exemplo n.º 14
0
    def tmpl_confirm_delete(self, ln=CFG_SITE_LANG):
        """
        display a confirm message
        @param ln: language
        @return: html output
        """
        _ = gettext_set_language(ln)
        out = """
<table class="confirmoperation">
  <tr>
    <td colspan="2" class="confirmmessage">
      %(message)s
    </td>
  </tr>
  <tr>
    <td>
      <form name="validate" action="delete_all" method="post">
        <input type="hidden" name="confirmed" value="1" />
        <input type="hidden" name="ln" value="%(ln)s" />
        <input type="submit" value="%(yes_label)s" class="formbutton" />
      </form>
    </td>
    <td>
      <form name="cancel" action="display" method="post">
        <input type="hidden" name="ln" value="%(ln)s" />
        <input type="submit" value="%(no_label)s" class="formbutton" />
      </form>
    </td>
  </tr>
</table>"""% {'message': _("Are you sure you want to empty your whole mailbox?"),
              'ln':ln,
              'yes_label': _("Yes"),
              'no_label': _("No")}
        return out
Exemplo n.º 15
0
def edit(req, ln=CFG_SITE_LANG, fname=""):
    """ creates an editor for the file. This is called also when the user wants to
        create a new file. In the case fname is empty"""
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    # sanity check for fname:
    fname = os.path.basename(fname)

    #check auth
    (admin_ok, uid) = is_admin(req)
    navtrail = """<a class="navtrail" href="%s/help/admin">%s</a>""" % \
               (CFG_SITE_SECURE_URL, _("Admin Area"))
    navtrail += """&gt; <a class="navtrail" href="%s/admin/bibcheck/bibcheckadmin.py/">BibCheck Admin</a> """ % CFG_SITE_SECURE_URL
    myout = _("File")+" " + cgi.escape(fname) + "<br/>"
    if admin_ok:
        #add a javascript checker so that the user cannot save a form with empty
        #fname
        myout += """<script language="JavaScript" type="text/javascript">
                    <!--
                     function checkform ( form ) { if (form.fname.value == "") {
                              alert( "Missing filename." ); form.fname.focus(); return false ;
                            }
                            return true ;
                      }
                     -->
                     </script>"""


        #read the file if there is one
        filelines = []
        if fname:
            myfile = CFG_ETCDIR+"/bibcheck/"+fname
            infile = file(myfile, 'r')
            filelines = infile.readlines()
            infile.close()
        myout += '<form method="post" action="save" onsubmit="return checkform(this);">'
        #create a filename dialog box if there is no fname, otherwise it's hidden
        if fname:
            myout += '<input type="hidden" name="fname" value="'+fname+'">'
        else:
            myout += '<input name="fname" value="'+fname+'"><br/>'
            myout += '<input type="hidden" name="wasnew" value="1">'
        myout += '<input type="hidden" name="ln" value="'+ln+'">'
        myout += '<textarea name="code" id="code" rows="25" style="width:100%">'
        for line in filelines:
            myout += line
        #create a save button
        myout += '</textarea><br/><input type="submit" name="save" value="'+_("Save Changes")+'"></form>'
        #create page
        return page(title=_("Edit BibCheck config file"),
                body= myout,
                language= ln,
                uid=uid,
                navtrail = navtrail,
                lastupdated=__lastupdated__,
                req=req,
                warnings=[])
    else: #not admin
        return page_not_authorized(req=req, text=_("Not authorized"), navtrail=navtrail)
Exemplo n.º 16
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
Exemplo n.º 17
0
    def display_job_result(self, req, form):
        """Displays the results of a job"""
        argd = wash_urlargd(form, {
                           "result_id": (int, JobResult.ID_MISSING),
                           "output_format" : (int, Job.OUTPUT_FORMAT_MISSING)
                           })
        # load the right message language
        language = argd["ln"]
        _ = gettext_set_language(language)

        self._check_user_credentials(req, language)

        user_id = self._get_user_id(req)
        job_result_id = argd["result_id"]
        output_format = argd["output_format"]

        title = _("Export Job Result")
        try:
            body = perform_request_display_job_result(job_result_id = job_result_id,
                                                      output_format = output_format,
                                                      user_id = user_id,
                                                      language = language)
        except AccessDeniedError:
            self._redirect_to_not_authorised_page(req, language)

        return page(title = title,
                    metaheaderadd = get_css(),
                    body = body,
                    req = req,
                    navmenuid   = "fieldexporter",
                    titleprologue = get_navigation_menu(language),
                    navtrail = self._NAVTRAIL_EXPORT,
                    language = language)
Exemplo n.º 18
0
    def index(self, req, form):
        """ The function called by default"""

        argd = wash_urlargd(form, {
                                   self._JSON_DATA_KEY: (str, ""),
                                   })

        # load the right message language
        language = argd["ln"]
        _ = gettext_set_language(language)

        # check user credentials
        (auth_code, auth_msg) = acc_authorize_action(req, "runbibeditmulti")
        if 0 != auth_code:
            return page_not_authorized(req = req,
                                       ln = language,
                                       text = auth_msg)

        if argd[self._JSON_DATA_KEY]:
            return self._process_json_request(form, req)

        body = multi_edit_engine.perform_request_index(language)
        title = _("Multi-Record Editor")
        metaheaderadd = multi_edit_engine.get_scripts()
        metaheaderadd = metaheaderadd + multi_edit_engine.get_css()

        return page(title = title,
            metaheaderadd = metaheaderadd,
            body = body,
            req = req,
            language = language)
Exemplo n.º 19
0
 def tmpl_admin_alert_was_already_sent(self, ln, journal_name,
                                       subject, plain_text, recipients,
                                       html_mail, issue):
     """
     """
     _ = gettext_set_language(ln)
     out = '''
     <form action="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/alert" name="alert" method="post">
         <input type="hidden" name="journal_name" value="%(journal_name)s"/>
         <input type="hidden" name="recipients" value="%(recipients)s" />
         <input type="hidden" name="subject" value="%(subject)s" />
         <input type="hidden" name="plainText" value="%(plain_text)s" />
         <input type="hidden" name="htmlMail" value="%(html_mail)s" />
         <input type="hidden" name="force" value="True" />
         <p><em>WARNING! </em>The email alert for the issue %(issue)s has already been
         sent. Are you absolutely sure you want to send it again?</p>
         <p>Maybe you forgot to release an update issue? If so, please do this
         first <a href="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/issue_control?journal_name=%(journal_name)s&amp;issue=%(issue)s">here</a>.</p>
         <p>Proceed with caution, or your subscribers will receive the alert a second time.</p>
         <br/>
         <input class="formbutton" type="submit" value="I really want this!" name="sent"/>
     </form>
             ''' % {'CFG_SITE_URL': CFG_SITE_URL,
                    'journal_name': journal_name,
                    'recipients': recipients,
                    'subject': subject,
                    'plain_text': plain_text,
                    'html_mail': html_mail,
                    'issue': issue}
     return out
Exemplo n.º 20
0
 def tmpl_display_menu(self, ln=CFG_SITE_LANG, ref=""):
     """ Displays menu with all upload options """
     _ = gettext_set_language(ln)
     body_content = """
     <table>
         <td>0.&nbsp;<small>%(upload_open_link)s%(text1)s%(upload_close_link)s</small></td>
         <td>1.&nbsp;<small>%(docupload_open_link)s%(text2)s%(docupload_close_link)s</small></td>
         <td>2.&nbsp;<small>%(history_open_link)s%(text3)s%(history_close_link)s</small></td>
         <td>3.&nbsp;<small>%(daemon_open_link)s%(text4)s%(daemon_close_link)s</small></td>
         </tr>
     </table>
     """ % { 'upload_open_link': not ref == "metadata" and "<a href=\"%s/batchuploader/metadata?ln=%s\">" % (CFG_SITE_URL, ln) or "",
             'upload_close_link': not ref == "metadata" and "</a>" or "",
             'text1': _("Metadata batch upload"),
             'docupload_open_link': not ref == "documents" and "<a href=\"%s/batchuploader/documents?ln=%s\">" % (CFG_SITE_URL, ln) or "",
             'docupload_close_link': not ref == "documents" and "</a>" or "",
             'text2': _("Document batch upload"),
             'history_open_link': not ref == "history" and "<a href=\"%s/batchuploader/history?ln=%s\">" % (CFG_SITE_URL, ln) or "",
             'history_close_link': not ref == "history" and "</a>" or "",
             'text3': _("Upload history"),
             'daemon_open_link': not ref == "daemon" and "<a href=\"%s/batchuploader/daemon?ln=%s\">" % (CFG_SITE_URL, ln) or "",
             'daemon_close_link': not ref == "daemon" and "</a>" or "",
             'text4': _("Daemon monitor")
            }
     return addadminbox("<b>Menu</b>", [body_content])
Exemplo n.º 21
0
def do_external_search(req, lang, vprint, basic_search_units, search_engines, print_search_info=True, print_body=True):
    """Make the external search."""
    _ = gettext_set_language(lang)
    vprint(3, 'beginning external search')
    engines_list = []

    for engine in search_engines:
        url = engine.build_search_url(basic_search_units, req.args, lang)
        user_url = engine.build_user_search_url(basic_search_units, req.args, lang)
        if url:
            engines_list.append([url, engine, user_url])

    pagegetters_list = [HTTPAsyncPageGetter(engine[0]) for engine in engines_list]

    def finished(pagegetter, data, current_time, print_search_info=True, print_body=True):
        """Function called, each time the download of a web page finish.
        Will parse and print the results of this page."""
        print_results(req, lang, pagegetter, data, current_time, print_search_info, print_body)

    finished_list = async_download(pagegetters_list, finished, engines_list, CFG_EXTERNAL_COLLECTION_TIMEOUT, print_search_info, print_body)

    for (finished, engine) in zip(finished_list, engines_list):
        if not finished:
            url = engine[2] or engine[0]
            name = engine[1].name
            print_timeout(req, lang, engine[1], name, url)
Exemplo n.º 22
0
 def tmpl_webjournal_error_box(self, req, ln, title, title_msg, msg):
     """
     returns an error box for webjournal errors.
     """
     _ = gettext_set_language(ln)
     title = _(title)
     title_msg = _(title_msg)
     msg = _(msg)
     mail_msg = _("Contact %(x_url_open)sthe administrator%(x_url_close)s") % \
                {'x_url_open' :
                 '<a href="mailto:%s">' % CFG_SITE_SUPPORT_EMAIL,
                 'x_url_close' : '</a>'}
     box = '''
     <div style="text-align: center;">
         <fieldset style="width:400px; margin-left: auto; margin-right: auto;">
             <legend style="color:#a70509;background-color:#fff;">
                 <i>%s</i>
             </legend>
             <p style="text-align:center;">%s</p>
             <br/>
             <div style="text-align:right;">
                 %s
             </div>
         </fieldset>
     </div>
             ''' % (title_msg, msg, mail_msg)
     return page(req=req, title=title, body=box)
Exemplo n.º 23
0
def format_element(bfo):
    ln = bfo.lang
    _ = gettext_set_language(ln)

    CFG_OPENAIRE_THESIS_TYPES = current_app.config['CFG_OPENAIRE_THESIS_TYPES']

    info = bfo.field('502__')

    if not info:
        return ""

    ret = ""
    if 'b' in info and 'c' in info:
        ret = "%(type)s, %(university)s"
    elif 'b' in info:
        ret = "%(type)s"
    elif 'c' in info:
        ret = "%(university)s"

    try:
        type_title = _(dict(CFG_OPENAIRE_THESIS_TYPES[info['b']]))
    except KeyError:
        type_title = ''

    ctx = {
        'university' : info['c'],
        'type': type_title,
    }

    return ret % ctx
Exemplo n.º 24
0
    def sub(self, req, form):
        """DEPRECATED: /submit/sub is deprecated now, so raise email to the admin (but allow submission to continue anyway)"""
        args = wash_urlargd(form, {'password': (str, '')})
        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "../sub/",
                                       navmenuid='submit')
        try:
            raise DeprecationWarning, 'submit/sub handler has been used. Please use submit/direct. e.g. "submit/sub?RN=123@SBIFOO" -> "submit/direct?RN=123&sub=SBIFOO"'
        except DeprecationWarning:
            register_exception(req=req, alert_admin=True)

        ln = args['ln']
        _ = gettext_set_language(ln)
        #DEMOBOO_RN=DEMO-BOOK-2008-001&ln=en&password=1223993532.26572%40APPDEMOBOO
        params = dict(form)
        password = args['password']
        if password:
            del params['password']
            if "@" in password:
                params['access'], params['sub'] = password.split('@', 1)
            else:
                params['sub'] = password
        else:
            args = str(req.args).split('@')
            if len(args) > 1:
                params = {'sub' : args[-1]}
                args = '@'.join(args[:-1])
                params.update(cgi.parse_qs(args))
            else:
                return warning_page(_("Sorry, invalid URL..."), req, ln=ln)
        url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL, urlencode(params, doseq=True))
        redirect_to_url(req, url)
Exemplo n.º 25
0
    def download_job_result(self, req, form):
        """Returns to the browser zip file containing the job result"""
        argd = wash_urlargd(form, {
                           "result_id" : (int, JobResult.ID_MISSING),
                           "output_format" : (int, Job.OUTPUT_FORMAT_MISSING)
                           })
        # load the right message language
        language = argd["ln"]
        job_result_id = argd["result_id"]
        output_format = argd["output_format"]
        user_id = self._get_user_id(req)

        _ = gettext_set_language(language)

        self._check_user_credentials(req, language)

        title = _("Export Job Result")
        try:
            perform_request_download_job_result(req = req,
                                                job_result_id = job_result_id,
                                                output_format = output_format,
                                                user_id = user_id,
                                                language = language)
        except AccessDeniedError:
            self._redirect_to_not_authorised_page(req, language)
Exemplo n.º 26
0
    def tmpl_navigation_menu(self, language = CFG_SITE_LANG):
        """Returns HTML representing navigation menu for field exporter."""

        _ = gettext_set_language(language)

        navigation_menu = """
           <table class="headermodulebox">
             <tbody><tr>
               <td class="headermoduleboxbody">
                     <a class="header" href="%(job_verview_url)s?ln=%(language)s">%(label_job_overview)s</a>
               </td>
               <td class="headermoduleboxbody">
                     <a class="header" href="%(edit_job_url)s?ln=%(language)s">%(label_new_job)s</a>
               </td>

               <td class="headermoduleboxbody">
                     <a class="header" href="%(job_history_url)s?ln=%(language)s">%(label_job_history)s</a>
               </td>
           </tr></tbody></table>
        """ %   {"edit_job_url" : self._EDIT_JOB_URL,
                "job_verview_url" : self._JOBS_URL,
                "job_history_url" : self._JOB_HISTORY_URL,
                "language" : language,
                "label_job_overview" : _("Export Job Overview"),
                "label_new_job" : _("New Export Job"),
                "label_job_history" : _("Export Job History")
                }
        return navigation_menu
Exemplo n.º 27
0
    def metadata(self, req, form):
        """ Display Metadata file upload form """
        argd = wash_urlargd(form, { 'filetype': (str, ""),
                                    'mode': (str, ""),
                                    'submit_date': (str, "yyyy-mm-dd"),
                                    'submit_time': (str, "hh:mm:ss"),
                                    'email_logs_to': (str, None)})
        _ = gettext_set_language(argd['ln'])

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized
        uid = getUid(req)
        if argd['email_logs_to'] is None:
            argd['email_logs_to'] = get_email(uid)
        body = batchuploader_templates.tmpl_display_menu(argd['ln'], ref="metadata")
        body += batchuploader_templates.tmpl_display_web_metaupload_form(argd['ln'],
                argd['filetype'], argd['mode'], argd['submit_date'],
                argd['submit_time'], argd['email_logs_to'])

        title = _("Metadata batch upload")
        return page(title = title,
                    body = body,
                    metaheaderadd = batchuploader_templates.tmpl_styles(),
                    uid = uid,
                    lastupdated = __lastupdated__,
                    req = req,
                    language = argd['ln'],
                    navmenuid = "batchuploader")
Exemplo n.º 28
0
    def history(self, req, form):
        """Display upload history of the current user"""
        argd = wash_urlargd(form, {})
        _ = gettext_set_language(argd['ln'])

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized
        uploaded_meta_files = get_user_metadata_uploads(req)
        uploaded_doc_files = get_user_document_uploads(req)

        uid = getUid(req)
        body = batchuploader_templates.tmpl_display_menu(argd['ln'],
                                                         ref="history")
        body += batchuploader_templates.tmpl_upload_history(argd['ln'],
                                                            uploaded_meta_files,
                                                            uploaded_doc_files)
        title = _("Upload history")
        return page(title = title,
                    body = body,
                    metaheaderadd = batchuploader_templates.tmpl_styles(),
                    uid = uid,
                    lastupdated = __lastupdated__,
                    req = req,
                    language = argd['ln'],
                    navmenuid = "batchuploader")
Exemplo n.º 29
0
def kb_add(req, ln=CFG_SITE_LANG, sortby="to", kbtype=""):
    """
    Adds a new kb
    @param req the request
    @param ln language
    @param sortby to or from
    @param kbtype type of knowledge base. one of: "", taxonomy, dynamic
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

    try:
        dummy = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        name = "Untitled"
        if kbtype == "taxonomy":
            name = "Untitled Taxonomy"
        if kbtype == "dynamic":
            name = "Untitled dynamic"
        kb_id = bibknowledge.add_kb(kb_name=name, kb_type=kbtype)
        redirect_to_url(req, "kb?ln=%(ln)s&amp;action=attributes&amp;kb=%(kb)s" % {'ln':ln, 'kb':kb_id, 'sortby':sortby})
    else:
        navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Exemplo n.º 30
0
def create_sciencewise_icon(reportnumber, lang=CFG_SITE_LANG, cds=False):
    """
    If the reportnumber is a valid arXiv reportnumber return a ScienceWise.info
    icon.
    """
    _ = gettext_set_language(lang)
    if cds:
        return """\
    <a href="http://sciencewise.info/bookmarks/cds:%(id)s/add" target="_blank" title="%(title)s"><img src="%(siteurl)s/img/sciencewise.png" width="23" height="16" alt="ScienceWise.info icon" /></a>""" % {
                'id': cgi.escape(reportnumber, True),
                'title': cgi.escape(_("Add this document to your ScienceWise.info bookmarks"), True),
                'siteurl': cgi.escape(CFG_BASE_URL, True)
            }
    reportnumber = reportnumber.lower()
    g = _RE_BAD_OLD_ARXIV.match(reportnumber)
    if g:
        reportnumber = '%s/%s' % (g.group('archive'), g.group('number'))
    for regexp in (_RE_MODERN_ARXIV, _RE_OLD_ARXIV):
        g = regexp.match(reportnumber)
        if g:
            return """\
    <a href="http://sciencewise.info/bookmarks/%(id)s/add" target="_blank" title="%(title)s"><img src="%(siteurl)s/img/sciencewise.png" width="23" height="16" alt="ScienceWise.info icon" /></a>""" % {
                'id': cgi.escape(g.group('number'), True),
                'title': cgi.escape(_("Add this article to your ScienceWise.info bookmarks"), True),
                'siteurl': cgi.escape(CFG_BASE_URL, True)
            }
    return ""
Exemplo n.º 31
0
def send_new_admin_account_warning(new_account_email,
                                   send_to,
                                   ln=CFG_SITE_LANG):
    """Send an email to the address given by send_to about the new account new_account_email."""
    _ = gettext_set_language(ln)
    sub = _("New account on") + " '%s'" % CFG_SITE_NAME
    if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
        sub += " - " + _("PLEASE ACTIVATE")
    body = _("A new account has been created on") + " '%s'" % CFG_SITE_NAME
    if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
        body += _(" and is awaiting activation")
    body += ":\n\n"
    body += _("   Username/Email") + ": %s\n\n" % new_account_email
    body += _(
        "You can approve or reject this account request at"
    ) + ": %s/admin/webaccess/webaccessadmin.py/manageaccounts\n" % CFG_SITE_URL
    return send_email(CFG_SITE_SUPPORT_EMAIL,
                      send_to,
                      subject=sub,
                      content=body)
Exemplo n.º 32
0
def get_user_info(uid, ln=CFG_SITE_LANG):
    """Get infos for a given user.
    @param uid: user id (int)
    @return: tuple: (uid, nickname, display_name)
    """
    _ = gettext_set_language(ln)
    query = """SELECT id, nickname
               FROM user
               WHERE id=%s"""
    res = run_sql(query, (uid, ))
    if res:
        if res[0]:
            user = list(res[0])
            if user[1]:
                user.append(user[1])
            else:
                user[1] = str(user[0])
                user.append(_("user") + ' #' + str(user[0]))
            return tuple(user)
    return (uid, '', _("N/A"))
Exemplo n.º 33
0
def get_users_by_status(grpID, status, ln=CFG_SITE_LANG):
    """Get the list of users with the given status.
    @return: ((id, nickname),) nickname= user # uid if
    the user has no nickname
    """
    _ = gettext_set_language(ln)
    res = run_sql("""SELECT ug.id_user, u.nickname
                       FROM user_usergroup ug, user u
                      WHERE ug.id_usergroup = %s
                        AND ug.id_user=u.id
                        AND user_status = %s""",
                  (grpID, status))
    users = []
    if res:
        for (mid, nickname) in res:
            nn = nickname
            if not nickname:
                nn = _("user") + "#%i" % mid
            users.append((mid, nn))
    return tuple(users)
Exemplo n.º 34
0
def kb_add(req, ln=CFG_SITE_LANG, sortby="to", kbtype=""):
    """
    Adds a new kb
    @param req the request
    @param ln language
    @param sortby to or from
    @param kbtype type of knowledge base. one of: "", taxonomy, dynamic
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (
        CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

    try:
        dummy = getUid(req)
    except:
        return error_page('Error', req)

    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        name = "Untitled"
        if kbtype == "taxonomy":
            name = "Untitled Taxonomy"
        if kbtype == "dynamic":
            name = "Untitled dynamic"
        kb_id = bibknowledge.add_kb(kb_name=name.decode('utf-8'),
                                    kb_type=kbtype)
        redirect_to_url(
            req, "kb?ln=%(ln)s&amp;action=attributes&amp;kb=%(kb)s" % {
                'ln': ln,
                'kb': kb_id,
                'sortby': sortby
            })
    else:
        navtrail_previous_links = ''' &gt; <a class="navtrail" href="%s/kb?ln=%s">%s</a>''' % (
            CFG_SITE_SECURE_URL, ln, _("Manage Knowledge Bases"))

        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
Exemplo n.º 35
0
    def get_collectionbox_name(self, ln=None, box_type="r"):
        """Return collection-specific labelling subtrees.

        - 'Focus on': regular collection
        - 'Narrow by': virtual collection
        - 'Latest addition': boxes

        If translation for given language does not exist, use label
        for CFG_SITE_LANG. If no custom label is defined for
        CFG_SITE_LANG, return default label for the box.

        :param ln: the language of the label
        :param box_type: can be 'r' (=Narrow by), 'v' (=Focus on),
                         'l' (=Latest additions)
        """
        if ln is None:
            ln = g.ln
        collectionboxnamequery = db.object_session(self).query(
            Collectionboxname).with_parent(self)
        try:
            collectionboxname = collectionboxnamequery.filter(
                db.and_(
                    Collectionboxname.ln == ln,
                    Collectionboxname.type == box_type,
                )).one()
        except Exception:
            try:
                collectionboxname = collectionboxnamequery.filter(
                    db.and_(
                        Collectionboxname.ln == ln,
                        Collectionboxname.type == box_type,
                    )).one()
            except Exception:
                collectionboxname = None

        if collectionboxname is None:
            # load the right message language
            _ = gettext_set_language(ln)
            return _(Collectionboxname.TYPES.get(box_type, ''))
        else:
            return collectionboxname.value
Exemplo n.º 36
0
 def tmpl_warning(self, warnings, ln=CFG_SITE_LANG):
     """
     Display len(warnings) warning fields
     @param infos: list of strings
     @param ln=language
     @return: html output
     """
     _ = gettext_set_language(ln)
     if not((type(warnings) is list) or (type(warnings) is tuple)):
         warnings = [warnings]
     warningbox = ""
     if warnings != []:
         warningbox = "<div class=\"warningbox\">\n  <b>Warning:</b>\n"
         for warning in warnings:
             lines = warning.split("\n")
             warningbox += "  <p>"
             for line in lines[0:-1]:
                 warningbox += line + "    <br />\n"
             warningbox += lines[-1] + "  </p>"
         warningbox += "</div><br />\n"
     return warningbox
Exemplo n.º 37
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
Exemplo n.º 38
0
def create_day_selectbox(name, selected_day=0, ln=None):
    """Creates an HTML menu for day selection. (0..31 values).

    @param name: name of the control (i.e. name of the var you'll get)
    @param selected_day: preselect a day. Use 0 for the label 'Day'
    @param ln: language of the menu
    @return: html a string
    """
    ln = default_ln(ln)
    _ = gettext_set_language(ln)
    out = "<select name=\"%s\">\n" % name
    for i in range(0, 32):
        out += "  <option value=\"%i\"" % i
        if (i == selected_day):
            out += " selected=\"selected\""
        if (i == 0):
            out += ">%s</option>\n" % _("Day")
        else:
            out += ">%i</option>\n" % i
    out += "</select>\n"
    return out
Exemplo n.º 39
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
Exemplo n.º 40
0
    def tmpl_errorMsg(self, ln, error_msg, rest=""):
        """
        Adds an error message to the output

        Parameters:

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

          - 'error_msg' *string* - The error message

          - 'rest' *string* - The rest of the page
        """

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

        out = """<div class="quicknote">%(error)s</div><br />%(rest)s""" % {
            'error': error_msg,
            'rest': rest
        }
        return out
Exemplo n.º 41
0
 def tmpl_admin_control_issue_success_msg(self, ln, active_issues,
                                          journal_name):
     """
     An issue was successfully published
     """
     _ = gettext_set_language(ln)
     issue_string = "".join([" - %s" % issue for issue in active_issues])
     title = '<h2>Issue(s) %s created successfully!</h2>' % issue_string
     body = '''<p>Now you can:</p>
              <p>Return to your journal here: &raquo;
              <a href="%s/journal/%s"> %s </a>
              </p>
              <p>Make additional publications here: &raquo;
              <a href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">Publishing Interface</a>
             </p>
             <p>Send an alert email here: &raquo;
             <a href="%s/admin/webjournal/webjournaladmin.py/alert?journal_name=%s"> Send an alert</a>
             </p>''' % (CFG_SITE_URL, journal_name, journal_name,
                        CFG_SITE_URL, journal_name, CFG_SITE_URL,
                        journal_name)
     return title + body
Exemplo n.º 42
0
def kb_manage(req, ln=CFG_SITE_LANG, search="", descriptiontoo=""):
    """
    Main BibKnowledge administration page.

    @param ln language
    @param search search for a substring in kb names
    @param descriptiontoo .. and descriptions
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    warnings = []
    # Check if user is authorized to administer
    # If not, still display page but offer to log in
    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)
    (auth_code, auth_msg) = check_user(req, 'cfgbibknowledge')
    if not auth_code:
        is_admin = True
    else:
        is_admin = False

    navtrail = '''<a class="navtrail" href="%s/help/admin">%s</a>''' % \
               (CFG_SITE_SECURE_URL, _("Admin Area"))
    if is_admin:
        return page(title=_("BibKnowledge Admin"),
                    body=bibknowledgeadminlib.
                    perform_request_knowledge_bases_management(
                        ln=ln, search=search, descriptiontoo=descriptiontoo),
                    language=ln,
                    uid=uid,
                    navtrail=navtrail,
                    lastupdated=__lastupdated__,
                    req=req,
                    warnings=warnings)
    else:
        #redirect to login
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail)
Exemplo n.º 43
0
def _notify_success_user(email_user, original_filename, recid, submission_title, ln=invenio.config.CFG_SITE_LANG):
    """Sends an success notification to the specified address of the user.
       Is called by process_batch_job() if the processing was successful.
    @param email_user: email address of the user
    @type email_user: string
    @param email_admin: email address of the admin
    @type email_admin: string
    """
    uid = emailUnique(email_user)
    if uid != -1 and uid != 0:
        language = getval(get_user_preferences(uid), "language")
        if language:
            ln = language
    _ = gettext_set_language(ln)
    rec_url = invenio.config.CFG_SITE_URL + "/record/" + str(recid)
    template = ("<br/>" +
            _("Your video submission%(submission_title)s was successfully processed.") +
            "<br/><br/>" +
            _("The file you uploaded was %(input_filename)s.") +
            "<br/><br/>" +
            _("Your video is now available here: %(record_url)s.") +
            "<br/>" +
            _("If the videos quality is not as expected, you might want to take "
            "a look at %(guidelines_url)s"
            " and modify or redo your submission."))
    text = template % {"input_filename": "%s" % original_filename,
             "submission_title": " %s" % submission_title,
             "record_url": "%s" % rec_url,
             "guidelines_url": "localhost"}
    text = text.replace("<br/>", "\n")
    html_text = template % {"input_filename": "<strong>%s</strong>" % original_filename,
             "submission_title": " <strong>%s</strong>" % submission_title,
             "record_url": "<a href=\"%s\">%s</a>" % (rec_url, rec_url),
             "guidelines_url": "<a href=\"locahost\">%s</a>" % _("the video guidelines")}
    send_email(fromaddr=invenio.config.CFG_SITE_ADMIN_EMAIL,
               toaddr=email_user,
               subject="Your video submission is now complete",
               content=text,
               html_content=html_text
               )
Exemplo n.º 44
0
def delete(req, ln, fname):
    """delete file fname"""
    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    # sanity check for fname:
    fname = os.path.basename(fname)

    #check auth
    (admin_ok, uid) = is_admin(req)
    navtrail = """<a class="navtrail" href="%s/help/admin">%s</a>""" % \
               (CFG_SITE_SECURE_URL, _("Admin Area"))
    navtrail += """&gt; <a class="navtrail" href="%s/admin/bibcheck/bibcheckadmin.py/">BibCheck Admin</a> """ % CFG_SITE_SECURE_URL
    if admin_ok:
        msg = ""
        myfile = CFG_ETCDIR + "/bibcheck/" + fname
        success = 1
        try:
            os.remove(myfile)
        except:
            success = 0
        if success:
            msg = _("File %(x_name)s deleted.", x_name=cgi.escape(fname))
        else:
            msg = _("File %(x_name)s: delete failed.",
                    x_name=cgi.escape(fname))
        #print message
        return page(title=_("Delete BibCheck config file"),
                    body=msg,
                    language=ln,
                    uid=uid,
                    navtrail=navtrail,
                    lastupdated=__lastupdated__,
                    req=req,
                    warnings=[])
    else:
        return page_not_authorized(req=req,
                                   text=_("Not authorized"),
                                   navtrail=navtrail)
Exemplo n.º 45
0
    def history(self, req, form):
        """Displays history of the jobs"""
        argd = wash_urlargd(form, {})

        # load the right message language
        language = argd["ln"]
        _ = gettext_set_language(language)

        self._check_user_credentials(req, language)

        title = _("Export Job History")
        user_id = self._get_user_id(req)
        body = perform_request_job_history(user_id, language)

        return page(title=title,
                    metaheaderadd=get_css(),
                    body=body,
                    req=req,
                    navmenuid="fieldexporter",
                    titleprologue=get_navigation_menu(language),
                    navtrail=self._NAVTRAIL_EXPORT,
                    language=language)
Exemplo n.º 46
0
    def _get_frequency_text(self, frequency, language=CFG_SITE_LANG):
        """
        Returns text representation of the frequency: Manually, Daily, Weekly, Monthly

        @param frequency: integer containg the number of hours between every execution.

        @param language: language for output
        """
        _ = gettext_set_language(language)

        if 0 == frequency:
            frequency_text = _("Manually")
        elif 24 == frequency:
            frequency_text = _("Daily")
        elif 168 == frequency:
            frequency_text = _("Weekly")
        elif 720 == frequency:
            frequency_text = _("Monthly")
        else:
            frequency_text = "Every %s hours" % (frequency, )

        return frequency_text
Exemplo n.º 47
0
 def tmpl_admin_show_taxonomy(self, ln, kb_id, kb_name):
     """
     An auxiliary method used by tmpl_admin_kb_show in order to make a form to upload an ref file.
     @param ln: language
     @param kb_id: knowledge base id
     @param kb_name: knowledge base name
     @param basefilename: the file name (if already exists)
     """
     _ = gettext_set_language(ln)  # load the right message language
     #check if this kb already has a file associated with it
     #it would be named CFG_WEBDIR+"/kbfiles/"+kb_id+".rdf"
     rdfname = CFG_WEBDIR + "/kbfiles/" + str(kb_id) + ".rdf"
     webname = CFG_SITE_URL + "/kb/export?kbname=" + cgi.escape(kb_name, 1)
     out = ""
     if os.path.isfile(rdfname):
         out += _("This knowledge base already has a taxonomy file.") + " "
         out += _(
             "If you upload another file, the current version will be replaced."
         )
         out += "<br/>"
         out += _(
             "The current taxonomy can be accessed with this URL: %(x_url)s",
             x_url=('<a href="' + webname + '">' + webname + "</a>"))
     else:
         out += _("Please upload the RDF file for taxonomy %(x_name)s",
                  x_name=cgi.escape(kb_name))
     out += """
       <br/>
       <!-- enctype="multipart/form-data"-->
       <form method="post" action="kb/upload" name="upload" enctype="multipart/form-data">
       <input style="display:none;" name="kb", value="%(kb_id)s"/>
       <input type="file" name="file"/>
       <input type="submit" name="submit" value="%(upload)s" class="adminbutton"/>
       </form>
       """ % {
         'kb_id': kb_id,
         'upload': _("Upload")
     }
     return out
Exemplo n.º 48
0
def perform_request_groups_display(uid, infos=[], warnings = [], \
        ln=CFG_SITE_LANG):
    """Display all the groups the user belongs to.
    @param uid:   user id
    @param info: info about last user action
    @param ln: language
    @return: body with warnings
    """
    _ = gettext_set_language(ln)
    body = ""

    body_admin = display_admin_groups(uid, ln)
    body_member = display_member_groups(uid, ln)
    body_external = display_external_groups(uid, ln)

    body = websession_templates.tmpl_display_all_groups(infos=infos,
        admin_group_html=body_admin,
        member_group_html=body_member,
        external_group_html=body_external,
        warnings=warnings,
        ln=ln)
    return body
Exemplo n.º 49
0
def perform_request_remove_member(uid, grpID, member_id, ln=CFG_SITE_LANG):
    """Remove member from a group.
    @param uid: user ID
    @param grpID: ID of the group
    @param member_id: selected member ID
    @param ln: language
    @return: body with warnings
    """
    body = ''
    warnings = []
    infos = []
    _ = gettext_set_language(ln)
    user_status = db.get_user_status(uid, grpID)
    if not len(user_status):
        try:
            raise InvenioWebSessionError(_('Sorry, there was an error with the database.'))
        except InvenioWebSessionError as exc:
            register_exception()
            body = websession_templates.tmpl_error(exc.message, ln)
            return body
    if member_id == -1:
        try:
            raise InvenioWebSessionWarning(_('Please choose a member if you want to remove him from the group.'))
        except InvenioWebSessionWarning as exc:
            register_exception(stream='warning')
            warnings.append(exc.message)
        body = perform_request_manage_member(uid,
                                             grpID,
                                             warnings=warnings,
                                             ln=ln)
    else:
        db.delete_member(grpID, member_id)
        infos.append(CFG_WEBSESSION_INFO_MESSAGES["MEMBER_DELETED"])
        body = perform_request_manage_member(uid,
                                             grpID,
                                             infos=infos,
                                             warnings=warnings,
                                             ln=ln)
    return body
Exemplo n.º 50
0
def bibdocfile_legacy_getfile(req, form):
    """ Handle legacy /getfile.py URLs """

    args = wash_urlargd(form, {
        'recid': (int, 0),
        'docid': (int, 0),
        'version': (str, ''),
        'name': (str, ''),
        'format': (str, ''),
        'ln' : (str, CFG_SITE_LANG)
        })

    _ = gettext_set_language(args['ln'])

    def _getfile_py(req, recid=0, docid=0, version="", name="", docformat="", ln=CFG_SITE_LANG):
        if not recid:
            ## Let's obtain the recid from the docid
            if docid:
                try:
                    bibdoc = BibDoc(docid=docid)
                    recid = bibdoc.bibrec_links[0]["recid"]
                except InvenioBibDocFileError:
                    return warning_page(_("An error has happened in trying to retrieve the requested file."), req, ln)
            else:
                return warning_page(_('Not enough information to retrieve the document'), req, ln)
        else:
            brd = BibRecDocs(recid)
            if not name and docid:
                ## Let's obtain the name from the docid
                try:
                    name = brd.get_docname(docid)
                except InvenioBibDocFileError:
                    return warning_page(_("An error has happened in trying to retrieving the requested file."), req, ln)

        docformat = normalize_format(docformat)

        redirect_to_url(req, '%s/%s/%s/files/%s%s?ln=%s%s' % (CFG_SITE_URL, CFG_SITE_RECORD, recid, name, docformat, ln, version and 'version=%s' % version or ''), apache.HTTP_MOVED_PERMANENTLY)

    return _getfile_py(req, **args)
Exemplo n.º 51
0
    def tmpl_admin_alert_interface(self, ln, journal_name, default_subject,
                                   default_msg, default_recipients, alert_ln):
        """
        Alert email interface.
        """
        _ = gettext_set_language(ln)
        interface = '''
        <table>
        <tr>
        <td valign="top">
        <form action="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py/alert" name="alert" method="post">
            <input type="hidden" name="journal_name" value="%(journal_name)s"/>
            <p>Recipients:</p>
            <input type="text" name="recipients" value="%(default_recipients)s" size="60" />
            <p>Subject:</p>
            <input type="text" name="subject" value="%(subject)s" size="60" />
            <p>Plain Text Message:</p>
            <textarea name="plainText" wrap="soft" rows="25" cols="80">%(plain_text)s</textarea>
            <p> <input type="checkbox" name="htmlMail" id="htmlMail" value="html" checked="checked" />
               <label for="htmlMail">Send journal front-page <small>(<em>HTML newsletter</em>)</small></label>
            </p>
            <br/>
            <input class="formbutton" type="submit" value="Send Alert" name="sent"/>
        </form>
        </td><td valign="top">
        <p>HTML newsletter preview:</p>
        <iframe id="htmlMailPreview" src="%(CFG_SITE_URL)s/journal/%(journal_name)s?ln=%(alert_ln)s" height="600" width="600"></iframe>
        </tr>
        </table>
        ''' % {
            'CFG_SITE_URL': CFG_SITE_URL,
            'journal_name': journal_name,
            'subject': default_subject,
            'plain_text': default_msg,
            'default_recipients': default_recipients,
            'alert_ln': alert_ln
        }

        return interface
Exemplo n.º 52
0
    def tmpl_get_latest_linkbacks_top(self, current_value, ln):
        """
        Top elements to select the count of approved latest added linkbacks to display
        @param current_value: current value option will be selected if it exists
        """
        _ = gettext_set_language(ln)
        result = """<form action='linkbacks' style='form { display: inline; }'><b>%s</b>
                        <select name="rg" size="1">
                 """ % _("View last")

        for i in range(len(CFG_WEBLINKBACK_LATEST_COUNT_VALUES)):
            latest_count_string = str(CFG_WEBLINKBACK_LATEST_COUNT_VALUES[i])
            if CFG_WEBLINKBACK_LATEST_COUNT_VALUES[i] == current_value:
                result += '<option SELECTED>' + latest_count_string + '</option>'
            else:
                result += '<option value=' + latest_count_string + '>' + latest_count_string + '</option>'

        result += """   </select> <b>linkbacks</b>
                        <input type="submit" class="adminbutton" value="%s">
                    </form>
                  """ % _("Refresh")
        return result
Exemplo n.º 53
0
def get_i18n_month_name(month_nb, display='short', ln=None):
    """Get a non-numeric representation of a month, internationalized.

    @param month_nb: number of month, (1 based!)
                     =>1=jan,..,12=dec
    @param ln: language for output
    @return: the string representation of month
    """
    ln = default_ln(ln)
    _ = gettext_set_language(ln)
    if display == 'short':
        months = {0: _("Month"),
                  1: _("Jan"),
                  2: _("Feb"),
                  3: _("Mar"),
                  4: _("Apr"),
                  5: _("May"),
                  6: _("Jun"),
                  7: _("Jul"),
                  8: _("Aug"),
                  9: _("Sep"),
                  10: _("Oct"),
                  11: _("Nov"),
                  12: _("Dec")}
    else:
        months = {0: _("Month"),
                  1: _("January"),
                  2: _("February"),
                  3: _("March"),
                  4: _("April"),
                  5: _("May "),  # trailing space distinguishes short/long form
                  6: _("June"),
                  7: _("July"),
                  8: _("August"),
                  9: _("September"),
                  10: _("October"),
                  11: _("November"),
                  12: _("December")}
    return months[month_nb].strip()
Exemplo n.º 54
0
    def tmpl_admin_index(self, ln):
        """
        Index page of admin interface
        """
        _ = gettext_set_language(ln)

        out = '<ol>'

        pending_linkback_count = len(get_all_linkbacks(status=CFG_WEBLINKBACK_STATUS['PENDING']))
        stat_pending_text = ""
        if pending_linkback_count > 0:
            stat_pending_text = ' <span class="moreinfo"> ('
            if pending_linkback_count == 1:
                stat_pending_text += "%s pending linkback request" % pending_linkback_count
            elif pending_linkback_count > 1:
                stat_pending_text += "%s pending linkback requests"% pending_linkback_count
            stat_pending_text += ')</span>'
        out += '<li><a href="%(siteURL)s/admin/weblinkback/weblinkbackadmin.py/linkbacks?ln=%(ln)s&amp;status=%(status)s">%(label)s</a>%(stat)s</li>' % \
                {'siteURL': CFG_SITE_URL,
                 'ln': ln,
                 'status': CFG_WEBLINKBACK_STATUS['PENDING'],
                 'label': _("Pending Linkbacks"),
                 'stat': stat_pending_text}

        out += '<li><a href="%(siteURL)s/linkbacks?ln=%(ln)s">%(label)s</a></li>' % \
                {'siteURL': CFG_SITE_URL,
                 'ln': ln,
                 'label': _("Recent Linkbacks")}

        out += '<li><a href="%(siteURL)s/admin/weblinkback/weblinkbackadmin.py/lists?ln=%(ln)s&amp;returncode=%(returnCode)s">%(label)s</a></li>' % \
                {'siteURL': CFG_SITE_URL,
                 'ln': ln,
                 'returnCode': CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'],
                 'label': _("Linkback Whitelist/Blacklist Manager")}


        out += '</ol>'
        from invenio.legacy.bibrank.adminlib import addadminbox
        return addadminbox('<b>%s</b>'% _("Menu"), [out])
Exemplo n.º 55
0
    def tmpl_linkback_tuple_admin(self, url_approve_prefix, url_reject_prefix, linkbacks, ln):
        """
        Display linkbacks with admin approve/reject features
        @param linkbacks: collection of linkbacks: [(linkback_id,
                                                     origin_url,
                                                     recid,
                                                     additional_properties,
                                                     type,
                                                     status,
                                                     insert_time)]
        """
        _ = gettext_set_language(ln)
        out = ''

        for current_linkback in linkbacks:
            linkbackid = current_linkback[0]
            url = current_linkback[1]

            out += '<div style="margin-bottom:20px;background:#F9F9F9;border:1px solid #DDD">'
            out += '<div style="background-color:#EEE;padding:2px;font-size:small">&nbsp;%s</div>' % (_('Submitted on') + ' <i>' + convert_datetext_to_dategui(str(current_linkback[6])) + '</i>:')
            out += '<br />'
            out += '<blockquote>'
            out += '''<font class="rankscoreinfo"><a>(%(type)s)&nbsp;</a></font><small>&nbsp;<a href="%(origin_url)s" target="_blank">%(page_title)s</a></small>''' % {
                       'type': current_linkback[4],
                       'origin_url': cgi.escape(url),
                       'page_title': cgi.escape(get_url_title(url))}
            out += '</blockquote>'
            out += '<br />'
            out += '<div style="float:right">'
            out += '<small>'
            out += '''<a style="color:#8B0000;" href="%s&linkbackid=%s">%s</a>''' % (url_approve_prefix, linkbackid, _("Approve"))
            out += '&nbsp;|&nbsp;'
            out += '''<a style="color:#8B0000;" href="%s&linkbackid=%s">%s</a>''' % (url_reject_prefix, linkbackid, _("Reject"))
            out += '</small>'
            out += '</div>'
            out += '</div>'

        return out
Exemplo n.º 56
0
    def _get_select_all_none_html(self,
                                  form_name,
                                  field_name,
                                  language=CFG_SITE_LANG):
        """Returns HTML providing Select All|None links

        @param form_name: the name of the form containing the checkboxes
        @param field_name: the name of the checkbox fields that will be affected
        @param language: language for output
        """
        _ = gettext_set_language(language)

        output_html = """
        %(label_select)s: <a href="javascript:SetAllCheckBoxes('%(form_name)s', '%(field_name)s', true);">%(label_all)s</a>, <a href="javascript:SetAllCheckBoxes('%(form_name)s', '%(field_name)s', false);">%(label_none)s</a>
        """ % {
            "label_select": _("Select"),
            "label_all": _("All"),
            "label_none": _("None"),
            "form_name": form_name,
            "field_name": field_name
        }

        return output_html
Exemplo n.º 57
0
def create_sciencewise_icon(reportnumber, lang=CFG_SITE_LANG, cds=False):
    """
    If the reportnumber is a valid arXiv reportnumber return a ScienceWise.info
    icon.
    """
    _ = gettext_set_language(lang)
    if cds:
        return """\
    <a href="http://sciencewise.info/bookmarks/cds:%(id)s/add" target="_blank" title="%(title)s"><img src="%(siteurl)s/img/sciencewise.png" width="23" height="16" alt="ScienceWise.info icon" /></a>""" % {
            'id':
            cgi.escape(reportnumber, True),
            'title':
            cgi.escape(
                _("Add this document to your ScienceWise.info bookmarks"),
                True),
            'siteurl':
            cgi.escape(CFG_BASE_URL, True)
        }
    reportnumber = reportnumber.lower()
    g = _RE_BAD_OLD_ARXIV.match(reportnumber)
    if g:
        reportnumber = '%s/%s' % (g.group('archive'), g.group('number'))
    for regexp in (_RE_MODERN_ARXIV, _RE_OLD_ARXIV):
        g = regexp.match(reportnumber)
        if g:
            return """\
    <a href="http://sciencewise.info/bookmarks/%(id)s/add" target="_blank" title="%(title)s"><img src="%(siteurl)s/img/sciencewise.png" width="23" height="16" alt="ScienceWise.info icon" /></a>""" % {
                'id':
                cgi.escape(g.group('number'), True),
                'title':
                cgi.escape(
                    _("Add this article to your ScienceWise.info bookmarks"),
                    True),
                'siteurl':
                cgi.escape(CFG_BASE_URL, True)
            }
    return ""
Exemplo n.º 58
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
Exemplo n.º 59
0
    def display(self, req, form):
        """
        Display approved latest added linkbacks of the invenio instance
        """
        argd = wash_urlargd(
            form, {'rg': (int, CFG_WEBLINKBACK_LATEST_COUNT_DEFAULT)})
        # count must be positive
        if argd['rg'] < 0:
            argd['rg'] = -argd['rg']

        _ = gettext_set_language(argd['ln'])

        user_info = collect_user_info(req)

        body = perform_request_display_approved_latest_added_linkbacks_to_accessible_records(
            argd['rg'],
            argd['ln'],
            user_info,
            weblinkback_templates=weblinkback_templates)

        navtrail = 'Recent Linkbacks'

        mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader(
        )

        return pageheaderonly(title=navtrail,
                              navtrail=navtrail,
                              verbose=1,
                              metaheaderadd = mathjaxheader + jqueryheader,
                              req=req,
                              language=argd['ln'],
                              navmenuid='search',
                              navtrail_append_title_p=0) + \
                              websearch_templates.tmpl_search_pagestart(argd['ln']) + \
               body + \
               websearch_templates.tmpl_search_pageend(argd['ln']) + \
               pagefooteronly(language=argd['ln'], req=req)
Exemplo n.º 60
0
    def continue_(self, req, form):
        """
        Continue an interrupted submission.
        """
        args = wash_urlargd(form, {'access': (str, ''), 'doctype': (str, '')})
        ln = args['ln']

        _ = gettext_set_language(ln)

        access = args['access']
        doctype = args['doctype']
        if not access or not doctype:
            return warning_page(_("Sorry, invalid arguments"), req=req, ln=ln)
        user_info = collect_user_info(req)
        email = user_info['email']
        res = run_sql(
            "SELECT action, status FROM sbmSUBMISSIONS WHERE id=%s AND email=%s and doctype=%s",
            (access, email, doctype))
        if res:
            action, status = res[0]
            if status == 'finished':
                return warning_page(_(
                    "Note: the requested submission has already been completed"
                ),
                                    req=req,
                                    ln=ln)
            redirect_to_url(
                req, CFG_SITE_SECURE_URL + '/submit/direct?' +
                urlencode({
                    'sub': action + doctype,
                    'access': access
                }))
        return warning_page(_(
            "Sorry, you don't seem to have initiated a submission with the provided access number"
        ),
                            req=req,
                            ln=ln)