예제 #1
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)
예제 #2
0
    def unsubscribe(self, req, form):
        """
        Unsubscribe current user from current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

        user_info = collect_user_info(req)
        uid = getUid(req)

        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)}
            )
            target = (
                CFG_SITE_SECURE_URL
                + "/youraccount/login"
                + make_canonical_urlargd(
                    {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_SECURE_URL + user_info["uri"]}, {}
                )
            )
            return redirect_to_url(req, target, norobot=True)

        success = unsubscribe_user_from_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_SECURE_URL,
            CFG_SITE_RECORD,
            self.recid,
            str(-success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
예제 #3
0
 def opensearchdescription(self, req, form):
     """OpenSearch description file"""
     req.content_type = "application/opensearchdescription+xml"
     req.send_http_header()
     argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG),
                                'verbose': (int, 0) })
     return websearch_templates.tmpl_opensearch_description(ln=argd['ln'])
예제 #4
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)
예제 #5
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)
예제 #6
0
    def _get_response(req):
        """
        Constructs the response returned from the OpenID provider

        @param req: request
        @type req: invenio.legacy.wsgi.SimulatedModPythonRequest
        """
        from invenio.ext.legacy.handler import wash_urlargd
        from openid.consumer import consumer

        content = {}
        for key in req.form.keys():
            content[key] = (str, '')

        args = wash_urlargd(req.form, content)

        if 'ln' in args:
            del args['ln']

        if 'referer' in args:
            if not args['referer']:
                del args['referer']

        oidconsumer = consumer.Consumer({"id": get_session(req)}, None)
        url = CFG_SITE_SECURE_URL + "/youraccount/login"
        req.g['openid_provider_name'] = args['provider']
        req.g['openid_response'] = oidconsumer.complete(args, url)
예제 #7
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {'referer': (str, None)})

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code,
         auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \
                      (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(success), argd['ln'])
        redirect_to_url(req, display_url)
예제 #8
0
    def compare_revisions(self, req, form):
        """Handle the compare revisions request"""
        argd = wash_urlargd(form, { \
                'ln': (str, CFG_SITE_LANG), \
                'rev1' : (str, ''), \
                'rev2' : (str, ''), \
                'recid': (int, 0)})

        ln = argd['ln']
        uid = current_user.get_id()
        _ = gettext_set_language(ln)

        # Checking if currently logged user has permission to perform this request

        auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
        if auth_code != 0:
            return page_not_authorized(req=req, referer="/edit",
                                       text=auth_message, navtrail=navtrail)
        recid = argd['recid']
        rev1 = argd['rev1']
        rev2 = argd['rev2']
        ln = argd['ln']

        body, errors, warnings = perform_request_compare(ln, recid, rev1, rev2)

        return page(title = _("Comparing two record revisions"),
                    body =  body,
                    errors = errors,
                    warnings = warnings,
                    uid = uid,
                    language = ln,
                    navtrail    = navtrail,
                    lastupdated = __lastupdated__,
                    req         = req,
                    body_css_classes = ['bibedit'])
예제 #9
0
 def new_ticket(self, req, form):
     """handle a edit/new_ticket request"""
     argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG), 'recid': (int, 0)})
     ln = argd['ln']
     _ = gettext_set_language(ln)
     auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
     if auth_code != 0:
         return page_not_authorized(req=req, referer="/edit",
                                    text=auth_message, navtrail=navtrail)
     uid = current_user.get_id()
     if argd['recid']:
         (errmsg, url) = perform_request_newticket(argd['recid'], uid)
         if errmsg:
             return page(title       = _("Failed to create a ticket"),
                         body        = _("Error")+": "+errmsg,
                         errors      = [],
                         warnings    = [],
                         uid         = uid,
                         language    = ln,
                         navtrail    = navtrail,
                         lastupdated = __lastupdated__,
                         req         = req,
                         body_css_classes = ['bibedit'])
         else:
             #redirect..
             redirect_to_url(req, url)
예제 #10
0
 def issue_control(self, req, form):
     """
     page that allows full control over creating, backtracing, adding to,
     removing from issues.
     """
     argd = wash_urlargd(
         form,
         {
             "name": (str, ""),
             "add": (str, ""),
             "action_publish": (str, "cfg"),
             "issue_number": (list, []),
             "ln": (str, ""),
         },
     )
     redirect_to_url(
         req,
         CFG_SITE_SECURE_URL
         + "/admin/webjournal/webjournaladmin.py/issue_control?journal_name="
         + argd["name"]
         + "&ln="
         + argd["ln"]
         + "&issue="
         + argd["issue_number"]
         + "&action="
         + argd["action_publish"],
     )
예제 #11
0
    def subscribe(self, req, form):
        """
        Subscribe current user to receive email notification when new
        comments are added to current discussion.
        """
        argd = wash_urlargd(form, {"referer": (str, None)})

        uid = getUid(req)

        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {"collection": guess_primary_collection_of_a_record(self.recid)}
            )
            target = (
                CFG_SITE_SECURE_URL
                + "/youraccount/login"
                + make_canonical_urlargd(
                    {"action": cookie, "ln": argd["ln"], "referer": CFG_SITE_SECURE_URL + user_info["uri"]}, {}
                )
            )
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", text=auth_msg)

        success = subscribe_user_to_discussion(self.recid, uid)
        display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % (
            CFG_SITE_SECURE_URL,
            CFG_SITE_RECORD,
            self.recid,
            str(success),
            argd["ln"],
        )
        redirect_to_url(req, display_url)
예제 #12
0
def index(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
    """Approval web Interface.
    GET params:

    """
    uid = getUid(req)
    (auth_code, auth_message) = acc_authorize_action(uid, 'submit')
    if auth_code > 0 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
        return page_not_authorized(req,
                                   "../approve.py/index",
                                   navmenuid='yourapprovals',
                                   text=auth_message)

    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    args = wash_urlargd(req.form, {'access': (str, '')})
    if args['access'] == "":
        return warning_page(
            _("approve.py: cannot determine document reference"), req, ln)
    url_params = get_approval_url_parameters(args['access'])
    if not url_params:
        return warning_page(_("approve.py: cannot find document in database"),
                            req, ln)
    url_params['ln'] = ln
    url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL,
                                   urllib.urlencode(url_params))
    redirect_to_url(req, url)
예제 #13
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)
예제 #14
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")
예제 #15
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)
예제 #16
0
    def doilookup(self, req, form):
        """
        Returns the metadata from the crossref website based on the DOI.
        """
        args = wash_urlargd(form, {'doi': (str, '')})
        response = defaultdict(list)
        if args['doi']:
            doi = args['doi']
            try:
                marcxml_template = get_marcxml_for_doi(doi)
            except CrossrefError:
                # Just ignore Crossref errors
                pass
            else:
                record = create_record(marcxml_template)[0]
                if record:
                    # We need to convert this record structure to a simple dictionary
                    for key, value in record.items(
                    ):  # key, value = (773, [([('0', 'PER:64142'), ...], ' ', ' ', '', 47)])
                        for val in value:  # val = ([('0', 'PER:64142'), ...], ' ', ' ', '', 47)
                            ind1 = val[1].replace(" ", "_")
                            ind2 = val[2].replace(" ", "_")
                            for (k, v) in val[0]:  # k, v = ('0', 'PER:5409')
                                response[key + ind1 + ind2 + k].append(v)
            # The output dictionary is something like:
            # {"100__a": ['Smith, J.'],
            #  "700__a": ['Anderson, J.', 'Someoneelse, E.'],
            #  "700__u": ['University1', 'University2']}

        # return dictionary as JSON
        return json.dumps(response)
예제 #17
0
    def explorer(self, req, form):
        """ Handles requests from the jQuery FileTree plugin in order to return
        all filenames under the root dir (indicated in the 'dir' GET parameter)
        """
        argd = wash_urlargd(form, {'dir': (str, '')})

        root_dir = INFO_PREFIX + os.sep + argd['dir']

        file_html_list = ['<ul class="jqueryFileTree" style="display: none;">']
        try:
            file_html_list = [
                '<ul class="jqueryFileTree" style="display: none;">'
            ]
            for f in os.listdir(root_dir):
                ff = os.path.join(root_dir, f)
                if os.path.isdir(ff):
                    file_html_list.append(
                        '<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>'
                        % (argd["dir"] + f, f))
                else:
                    e = os.path.splitext(f)[1][1:]  # get .ext and remove dot
                    file_html_list.append(
                        '<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>'
                        % (e, argd["dir"] + f, f))
            file_html_list.append('</ul>')
        except Exception, e:
            file_html_list.append('Could not load directory: %s' % str(e))
예제 #18
0
    def plugin_builder(the_plugin):
        """
        Enhanced plugin_builder created by L{create_enhanced_plugin_builder}.

        :param plugin: the code of the module as just read from package.
        :return: the plugin in the form of a map.
        """
        plugin_name = the_plugin.__name__
        plugin = {}

        if compulsory_objects:
            for object_name, object_signature in \
                    iteritems(compulsory_objects):
                the_object = getattr(the_plugin, object_name, None)
                if the_object is None:
                    raise AutodiscoveryError(
                        'Plugin "%s" does not '
                        'contain compulsory object "%s"' %
                        (plugin_name, object_name))
                try:
                    check_signature(object_name, the_object, object_signature)
                except AutodiscoveryError as err:
                    raise AutodiscoveryError(
                        'Plugin "%s" contains '
                        'object "%s" with a wrong signature: %s' %
                        (plugin_name, object_name, err))
                plugin[object_name] = the_object

        if optional_objects:
            for object_name, object_signature in iteritems(optional_objects):
                the_object = getattr(the_plugin, object_name, None)
                if the_object is not None:
                    try:
                        check_signature(
                            object_name,
                            the_object,
                            object_signature)
                    except AutodiscoveryError as err:
                        raise AutodiscoveryError(
                            'Plugin "%s" '
                            'contains object "%s" with a wrong signature: %s' %
                            (plugin_name, object_name, err))
                    plugin[object_name] = the_object

        if other_data:
            the_other_data = {}
            for data_name, (dummy, data_default) in iteritems(other_data):
                the_other_data[data_name] = getattr(the_plugin, data_name,
                                                    data_default)

            try:
                the_other_data = wash_urlargd(the_other_data, other_data)
            except Exception as err:
                raise AutodiscoveryError(
                    'Plugin "%s" contains other '
                    'data with problems: %s' %
                    (plugin_name, err))

            plugin.update(the_other_data)
        return plugin
예제 #19
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")
예제 #20
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")
예제 #21
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")
예제 #22
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)
예제 #23
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")
예제 #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)
예제 #25
0
    def getattachedfile(self, req, form):
        """
        Returns a file uploaded to the submission 'drop box' by the
        CKEditor.
        """
        argd = wash_urlargd(form, {
            'file': (str, None),
            'type': (str, None),
            'uid': (int, 0)
        })

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)

        if not argd['file'] is None:
            # Prepare path to file on disk. Normalize the path so that
            # ../ and other dangerous components are removed.
            path = os.path.abspath(CFG_PREFIX + '/var/tmp/attachfile/' + \
                                   '/'  + str(argd['uid']) + \
                                   '/' + argd['type'] + '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith(CFG_PREFIX + '/var/tmp/attachfile/'
                               ) and os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        return (apache.HTTP_NOT_FOUND)
예제 #26
0
    def doilookup(self, req, form):
        """
        Returns the metadata from the crossref website based on the DOI.
        """
        args = wash_urlargd(form, {
            'doi': (str, '')})
        response = defaultdict(list)
        if args['doi']:
            doi = args['doi']
            try:
                marcxml_template = get_marcxml_for_doi(doi)
            except CrossrefError:
                # Just ignore Crossref errors
                pass
            else:
                record = create_record(marcxml_template)[0]
                if record:
                    # We need to convert this record structure to a simple dictionary
                    for key, value in record.items():  # key, value = (773, [([('0', 'PER:64142'), ...], ' ', ' ', '', 47)])
                        for val in value:  # val = ([('0', 'PER:64142'), ...], ' ', ' ', '', 47)
                            ind1 = val[1].replace(" ", "_")
                            ind2 = val[2].replace(" ", "_")
                            for (k, v) in val[0]:  # k, v = ('0', 'PER:5409')
                                response[key+ind1+ind2+k].append(v)
            # The output dictionary is something like:
            # {"100__a": ['Smith, J.'],
            #  "700__a": ['Anderson, J.', 'Someoneelse, E.'],
            #  "700__u": ['University1', 'University2']}

        # return dictionary as JSON
        return json.dumps(response)
예제 #27
0
    def sendtrackback(self, req, form):
        """
        Send a new trackback
        """
        if CFG_WEBLINKBACK_TRACKBACK_ENABLED:
            argd = wash_urlargd(
                form, {
                    'url':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                    'title':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                    'excerpt':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                    'blog_name':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                    'id':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                    'source':
                    (str, CFG_WEBLINKBACK_SUBSCRIPTION_DEFAULT_ARGUMENT_NAME),
                })

            perform_sendtrackback(req, self.recid, argd['url'], argd['title'],
                                  argd['excerpt'], argd['blog_name'],
                                  argd['id'], argd['source'], argd['ln'])
        else:
            perform_sendtrackback_disabled(req)
예제 #28
0
파일: openid.py 프로젝트: mhellmic/b2share
    def _get_response(req):
        """
        Constructs the response returned from the OpenID provider

        @param req: request
        @type req: invenio.legacy.wsgi.SimulatedModPythonRequest
        """
        from invenio.ext.legacy.handler import wash_urlargd
        from openid.consumer import consumer

        content = {}
        for key in req.form.keys():
            content[key] = (str, '')

        args = wash_urlargd(req.form, content)

        if 'ln' in args:
            del args['ln']

        if 'referer' in args:
            if not args['referer']:
                del args['referer']

        oidconsumer = consumer.Consumer({"id": get_session(req)}, None)
        url = CFG_SITE_SECURE_URL + "/youraccount/login"
        req.g['openid_provider_name'] = args['provider']
        req.g['openid_response'] = oidconsumer.complete(args, url)
예제 #29
0
    def __call__(self, req, form):
        argd = wash_urlargd(form, {
            'id' : (int, 0),
            'format' : (str, '')})

        formats_dict = get_output_formats(True)
        formats = {}
        for f in formats_dict.values():
            if f['attrs']['visibility']:
                formats[f['attrs']['code'].lower()] = f['attrs']['content_type']
        del formats_dict

        if argd['id'] and argd['format']:
            ## Translate back common format names
            f = {
                'nlm' : 'xn',
                'marcxml' : 'xm',
                'dc' : 'xd',
                'endnote' : 'xe',
                'mods' : 'xo'
            }.get(argd['format'], argd['format'])
            if f in formats:
                redirect_to_url(req, '%s/%s/%s/export/%s' % (CFG_SITE_URL, CFG_SITE_RECORD, argd['id'], f))
            else:
                raise apache.SERVER_RETURN, apache.HTTP_NOT_ACCEPTABLE
        elif argd['id']:
            return websearch_templates.tmpl_unapi(formats, identifier=argd['id'])
        else:
            return websearch_templates.tmpl_unapi(formats)
예제 #30
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")
예제 #31
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)
예제 #32
0
    def getattachedfile(self, req, form):
        """
        Returns a file uploaded to the submission 'drop box' by the
        CKEditor.
        """
        argd = wash_urlargd(form, {'file': (str, None),
                                   'type': (str, None),
                                   'uid': (int, 0)})

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)

        if not argd['file'] is None:
            # Prepare path to file on disk. Normalize the path so that
            # ../ and other dangerous components are removed.
            path = os.path.abspath(CFG_PREFIX + '/var/tmp/attachfile/' + \
                                   '/'  + str(argd['uid']) + \
                                   '/' + argd['type'] + '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith(CFG_PREFIX + '/var/tmp/attachfile/') and os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        return(apache.HTTP_NOT_FOUND)
예제 #33
0
 def restupload(req, form):
     """Interface for robots used like this:
         $ curl --data-binary '@localfile.xml' http://cds.cern.ch/batchuploader/robotupload/[insert|replace|correct|append]?[callback_url=http://...]&nonce=1234 -A invenio_webupload
     """
     filepath, mimetype = handle_file_post(req)
     argd = wash_urlargd(form, {'callback_url': (str, None), 'nonce': (str, None), 'special_treatment': (str, None)})
     return cli_upload(req, open(filepath), '--' + path[0], argd['callback_url'], argd['nonce'], argd['special_treatment'])
예제 #34
0
    def display(self, req, form):
        """Display search history page.  A misnomer."""

        argd = wash_urlargd(form, {'p': (str, "n")
                                   })

        uid = getUid(req)

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

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/youralerts/display" % \
                                             (CFG_SITE_SECURE_URL,),
                                       navmenuid="youralerts")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/youralerts/display%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_usealerts']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use alerts."))

        if argd['p'] == 'y':
            _title = _("Popular Searches")
        else:
            _title = _("Your Searches")

        # register event in webstat
        if user_info['email']:
            user_str = "%s (%d)" % (user_info['email'], user_info['uid'])
        else:
            user_str = ""
        try:
            register_customevent("alerts", ["display", "", user_str])
        except:
            register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'")

        return page(title=_title,
                    body=webalert.perform_display(argd['p'], uid, ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
예제 #35
0
    def metasubmit(self, req, form):
        """ Function called after submitting the metadata upload form.
            Checks if input fields are correct before uploading.
        """
        argd = wash_urlargd(
            form, {
                'metafile': (str, None),
                'filetype': (str, None),
                'mode': (str, None),
                'submit_date': (str, None),
                'submit_time': (str, None),
                'filename': (str, None),
                'priority': (str, None),
                'email_logs_to': (str, None)
            })
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed
        if argd['metafile'] == None:
            redirect_to_url(
                req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL))

        not_authorized = user_authorization(req, argd['ln'])
        if not_authorized:
            return not_authorized

        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        auth_code, auth_message = metadata_upload(req, argd['metafile'],
                                                  argd['filetype'],
                                                  argd['mode'].split()[0],
                                                  date, time, argd['filename'],
                                                  argd['ln'], argd['priority'],
                                                  argd['email_logs_to'])

        if auth_code == 1:  # not authorized
            referer = '/batchuploader/'
            return page_not_authorized(req=req,
                                       referer=referer,
                                       text=auth_message,
                                       navmenuid="batchuploader")
        else:
            uid = getUid(req)
            body = batchuploader_templates.tmpl_display_menu(argd['ln'])
            body += batchuploader_templates.tmpl_upload_successful(argd['ln'])
            title = _("Upload successful")
            navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                            (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
            return page(title=title,
                        body=body,
                        uid=uid,
                        navtrail=navtrail,
                        lastupdated=__lastupdated__,
                        req=req,
                        language=argd['ln'],
                        navmenuid="batchuploader")
예제 #36
0
    def summary(self, req, form):
        args = wash_urlargd(
            form, {
                'doctype': (str, ''),
                'act': (str, ''),
                'access': (str, ''),
                'indir': (str, '')
            })
        ln = args['ln']

        uid = getUid(req)
        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "../summary", navmenuid='submit')

        t = ""
        curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, args['indir'],
                              args['doctype'], args['access'])
        try:
            assert (curdir == os.path.abspath(curdir))
        except AssertionError:
            register_exception(
                req=req,
                alert_admin=True,
                prefix=
                'Possible cracking tentative: indir="%s", doctype="%s", access="%s"'
                % (args['indir'], args['doctype'], args['access']))
            return warning_page("Invalid parameters", req, ln)

        subname = "%s%s" % (args['act'], args['doctype'])

        res = run_sql(
            "select sdesc,fidesc,pagenb,level from sbmFIELD where subname=%s "
            "order by pagenb,fieldnb", (subname, ))
        nbFields = 0

        values = []
        for arr in res:
            if arr[0] != "":
                val = {
                    'mandatory': (arr[3] == 'M'),
                    'value': '',
                    'page': arr[2],
                    'name': arr[0],
                }
                if os.path.exists(os.path.join(curdir, curdir, arr[1])):
                    fd = open(os.path.join(curdir, arr[1]), "r")
                    value = fd.read()
                    fd.close()
                    value = value.replace("\n", " ")
                    value = value.replace("Select:", "")
                else:
                    value = ""
                val['value'] = value
                values.append(val)

        return websubmit_templates.tmpl_submit_summary(
            ln=args['ln'],
            values=values,
        )
예제 #37
0
    def write(self, req, form):
        """ write(): interface for message composing
        @param msg_reply_id: if this message is a reply to another, id of the
                             other
        @param msg_to: if this message is not a reply, nickname of the user it
                       must be delivered to.
        @param msg_to_group: name of group to send message to
        @param ln: language
        @return: the compose page
        """
        argd = wash_urlargd(form, {'msg_reply_id': (int, 0),
                                   'msg_to': (str, ""),
                                   'msg_to_group': (str, ""),
                                   'msg_subject' : (str, ""),
                                   'msg_body' : (str, "")})

        # Check if user is logged
        uid = getUid(req)

        _ = gettext_set_language(argd['ln'])

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourmessages/write" % \
                                             (CFG_SITE_URL,),
                                       navmenuid="yourmessages")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/yourmessages/write%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_usemessages']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use messages."))

        # Request the composing page
        body = perform_request_write(
                                     uid=uid,
                                     msg_reply_id=argd['msg_reply_id'],
                                     msg_to=argd['msg_to'],
                                     msg_to_group=argd['msg_to_group'],
                                     msg_subject=argd['msg_subject'],
                                     msg_body=argd['msg_body'],
                                     ln=argd['ln'])
        title = _("Write a message")

        return page(title       = title,
                    body        = body,
                    navtrail    = get_navtrail(argd['ln'], title),
                    uid         = uid,
                    lastupdated = __lastupdated__,
                    req         = req,
                    language    = argd['ln'],
                    navmenuid   = "yourmessages",
                    secure_page_p=1)
예제 #38
0
    def display(self, req, form):
        """Display search history page.  A misnomer."""

        argd = wash_urlargd(form, {'p': (str, "n")
                                   })

        uid = getUid(req)

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

        if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/youralerts/display" % \
                                             (CFG_SITE_SECURE_URL,),
                                       navmenuid="youralerts")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/youralerts/display%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_usealerts']:
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use alerts."))

        if argd['p'] == 'y':
            _title = _("Popular Searches")
        else:
            _title = _("Your Searches")

        # register event in webstat
        if user_info['email']:
            user_str = "%s (%d)" % (user_info['email'], user_info['uid'])
        else:
            user_str = ""
        try:
            register_customevent("alerts", ["display", "", user_str])
        except:
            register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'")

        return page(title=_title,
                    body=webalert.perform_display(argd['p'], uid, ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
예제 #39
0
 def openurl(self, req, form):
     """ OpenURL Handler."""
     argd = wash_urlargd(form, websearch_templates.tmpl_openurl_accepted_args)
     ret_url = websearch_templates.tmpl_openurl2invenio(argd)
     if ret_url:
         return redirect_to_url(req, ret_url)
     else:
         return redirect_to_url(req, CFG_SITE_URL)
예제 #40
0
    def manage(self, req, form):
        """ Web interface for the management of the info space """
        uid = getUid(req)
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})

        # If it is an Ajax request, extract any JSON data.
        ajax_request = False
        if 'jsondata' in form:
            json_data = json.loads(str(form['jsondata']))
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}

        # Authorization.
        user_info = collect_user_info(req)
        if user_info['email'] == 'guest':
            # User is not logged in.
            if not ajax_request:
                # Do not display the introductory recID selection box to guest
                # users (as it used to be with v0.99.0):
                dummy_auth_code, auth_message = acc_authorize_action(
                    req, 'runinfomanager')
                referer = '/info'
                return page_not_authorized(req=req,
                                           referer=referer,
                                           text=auth_message)
            else:
                # Session has most likely timed out.
                json_response.update({'status': "timeout"})
                return json.dumps(json_response)
        # Handle request.
        if not ajax_request:
            body, errors, warnings = perform_request_init_info_interface()
            title = 'Info Space Manager'
            return page(title=title,
                        body=body,
                        errors=errors,
                        warnings=warnings,
                        uid=uid,
                        language=argd['ln'],
                        req=req)
        else:
            # Handle AJAX request.
            if json_data["action"] == "listFiles":
                json_response.update(
                    perform_request_edit_file(json_data["filename"]))
                try:
                    return json.dumps(json_response)
                except UnicodeDecodeError:
                    # Error decoding, the file can be a pdf, image or any kind
                    # of file non-editable
                    return json.dumps({"status": "error_file_not_readable"})

            if json_data["action"] == "saveContent":
                return json.dumps(
                    perform_request_save_file(json_data["filename"],
                                              json_data["filecontent"]))
예제 #41
0
    def getuploadedfile(self, req, form):
        """
        Stream uploaded files.

        For the moment, restrict to files in ./curdir/files/uid or
        ./curdir/icons/uid directory, so that we are sure we stream
        files only to the user who uploaded them.
        """
        argd = wash_urlargd(form, {'indir': (str, None),
                                   'doctype': (str, None),
                                   'access': (str, None),
                                   'icon': (int, 0),
                                   'key': (str, None),
                                   'filename': (str, None),
                                   'nowait': (int, 0)})

        if None in argd.values():
            raise apache.SERVER_RETURN(apache.HTTP_BAD_REQUEST)

        uid = getUid(req)

        if argd['icon']:
            file_path = os.path.join(CFG_WEBSUBMIT_STORAGEDIR,
                                     argd['indir'],
                                     argd['doctype'],
                                     argd['access'],
                                     'icons',
                                     str(uid),
                                     argd['key'],
                                     argd['filename']
                                     )
        else:
            file_path = os.path.join(CFG_WEBSUBMIT_STORAGEDIR,
                                     argd['indir'],
                                     argd['doctype'],
                                     argd['access'],
                                     'files',
                                     str(uid),
                                     argd['key'],
                                     argd['filename']
                                     )

        abs_file_path = os.path.abspath(file_path)
        if abs_file_path.startswith(CFG_WEBSUBMIT_STORAGEDIR):
            # Check if file exist. Note that icon might not yet have
            # been created.
            if not argd['nowait']:
                for i in range(5):
                    if os.path.exists(abs_file_path):
                        return stream_file(req, abs_file_path)
                    time.sleep(1)
            else:
                if os.path.exists(abs_file_path):
                        return stream_file(req, abs_file_path)

        # Send error 404 in all other cases
        raise apache.SERVER_RETURN(apache.HTTP_NOT_FOUND)
예제 #42
0
    def confirm(self, req, form):
        """ Function called after submitting the metadata upload form.
            Shows a summary of actions to be performed and possible errors
        """
        argd = wash_urlargd(
            form, {
                'metafile': (Field, None),
                'filetype': (str, None),
                'mode': (str, None),
                'submit_date': (str, None),
                'submit_time': (str, None),
                'filename': (str, None),
                'priority': (str, None),
                'skip_simulation': (str, None),
                'email_logs_to': (str, None)
            })
        _ = gettext_set_language(argd['ln'])

        # Check if the page is directly accessed or no file selected
        if not argd['metafile']:
            redirect_to_url(
                req, "%s/batchuploader/metadata" % (CFG_SITE_SECURE_URL))

        metafile = argd['metafile'].value
        if argd['filetype'] != 'marcxml':
            metafile = _transform_input_to_marcxml(file_input=metafile)


        date = argd['submit_date'] not in ['yyyy-mm-dd', ''] \
                and argd['submit_date'] or ''
        time = argd['submit_time'] not in ['hh:mm:ss', ''] \
                and argd['submit_time'] or ''

        errors_upload = ''

        skip_simulation = argd['skip_simulation'] == "skip"
        if not skip_simulation:
            errors_upload = perform_upload_check(metafile, argd['mode'])

        body = batchuploader_templates.tmpl_display_confirm_page(
            argd['ln'], metafile, argd['filetype'], argd['mode'], date, time,
            argd['filename'], argd['priority'], errors_upload, skip_simulation,
            argd['email_logs_to'])

        uid = getUid(req)
        navtrail = '''<a class="navtrail" href="%s/batchuploader/metadata">%s</a>''' % \
                    (CFG_SITE_SECURE_URL, _("Metadata batch upload"))
        title = 'Confirm your actions'
        return page(title=title,
                    body=body,
                    metaheaderadd=batchuploader_templates.tmpl_styles(),
                    uid=uid,
                    navtrail=navtrail,
                    lastupdated=__lastupdated__,
                    req=req,
                    language=argd['ln'],
                    navmenuid="batchuploader")
예제 #43
0
    def article(self, req, form):
        """
        Article page.
        Washes all the parameters and stores them in journal_defaults dict
        for subsequent format_elements.
        Passes on to logic function and eventually returns HTML.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                    'issue': (str, ""),
                                    'category': (str, ""),
                                    'number': (str, ""),
                                    'ln': (str, ""),
                                   }
                            )
        try:
            ln = wash_journal_language(argd['ln'])
            journal_name = wash_journal_name(ln, argd['name'])
            issue = wash_issue_number(ln, journal_name,
                                      argd['issue'])
            issue_year = issue.split('/')[1]
            issue_number = issue.split('/')[0]
            category = wash_category(ln, argd['category'], journal_name, issue_number)
            number = wash_article_number(ln, argd['number'], journal_name)
            recid = get_recid_from_legacy_number(issue, category, int(number))
        except InvenioWebJournalNoJournalOnServerError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoNameError as e:
            return e.user_box(req)
        except InvenioWebJournalNoCurrentIssueError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalIssueNumberBadlyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoArticleNumberError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoCategoryError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalJournalIdNotFoundDBError as e:
            register_exception(req=req)
            return e.user_box(req)

        if recid != -1:
            # Found a corresponding record
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '/' + str(recid) + '?ln=' + ln)
        else:
            # Corresponding record not found. Display index
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '?ln=' + ln)
예제 #44
0
    def article(self, req, form):
        """
        Article page.
        Washes all the parameters and stores them in journal_defaults dict
        for subsequent format_elements.
        Passes on to logic function and eventually returns HTML.
        """
        argd = wash_urlargd(form, {'name': (str, ""),
                                    'issue': (str, ""),
                                    'category': (str, ""),
                                    'number': (str, ""),
                                    'ln': (str, ""),
                                   }
                            )
        try:
            ln = wash_journal_language(argd['ln'])
            journal_name = wash_journal_name(ln, argd['name'])
            issue = wash_issue_number(ln, journal_name,
                                      argd['issue'])
            issue_year = issue.split('/')[1]
            issue_number = issue.split('/')[0]
            category = wash_category(ln, argd['category'], journal_name, issue_number)
            number = wash_article_number(ln, argd['number'], journal_name)
            recid = get_recid_from_legacy_number(issue, category, int(number))
        except InvenioWebJournalNoJournalOnServerError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoNameError as e:
            return e.user_box(req)
        except InvenioWebJournalNoCurrentIssueError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalIssueNumberBadlyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoArticleNumberError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoCategoryError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalJournalIdNotFoundDBError as e:
            register_exception(req=req)
            return e.user_box(req)

        if recid != -1:
            # Found a corresponding record
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '/' + str(recid) + '?ln=' + ln)
        else:
            # Corresponding record not found. Display index
            redirect_to_url(req, CFG_SITE_URL + \
                            '/journal/' + journal_name + '/' + issue_year + \
                            '/' + issue_number + '/' + category + \
                            '?ln=' + ln)
