def perform_request_download_job_result(req, job_result_id, output_format, user_id, language = CFG_SITE_LANG):
    """
    Returns to the browser zip file containing the content of the job result

    @param req: request as received from apache
    @param job_result_id: identifier of the job result that should be displayed
    @param user_id: identifier of the current user
    @param language: language of the page
    @param output_format: format for downloading the result
    """
    _check_user_ownership_on_job_result(user_id, job_result_id, language)

    job_result = fieldexporter_dblayer.get_job_result(job_result_id)
    if output_format != fieldexporter_dblayer.Job.OUTPUT_FORMAT_MISSING:
        job_result.get_job().set_output_format(output_format)

    download_file_name = "result.zip"
    temp_zip_file_path = ""

    try:
        temp_zip_file_path = fieldexporter_dblayer.create_temporary_zip_file_with_job_result(job_result)
        bibdocfile.stream_file(req, temp_zip_file_path, download_file_name)
    finally:
        if os.path.exists(temp_zip_file_path):
            os.remove(temp_zip_file_path)
Beispiel #2
0
def application(environ, start_response):
    """
    Entry point for wsgi.
    """
    ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues>
    req = SimulatedModPythonRequest(environ, start_response)
    #print 'Starting mod_python simulation'

    try:
        if (CFG_FULL_HTTPS or
            (CFG_HAS_HTTPS_SUPPORT
             and get_session(req).need_https)) and not req.is_https():
            # We need to isolate the part of the URI that is after
            # CFG_SITE_URL, and append that to our CFG_SITE_SECURE_URL.
            original_parts = urlparse(req.unparsed_uri)
            plain_prefix_parts = urlparse(CFG_SITE_URL)
            secure_prefix_parts = urlparse(CFG_SITE_SECURE_URL)

            # Compute the new path
            plain_path = original_parts[2]
            plain_path = secure_prefix_parts[2] + \
                        plain_path[len(plain_prefix_parts[2]):]

            # ...and recompose the complete URL
            final_parts = list(secure_prefix_parts)
            final_parts[2] = plain_path
            final_parts[-3:] = original_parts[-3:]

            target = urlunparse(final_parts)
            redirect_to_url(req, target)

        possible_module, possible_handler = is_mp_legacy_publisher_path(
            environ['PATH_INFO'])
        if possible_module is not None:
            mp_legacy_publisher(req, possible_module, possible_handler)
        elif CFG_WSGI_SERVE_STATIC_FILES:
            possible_static_path = is_static_path(environ['PATH_INFO'])
            if possible_static_path is not None:
                from invenio.bibdocfile import stream_file
                stream_file(req, possible_static_path)
            else:
                ret = invenio_handler(req)
        else:
            ret = invenio_handler(req)
        req.flush()
    except SERVER_RETURN, status:
        status = int(str(status))
        if status not in (OK, DONE):
            req.status = status
            req.headers_out['content-type'] = 'text/html'
            admin_to_be_alerted = alert_admin_for_server_status_p(
                status, req.headers_in.get('referer'))
            if admin_to_be_alerted:
                register_exception(req=req, alert_admin=True)
            if not req.response_sent_p:
                start_response(req.get_wsgi_status(),
                               req.get_low_level_headers(), sys.exc_info())
            return generate_error_page(req, admin_to_be_alerted)
        else:
            req.flush()
    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)
    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)
