Beispiel #1
0
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 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 #3
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)
Beispiel #4
0
    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 #5
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)
Beispiel #6
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)
Beispiel #7
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)
Beispiel #8
0
    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 #9
0
 def post2(self, req, form):
     """
     This is to test L{handle_file_post} function.
     """
     from invenio.legacy.wsgi.utils import handle_file_post
     from invenio.legacy.bibdocfile.api 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)
Beispiel #10
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 = (
                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)

        # 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 = (
                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)
        elif auth_code:
            return page_not_authorized(req, "../", text=auth_msg, ln=argd["ln"])

        # Check that comment is not currently deleted
        if is_comment_deleted(argd["comid"]):
            return page_not_authorized(
                req, "../", text=_("You cannot access files of a deleted comment"), 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"]
        )
Beispiel #11
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 = 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)

        # 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 = 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)
        elif auth_code:
            return page_not_authorized(req, "../", \
                                       text = auth_msg,
                                       ln=argd['ln'])

        # Check that comment is not currently deleted
        if is_comment_deleted(argd['comid']):
            return page_not_authorized(req, "../", \
                                       text = _("You cannot access files of a deleted comment"),
                                       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'])