예제 #45
0
    def plugin_builder(the_plugin):
        """
        Enhanced plugin_builder created by L{create_enhanced_plugin_builder}.

        :param plugin: the code of the module as just read from package.
        :return: the plugin in the form of a map.
        """
        plugin_name = the_plugin.__name__
        plugin = {}

        if compulsory_objects:
            for object_name, object_signature in \
                    iteritems(compulsory_objects):
                the_object = getattr(the_plugin, object_name, None)
                if the_object is None:
                    raise AutodiscoveryError('Plugin "%s" does not '
                                             'contain compulsory object "%s"' %
                                             (plugin_name, object_name))
                try:
                    check_signature(object_name, the_object, object_signature)
                except AutodiscoveryError as err:
                    raise AutodiscoveryError(
                        'Plugin "%s" contains '
                        'object "%s" with a wrong signature: %s' %
                        (plugin_name, object_name, err))
                plugin[object_name] = the_object

        if optional_objects:
            for object_name, object_signature in iteritems(optional_objects):
                the_object = getattr(the_plugin, object_name, None)
                if the_object is not None:
                    try:
                        check_signature(object_name, the_object,
                                        object_signature)
                    except AutodiscoveryError as err:
                        raise AutodiscoveryError(
                            'Plugin "%s" '
                            'contains object "%s" with a wrong signature: %s' %
                            (plugin_name, object_name, err))
                    plugin[object_name] = the_object

        if other_data:
            the_other_data = {}
            for data_name, (dummy, data_default) in iteritems(other_data):
                the_other_data[data_name] = getattr(the_plugin, data_name,
                                                    data_default)

            try:
                the_other_data = wash_urlargd(the_other_data, other_data)
            except Exception as err:
                raise AutodiscoveryError('Plugin "%s" contains other '
                                         'data with problems: %s' %
                                         (plugin_name, err))

            plugin.update(the_other_data)
        return plugin