def application(environ, start_response):
    """
    Entry point for wsgi.
    """
    ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues>
    req = SimulatedModPythonRequest(environ, start_response)
    #print 'Starting mod_python simulation'
    try:
        try:
            possible_module, possible_handler = is_mp_legacy_publisher_path(
                environ['PATH_INFO'])
            if possible_module is not None:
                mp_legacy_publisher(req, possible_module, possible_handler)
            elif CFG_WSGI_SERVE_STATIC_FILES:
                possible_static_path = is_static_path(environ['PATH_INFO'])
                if possible_static_path is not None:
                    from invenio.bibdocfile import stream_file
                    stream_file(req, possible_static_path)
                else:
                    ret = invenio_handler(req)
            else:
                ret = invenio_handler(req)
            req.flush()
        except SERVER_RETURN, status:
            status = int(str(status))
            if status not in (OK, DONE):
                req.status = status
                req.headers_out['content-type'] = 'text/html'
                admin_to_be_alerted = alert_admin_for_server_status_p(
                    status, req.headers_in.get('referer'))
                if admin_to_be_alerted:
                    register_exception(req=req, alert_admin=True)
                if not req.response_sent_p:
                    start_response(req.get_wsgi_status(),
                                   req.get_low_level_headers(), sys.exc_info())
                return generate_error_page(req, admin_to_be_alerted)
            else:
                req.flush()
        except:
            register_exception(req=req, alert_admin=True)
            if not req.response_sent_p:
                req.status = HTTP_INTERNAL_SERVER_ERROR
                req.headers_out['content-type'] = 'text/html'
                start_response(req.get_wsgi_status(),
                               req.get_low_level_headers(), sys.exc_info())
                if CFG_DEVEL_SITE:
                    return [
                        "<pre>%s</pre>" % cgi.escape(
                            get_pretty_traceback(req=req,
                                                 exc_info=sys.exc_info()))
                    ]
                    from cgitb import html
                    return [html(sys.exc_info())]
                return generate_error_page(req)
            else:
                return generate_error_page(req, page_already_started=True)
    def __call__(self, req, form):
        """Serve webdoc page in the given language."""
        argd = wash_urlargd(form, {"ln": (str, CFG_SITE_LANG)})
        file_requested_ext = os.path.splitext(req.uri)
        if file_requested_ext:
            uri_parts = req.uri.split(os.sep)
            location = INFO_PREFIX + os.sep + os.sep.join(uri_parts[uri_parts.index("info") + 1 :])
            # Make sure that the file to be opened is inside of the info space
            if file_in_info_space(location) and os.path.isfile(location):
                stream_file(req, location)
                return

        return display_webdoc_page(self.webdocname, categ="info", ln=argd["ln"], req=req)
def application(environ, start_response):
    """
    Entry point for wsgi.
    """
    ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues>
    req = SimulatedModPythonRequest(environ, start_response)
    #print 'Starting mod_python simulation'
    try:
        try:
            possible_module, possible_handler = is_mp_legacy_publisher_path(environ['PATH_INFO'])
            if possible_module is not None:
                mp_legacy_publisher(req, possible_module, possible_handler)
            elif CFG_WSGI_SERVE_STATIC_FILES:
                possible_static_path = is_static_path(environ['PATH_INFO'])
                if possible_static_path is not None:
                    from invenio.bibdocfile import stream_file
                    stream_file(req, possible_static_path)
                else:
                    ret = invenio_handler(req)
            else:
                ret = invenio_handler(req)
            req.flush()
        except SERVER_RETURN, status:
            status = int(str(status))
            if status not in (OK, DONE):
                req.status = status
                req.headers_out['content-type'] = 'text/html'
                admin_to_be_alerted = alert_admin_for_server_status_p(status,
                                                  req.headers_in.get('referer'))
                if admin_to_be_alerted:
                    register_exception(req=req, alert_admin=True)
                if not req.response_sent_p:
                    start_response(req.get_wsgi_status(), req.get_low_level_headers(), sys.exc_info())
                return generate_error_page(req, admin_to_be_alerted)
            else:
                req.flush()
        except:
            register_exception(req=req, alert_admin=True)
            if not req.response_sent_p:
                req.status = HTTP_INTERNAL_SERVER_ERROR
                req.headers_out['content-type'] = 'text/html'
                start_response(req.get_wsgi_status(), req.get_low_level_headers(), sys.exc_info())
                if CFG_DEVEL_SITE:
                    return ["<pre>%s</pre>" % cgi.escape(get_pretty_traceback(req=req, exc_info=sys.exc_info()))]
                    from cgitb import html
                    return [html(sys.exc_info())]
                return generate_error_page(req)
            else:
                return generate_error_page(req, page_already_started=True)
    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
    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)
    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),
            },
        )

        if None in argd.values():
            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.
            for i in range(5):
                if os.path.exists(abs_file_path):
                    return stream_file(req, abs_file_path)
                time.sleep(1)

        # Send error 404 in all other cases
        return apache.HTTP_NOT_FOUND
    def __call__(self, req, form):
        """Serve webdoc page in the given language."""
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})
        file_requested_ext = os.path.splitext(req.uri)
        if file_requested_ext:
            uri_parts = req.uri.split(os.sep)
            location = INFO_PREFIX + os.sep + os.sep.join(
                uri_parts[uri_parts.index('info') + 1:])
            # Make sure that the file to be opened is inside of the info space
            if file_in_info_space(location) and os.path.isfile(location):
                stream_file(req, location)
                return

        return display_webdoc_page(self.webdocname,
                                   categ="info",
                                   ln=argd['ln'],
                                   req=req)