예제 #46
0
    def index(self, req, form):
        """Index page."""

        argd = wash_urlargd(form, {'page': (int, 1),
                                   'format': (str, "rc"),
                                   'order_by': (str, "lcf"),
                                   'per_page': (str, "all"),
                                   })
        # TODO: support also "reviews", by adding  new option to show/hide them if needed
        uid = getUid(req)

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

        # Is site ready to accept comments?
        if not CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourcomments" % \
                                             (CFG_SITE_SECURE_URL,),
                                       text="Comments are currently disabled on this site",
                                       navmenuid="yourcomments")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/yourcomments%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_sendcomments']:
            # Maybe we should still authorize if user submitted
            # comments in the past?
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use comments."))

        return page(title=_("Your Comments"),
                    body=perform_display_your_comments(user_info,
                                                       page_number=argd['page'],
                                                       selected_order_by_option=argd['order_by'],
                                                       selected_display_number_option=argd['per_page'],
                                                       selected_display_format_option=argd['format'],
                                                       ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
예제 #47
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)
예제 #48
0
def get_record_ids(argstr, date_from, date_until):
    """Returns the local and external records found for a specific query and timeframe."""

    argd = wash_urlargd(parse_qs(argstr), websearch_templates.search_results_default_urlargd)
    p       = argd.get('p', [])
    c       = argd.get('c', [])
    cc      = argd.get('cc', [])
    aas     = argd.get('aas', [])
    f       = argd.get('f', [])
    so      = argd.get('so', [])
    sp      = argd.get('sp', [])
    ot      = argd.get('ot', [])
    p1      = argd.get('p1', [])
    f1      = argd.get('f1', [])
    m1      = argd.get('m1', [])
    op1     = argd.get('op1', [])
    p2      = argd.get('p2', [])
    f2      = argd.get('f2', [])
    m2      = argd.get('m2', [])
    op2     = argd.get('op3', [])
    p3      = argd.get('p3', [])
    f3      = argd.get('f3', [])
    m3      = argd.get('m3', [])
    sc      = argd.get('sc', [])

    d1y, d1m, d1d = _date_to_tuple(date_from)
    d2y, d2m, d2d = _date_to_tuple(date_until)

    #alerts might contain collections that have been deleted
    #check if such collections are in the query, and if yes, do not include them in the search
    cc = Collection.query.filter_by(name=cc).value('name')
    if not cc and not c: #the alarm was for an entire collection that does not exist anymore
        return ([], ([], []))
    if c: # some collections were defined in the query
        c = [c_norm_name for c_norm_name in [
            Collection.query.filter_by(name=c_name).value('name')
            for c_name in c] if c_norm_name]
        # remove unknown collections from c
        if not c: #none of the collection selected in the alert still exist
            return ([], ([], []))

    # washed_colls = wash_colls(cc, c, sc, 0)
    # hosted_colls = washed_colls[3]
    # if hosted_colls:
    #     req_args = "p=%s&f=%s&d1d=%s&d1m=%s&d1y=%s&d2d=%s&d2m=%s&d2y=%s&ap=%i" % (p, f, d1d, d1m, d1y, d2d, d2m, d2y, 0)
    #     external_records = calculate_external_records(req_args, [p, p1, p2, p3], f, hosted_colls, CFG_EXTERNAL_COLLECTION_TIMEOUT, CFG_EXTERNAL_COLLECTION_MAXRESULTS_ALERTS)
    # else:
    # FIXME: removed support for hosted collections
    external_records = ([], [])

    recids = perform_request_search(of='id', p=p, c=c, cc=cc, f=f, so=so, sp=sp, ot=ot,
                                  aas=aas, p1=p1, f1=f1, m1=m1, op1=op1, p2=p2, f2=f2,
                                  m2=m2, op2=op2, p3=p3, f3=f3, m3=m3, sc=sc, d1y=d1y,
                                  d1m=d1m, d1d=d1d, d2y=d2y, d2m=d2m, d2d=d2d)

    return (recids, external_records)
예제 #49
0
    def index(self, req, form):
        """Index page."""

        argd = wash_urlargd(form, {'page': (int, 1),
                                   'format': (str, "rc"),
                                   'order_by': (str, "lcf"),
                                   'per_page': (str, "all"),
                                   })
        # TODO: support also "reviews", by adding  new option to show/hide them if needed
        uid = getUid(req)

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

        # Is site ready to accept comments?
        if not CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return page_not_authorized(req, "%s/yourcomments" % \
                                             (CFG_SITE_SECURE_URL,),
                                       text="Comments are currently disabled on this site",
                                       navmenuid="yourcomments")
        elif uid == -1 or isGuestUser(uid):
            return redirect_to_url(req, "%s/youraccount/login%s" % (
                CFG_SITE_SECURE_URL,
                make_canonical_urlargd({
                    'referer' : "%s/yourcomments%s" % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(argd, {})),
                    "ln" : argd['ln']}, {})))

        user_info = collect_user_info(req)
        if not user_info['precached_sendcomments']:
            # Maybe we should still authorize if user submitted
            # comments in the past?
            return page_not_authorized(req, "../", \
                                       text = _("You are not authorized to use comments."))

        return page(title=_("Your Comments"),
                    body=perform_display_your_comments(user_info,
                                                       page_number=argd['page'],
                                                       selected_order_by_option=argd['order_by'],
                                                       selected_display_number_option=argd['per_page'],
                                                       selected_display_format_option=argd['format'],
                                                       ln=argd['ln']),
                    navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % {
                                 'sitesecureurl' : CFG_SITE_SECURE_URL,
                                 'ln': argd['ln'],
                                 'account' : _("Your Account"),
                              },
                    description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    language=argd['ln'],
                    req=req,
                    lastupdated=__lastupdated__,
                    navmenuid='youralerts',
                    secure_page_p=1)
예제 #50
0
    def search(self, req, form):
        """
        Display search interface
        """
        argd = wash_urlargd(
            form,
            {
                "name": (str, ""),
                "issue": (str, ""),
                "archive_year": (str, ""),
                "archive_issue": (str, ""),
                "archive_select": (str, "False"),
                "archive_date": (str, ""),
                "archive_search": (str, "False"),
                "ln": (str, CFG_SITE_LANG),
                "verbose": (int, 0),
            },
        )
        try:
            # FIXME: if journal_name is empty, redirect
            ln = wash_journal_language(argd["ln"])
            washed_journal_name = wash_journal_name(ln, argd["name"])
            archive_issue = wash_issue_number(ln, washed_journal_name, argd["archive_issue"])
            archive_date = wash_archive_date(ln, washed_journal_name, argd["archive_date"])
            archive_select = argd["archive_select"]
            archive_search = argd["archive_search"]
        except InvenioWebJournalNoJournalOnServerError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalNoNameError as e:
            return e.user_box(req)
        except InvenioWebJournalNoCurrentIssueError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalIssueNumberBadlyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalArchiveDateWronglyFormedError as e:
            register_exception(req=req)
            return e.user_box(req)
        except InvenioWebJournalJournalIdNotFoundDBError as e:
            register_exception(req=req)
            return e.user_box(req)

        html = perform_request_search(
            req=req,
            journal_name=washed_journal_name,
            ln=ln,
            archive_issue=archive_issue,
            archive_select=archive_select,
            archive_date=archive_date,
            archive_search=archive_search,
            verbose=argd["verbose"],
        )
        return html