Beispiel #12
0
 def post2(self, req, form):
     """
     This is to test L{handle_file_post} function.
     """
     from invenio.webinterface_handler_wsgi_utils import handle_file_post
     from invenio.bibdocfile import stream_file
     if req.method != 'POST':
         body = """<p>Please send a file via POST.</p>"""
         return page("test2", body=body, req=req)
     path, mimetype = handle_file_post(req)
     return stream_file(req, path, mime=mimetype)
 def post2(self, req, form):
     """
     This is to test L{handle_file_post} function.
     """
     from invenio.webinterface_handler_wsgi_utils import handle_file_post
     from invenio.bibdocfile import stream_file
     if req.method != 'POST':
         body = """<p>Please send a file via POST.</p>"""
         return page("test2", body=body, req=req)
     path, mimetype = handle_file_post(req)
     return  stream_file(req, path, mime=mimetype)
 def post2(self, req, form):
     """
     This is to test L{handle_file_post} function.
     """
     from invenio.webinterface_handler_wsgi_utils import handle_file_post
     from invenio.bibdocfile import stream_file
     argd = wash_urlargd(form, {"save": (str, "")})
     if req.method != 'POST':
         body = """<p>Please send a file via POST.</p>"""
         return page("test2", body=body, req=req)
     path, mimetype = handle_file_post(req)
     if argd['save'] and argd['save'].startswith(CFG_TMPDIR):
         open(argd['save'], "w").write(open(path).read())
     return stream_file(req, path, mime=mimetype)
    def _get(self, req, form):
        """
        Returns a file attached to a comment.

        A file is attached to a comment, by a user (who is the author
        of the comment), and is of a certain type (file, image,
        etc). Therefore these 3 values are part of the URL. Eg:
        CFG_SITE_URL/record/5953/comments/attachments/get/652/file/myfile.pdf
        """
        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)
        (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text = auth_msg)

        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('/opt/cds-invenio/var/data/comments/' + \
                                   str(self.recid) + '/'  + str(argd['uid']) + \
                                   '/' + argd['type'] + '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith('/opt/cds-invenio/var/data/comments/' + \
                               str(self.recid)) and \
                   os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        return(apache.HTTP_NOT_FOUND)
    def _get(self, req, form):
        """
        Returns a file attached to a comment.

        Example:
        CFG_SITE_URL/record/5953/comments/attachments/get/652/myfile.pdf
        where 652 is the comment ID
        """
        argd = wash_urlargd(form, {'file': (str, None),
                                   'comid': (int, 0)})
        _ = gettext_set_language(argd['ln'])

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check that user can view record, and its comments (protected
        # with action "viewcomment")
        (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg)

        # Does comment exist?
        if not query_get_comment(argd['comid']):
            req.status = apache.HTTP_NOT_FOUND
            return page(title=_("Page Not Found"),
                        body=_('The requested comment could not be found'),
                        req=req)

        # Check that user can view this particular comment, protected
        # using its own restriction
        (auth_code, auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
        if auth_code and user_info['email'] == 'guest' and not user_info['apache_user']:
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        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('/opt/cds-invenio/var/data/comments/' + \
                                   str(self.recid) + '/'  + str(argd['comid']) + \
                                   '/' + argd['file'])

            # Check that we are really accessing attachements
            # directory, for the declared record.
            if path.startswith('/opt/cds-invenio/var/data/comments/' + \
                               str(self.recid)) and \
                   os.path.exists(path):
                return stream_file(req, path)

        # Send error 404 in all other cases
        req.status = apache.HTTP_NOT_FOUND
        return page(title=_("Page Not Found"),
                    body=_('The requested file could not be found'),
                    req=req,
                    language=argd['ln'])
Beispiel #17
0
    def _get(self, req, form):
        """
        Returns a file attached to a comment.

        Example:
        CFG_SITE_URL/CFG_SITE_RECORD/5953/comments/attachments/get/652/myfile.pdf
        where 652 is the comment ID
        """
        argd = wash_urlargd(form, {'file': (str, None), 'comid': (int, 0)})
        _ = gettext_set_language(argd['ln'])

        # Can user view this record, i.e. can user access its
        # attachments?
        uid = getUid(req)
        user_info = collect_user_info(req)
        # Check that user can view record, and its comments (protected
        # with action "viewcomment")
        (auth_code,
         auth_msg) = check_user_can_view_comments(user_info, self.recid)
        if auth_code and user_info['email'] == 'guest':
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = '/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)

        # Does comment exist?
        if not query_get_comment(argd['comid']):
            req.status = apache.HTTP_NOT_FOUND
            return page(title=_("Page Not Found"),
                        body=_('The requested comment could not be found'),
                        req=req)

        # Check that user can view this particular comment, protected
        # using its own restriction
        (auth_code,
         auth_msg) = check_user_can_view_comment(user_info, argd['comid'])
        if auth_code and user_info['email'] == 'guest':
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        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/data/comments/' + \
                                   str(self.recid) + '/'  + str(argd['comid']) + \
                                   '/' + argd['file'])

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

        # Send error 404 in all other cases
        req.status = apache.HTTP_NOT_FOUND
        return page(title=_("Page Not Found"),
                    body=_('The requested file could not be found'),
                    req=req,
                    language=argd['ln'])
def application(environ, start_response):
    """
    Entry point for wsgi.
    """
    ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues>
    req = SimulatedModPythonRequest(environ, start_response)
    #print 'Starting mod_python simulation'
    try:
        try:
            if (CFG_FULL_HTTPS or (CFG_HAS_HTTPS_SUPPORT and get_session(req).need_https)) and not req.is_https():
                # We need to isolate the part of the URI that is after
                # CFG_SITE_URL, and append that to our CFG_SITE_SECURE_URL.
                original_parts = urlparse(req.unparsed_uri)
                plain_prefix_parts = urlparse(CFG_SITE_URL)
                secure_prefix_parts = urlparse(CFG_SITE_SECURE_URL)

                # Compute the new path
                plain_path = original_parts[2]
                plain_path = secure_prefix_parts[2] + \
                            plain_path[len(plain_prefix_parts[2]):]

                # ...and recompose the complete URL
                final_parts = list(secure_prefix_parts)
                final_parts[2] = plain_path
                final_parts[-3:] = original_parts[-3:]

                target = urlunparse(final_parts)
                redirect_to_url(req, target)

            possible_module, possible_handler = is_mp_legacy_publisher_path(environ['PATH_INFO'])
            if possible_module is not None:
                mp_legacy_publisher(req, possible_module, possible_handler)
            elif CFG_WSGI_SERVE_STATIC_FILES:
                possible_static_path = is_static_path(environ['PATH_INFO'])
                if possible_static_path is not None:
                    from invenio.bibdocfile import stream_file
                    stream_file(req, possible_static_path)
                else:
                    ret = invenio_handler(req)
            else:
                ret = invenio_handler(req)
            req.flush()
        except SERVER_RETURN, status:
            status = int(str(status))
            if status not in (OK, DONE):
                req.status = status
                req.headers_out['content-type'] = 'text/html'
                admin_to_be_alerted = alert_admin_for_server_status_p(status,
                                                  req.headers_in.get('referer'))
                if admin_to_be_alerted:
                    register_exception(req=req, alert_admin=True)
                if not req.response_sent_p:
                    start_response(req.get_wsgi_status(), req.get_low_level_headers(), sys.exc_info())
                return generate_error_page(req, admin_to_be_alerted)
            else:
                req.flush()
        except:
            register_exception(req=req, alert_admin=True)
            if not req.response_sent_p:
                req.status = HTTP_INTERNAL_SERVER_ERROR
                req.headers_out['content-type'] = 'text/html'
                start_response(req.get_wsgi_status(), req.get_low_level_headers(), sys.exc_info())
                if CFG_DEVEL_SITE:
                    return ["<pre>%s</pre>" % cgi.escape(get_pretty_traceback(req=req, exc_info=sys.exc_info()))]
                    from cgitb import html
                    return [html(sys.exc_info())]
                return generate_error_page(req)
            else:
                return generate_error_page(req, page_already_started=True)