예제 #51
0
def main_page(req, recid, tabs, ln, template):
    """Generate the main page for the keyword tab

    Url style : http://url/record/[recid]/keywords
    :param req: request object
    :param recid: int docid
    :param tabs: list of tab links
    :param ln: language id
    :param template: template object
    :return: nothing, writes using req object
    """
    form = req.form
    argd = wash_urlargd(
        form,
        {
            "generate": (str, "no"),
            "sorting": (str, "occurences"),
            "type": (str, "tagcloud"),
            "numbering": (str, "off"),
            "showall": (str, "off"),
        },
    )

    for k, v in argd.items():
        argd[k] = escape(v)

    req.write(template.detailed_record_container_top(recid, tabs, ln))

    # Get the keywords from MARC (if any)
    success, keywords, marcrec = record_get_keywords(recid)

    if success:
        # check for the cached file and delete it (we don't need it anymore, data are in the DB)
        tmp_file = get_tmp_file(recid)
        if os.path.exists(tmp_file):
            try:
                os.remove(tmp_file)
            except Exception as msg:
                log.error("Error removing the cached file: %s" % tmp_file)
                log.error(msg)
    else:
        # Give user possibility to generate them ONLY if not available already
        # we may have some keywords, but they are the old ones and we want to generate new
        new_found, new_keywords, marcrec = generate_keywords(req, recid, argd)
        if keywords and new_keywords:
            for key in keywords.keys():
                if key in new_keywords:
                    log.warning('The old "DESY" keyword will be overwritten by the newly extracted one: %s' % key)
        keywords.update(new_keywords)

    if keywords:
        # Output the keywords or the generate button or some message why kw not available
        write_keywords_body(keywords, req, recid, argd, marcrec=marcrec)

    req.write(template.detailed_record_container_bottom(recid, tabs, ln))
예제 #52
0
def main_page(req, recid, tabs, ln, template):
    """Generate the main page for the keyword tab

    Url style : http://url/record/[recid]/keywords
    :param req: request object
    :param recid: int docid
    :param tabs: list of tab links
    :param ln: language id
    :param template: template object
    :return: nothing, writes using req object
    """
    form = req.form
    argd = wash_urlargd(
        form, {
            'generate': (str, 'no'),
            'sorting': (str, 'occurences'),
            'type': (str, 'tagcloud'),
            'numbering': (str, 'off'),
            'showall': (str, 'off'),
        })

    for k, v in argd.items():
        argd[k] = escape(v)

    req.write(template.detailed_record_container_top(recid, tabs, ln))

    # Get the keywords from MARC (if any)
    success, keywords, marcrec = record_get_keywords(recid)

    if success:
        # check for the cached file and delete it (we don't need it anymore, data are in the DB)
        tmp_file = get_tmp_file(recid)
        if os.path.exists(tmp_file):
            try:
                os.remove(tmp_file)
            except Exception as msg:
                log.error('Error removing the cached file: %s' % tmp_file)
                log.error(msg)
    else:
        # Give user possibility to generate them ONLY if not available already
        # we may have some keywords, but they are the old ones and we want to generate new
        new_found, new_keywords, marcrec = generate_keywords(req, recid, argd)
        if keywords and new_keywords:
            for key in keywords.keys():
                if key in new_keywords:
                    log.warning(
                        'The old "DESY" keyword will be overwritten by the newly extracted one: %s'
                        % key)
        keywords.update(new_keywords)

    if keywords:
        # Output the keywords or the generate button or some message why kw not available
        write_keywords_body(keywords, req, recid, argd, marcrec=marcrec)

    req.write(template.detailed_record_container_bottom(recid, tabs, ln))
예제 #53
0
    def job_queries(self, req, form):
        """Allows edition and manipulations of the queries of a job"""

        argd = wash_urlargd(
            form, {
                "new_button": (str, ""),
                "run_button": (str, ""),
                "delete_button": (str, ""),
                "selected_queries": (list, ""),
                "job_id": (int, -1)
            })
        # 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_id = argd["job_id"]

        try:
            # if the form is submitted through some of the buttons
            # we should perform the appropriate action
            if argd["new_button"]:
                new_query_url = "%s?job_id=%s" % (self._EDIT_QUERY_URL, job_id)
                self._redirect_to_page(req, new_query_url, language)
            if argd["delete_button"]:
                query_ids = argd["selected_queries"]
                perform_request_delete_queries(query_ids=query_ids,
                                               user_id=user_id,
                                               language=language)
            if argd["run_button"]:
                title = _("Query Results")
                query_ids = argd["selected_queries"]
                body = perform_request_run_queries(query_ids=query_ids,
                                                   user_id=user_id,
                                                   job_id=job_id,
                                                   language=language)
            else:
                title = _("Export Job Queries")
                body = perform_request_job_queries(job_id=job_id,
                                                   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)
예제 #54
0
    def not_authorized(self, req, form):
        """Displays page telling the user that
        he is not authorised to access the resource"""
        argd = wash_urlargd(form, {})

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

        text = _("You are not authorised to access this resource.")
        return page_not_authorized(req=req, ln=language, text=text)
예제 #55
0
    def manage(self, req, form):
        """ Web interface for the management of the info space """
        uid = getUid(req)
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})

        # If it is an Ajax request, extract any JSON data.
        ajax_request = False
        if 'jsondata' in form:
            json_data = json.loads(str(form['jsondata']))
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}

        # Authorization.
        user_info = collect_user_info(req)
        if user_info['email'] == 'guest':
            # User is not logged in.
            if not ajax_request:
                # Do not display the introductory recID selection box to guest
                # users (as it used to be with v0.99.0):
                dummy_auth_code, auth_message = acc_authorize_action(req,
                                                                     'runinfomanager')
                referer = '/info'
                return page_not_authorized(req=req, referer=referer,
                                           text=auth_message)
            else:
                # Session has most likely timed out.
                json_response.update({'status': "timeout"})
                return json.dumps(json_response)
        # Handle request.
        if not ajax_request:
            body, errors, warnings = perform_request_init_info_interface()
            title = 'Info Space Manager'
            return page(title=title,
                        body=body,
                        errors=errors,
                        warnings=warnings,
                        uid=uid,
                        language=argd['ln'],
                        req=req)
        else:
            # Handle AJAX request.
            if json_data["action"] == "listFiles":
                json_response.update(perform_request_edit_file(json_data["filename"]))
                try:
                    return json.dumps(json_response)
                except UnicodeDecodeError:
                    # Error decoding, the file can be a pdf, image or any kind
                    # of file non-editable
                    return json.dumps({"status": "error_file_not_readable"})

            if json_data["action"] == "saveContent":
                return json.dumps(perform_request_save_file(json_data["filename"],
                                                            json_data["filecontent"]))
예제 #56
0
 def __extract_attribute(self, req):
     """
     Load from the request the given assertion, extract all the attribute
     to properly login the user, and verify that the data are actually
     both well formed and signed correctly.
     """
     from invenio.ext.legacy.handler import wash_urlargd
     args = wash_urlargd(
         req.form, {
             'assertion': (str, ''),
             'robot': (str, ''),
             'digest': (str, ''),
             'login_method': (str, '')
         })
     assertion = args['assertion']
     digest = args['digest']
     robot = args['robot']
     login_method = args['login_method']
     shared_key = load_robot_keys().get(login_method, {}).get(robot)
     if shared_key is None:
         raise InvenioWebAccessExternalAuthError(
             "A key does not exist for robot: %s, login_method: %s" %
             (robot, login_method))
     if not self.verify(shared_key, assertion, digest):
         raise InvenioWebAccessExternalAuthError(
             "The provided assertion does not validate against the digest %s for robot %s"
             % (repr(digest), repr(robot)))
     if self.use_zlib:
         try:
             ## Workaround to Perl implementation that does not add
             ## any padding to the base64 encoding.
             needed_pad = (4 - len(assertion) % 4) % 4
             assertion += needed_pad * '='
             assertion = decompress(base64.urlsafe_b64decode(assertion))
         except:
             raise InvenioWebAccessExternalAuthError(
                 "The provided assertion is corrupted")
     data = json_unicode_to_utf8(json.loads(assertion))
     if not isinstance(data, dict):
         raise InvenioWebAccessExternalAuthError(
             "The provided assertion is invalid")
     timeout = data[self.timeout_attribute_name]
     if timeout < time.time():
         raise InvenioWebAccessExternalAuthError(
             "The provided assertion is expired")
     userip = data.get(self.userip_attribute_name)
     if not self.check_user_ip or (normalize_ip(
             userip, self.check_user_ip) == normalize_ip(
                 req.remote_ip, self.check_user_ip)):
         return data
     else:
         raise InvenioWebAccessExternalAuthError(
             "The provided assertion has been issued for a different IP address (%s instead of %s)"
             % (userip, req.remote_ip))