def quick_upload_file(self):
        context = aq_inner(self.context)
        request = self.request
        response = request.RESPONSE

        response.setHeader('Expires', 'Sat, 1 Jan 2000 00:00:00 GMT')
        response.setHeader('Cache-control', 'no-cache')
        # the good content type woul be text/json or text/plain but IE
        # do not support it
        response.setHeader('Content-Type', 'text/html; charset=utf-8')
        # disable diazo themes
        request.response.setHeader('X-Theme-Disabled', 'True')

        if request.HTTP_X_REQUESTED_WITH:
            # using ajax upload
            file_name = urllib.unquote(request.HTTP_X_FILE_NAME)
            upload_with = "XHR"
            try:
                file = request.BODYFILE
                file_data = file.read()
                file.seek(0)
            except AttributeError:
                # in case of cancel during xhr upload
                logger.error("Upload of %s has been aborted", file_name)
                # not really useful here since the upload block
                # is removed by "cancel" action, but
                # could be useful if someone change the js behavior
                return json.dumps({u'error': u'emptyError'})
            except:
                logger.error(
                    "Error when trying to read the file %s in request",
                    file_name
                )
                return json.dumps({u'error': u'serverError'})
        else:
            # using classic form post method (MSIE<=8)
            file = request.get("qqfile", None)
            file_data = file.read()
            file.seek(0)
            filename = getattr(file, 'filename', '')
            file_name = filename.split("\\")[-1]
            try:
                file_name = file_name.decode('utf-8')
            except UnicodeDecodeError:
                pass

            file_name = IUserPreferredFileNameNormalizer(
                self.request
            ).normalize(file_name)
            upload_with = "CLASSIC FORM POST"
            # we must test the file size in this case (no client test)
            if not self._check_file_size(file_data):
                logger.info("Test file size: the file %s is too big, upload "
                            "rejected" % filename)
                return json.dumps({u'error': u'sizeError'})

        # overwrite file
        try:
            newid = get_id_from_filename(file_name, context)
        except MissingExtension:
            return json.dumps({u'error': u'missingExtension'})

        if newid in context or file_name in context:
            updated_object = context.get(newid, False) or context[file_name]
            mtool = getToolByName(context, 'portal_membership')
            override_setting = self.qup_prefs.object_override
            if override_setting and\
                    mtool.checkPermission(ModifyPortalContent, updated_object):
                can_overwrite = True
            else:
                can_overwrite = False

            if not can_overwrite:
                logger.debug(
                    "The file id for %s already exists, upload rejected"
                    % file_name
                )
                return json.dumps({u'error': u'serverErrorAlreadyExists'})

            overwritten_file = updated_object
        else:
            overwritten_file = None

        content_type = get_content_type(context, file_data, file_name)

        portal_type = getDataFromAllRequests(request, 'typeupload') or ''
        title = getDataFromAllRequests(request, 'title') or ''
        description = getDataFromAllRequests(request, 'description') or ''

        if not portal_type:
            ctr = getToolByName(context, 'content_type_registry')
            portal_type = ctr.findTypeName(
                file_name.lower(), content_type, ''
            ) or 'File'

        if file_data:
            if overwritten_file is not None:
                updater = IQuickUploadFileUpdater(context)
                logger.info(
                    "reuploading %s file with %s: title=%s, description=%s, "
                    "content_type=%s"
                    % (overwritten_file.absolute_url(), upload_with, title,
                       description, content_type))
                try:
                    f = updater(overwritten_file, file_name, title,
                                description, content_type, file_data)
                except Exception, e:
                    logger.error(
                        "Error updating %s file: %s", file_name, str(e)
                    )
                    return json.dumps({u'error': u'serverError'})

            else:
                factory = IQuickUploadFileFactory(context)
                logger.info(
                    "uploading file with %s: filename=%s, title=%s, "
                    "description=%s, content_type=%s, portal_type=%s"
                    % (upload_with, file_name, title,
                       description, content_type, portal_type))
                try:
                    f = factory(file_name, title, description, content_type,
                                file_data, portal_type)
                except Exception, e:
                    logger.error(
                        "Error creating %s file: %s", file_name, str(e)
                    )
                    return json.dumps({u'error': u'serverError'})
Пример #2
0
    def quick_upload_file(self) :
        context = aq_inner(self.context)
        request = self.request
        response = request.RESPONSE

        response.setHeader('Expires', 'Sat, 1 Jan 2000 00:00:00 GMT')
        response.setHeader('Cache-control', 'no-cache')
        # the good content type woul be text/json or text/plain but IE
        # do not support it
        response.setHeader('Content-Type', 'text/html; charset=utf-8')
        # disable diazo themes
        request.response.setHeader('X-Theme-Disabled', 'True')

        if request.HTTP_X_REQUESTED_WITH :
            # using ajax upload
            file_name = urllib.unquote(request.HTTP_X_FILE_NAME)
            upload_with = "XHR"
            try :
                file = request.BODYFILE
                file_data = file.read()
                file.seek(0)
            except AttributeError :
                # in case of cancel during xhr upload
                logger.error("Upload of %s has been aborted", file_name)
                # not really useful here since the upload block
                # is removed by "cancel" action, but
                # could be useful if someone change the js behavior
                return  json.dumps({u'error': u'emptyError'})
            except :
                logger.error("Error when trying to read the file %s in request", file_name)
                return json.dumps({u'error': u'serverError'})
        else :
            # using classic form post method (MSIE<=8)
            file_data = request.get("qqfile", None)
            filename = getattr(file_data,'filename', '')
            file_name = filename.split("\\")[-1]
            try:
                file_name = file_name.decode('utf-8')
            except UnicodeDecodeError:
                pass

            file_name = IUserPreferredFileNameNormalizer(self.request
                            ).normalize(file_name)
            upload_with = "CLASSIC FORM POST"
            # we must test the file size in this case (no client test)
            if not self._check_file_size(file_data) :
                logger.info("Test file size : the file %s is too big, upload rejected" % filename)
                return json.dumps({u'error': u'sizeError'})

        # overwrite file
        try:
            newid = get_id_from_filename(file_name, context)
        except MissingExtension:
            return json.dumps({u'error': u'missingExtension'})

        if newid in context or file_name in context:
            updated_object = context.get(newid, False) or context[file_name]
            mtool = getToolByName(context, 'portal_membership')
            if mtool.checkPermission(ModifyPortalContent, updated_object):
                can_overwrite = True
            else:
                can_overwrite = False

            if not can_overwrite:
                logger.debug("The file id for %s already exists, upload rejected" % file_name)
                return json.dumps({u'error': u'serverErrorAlreadyExists'})

            overwritten_file = updated_object
        else:
            overwritten_file = None

        content_type = mimetypes.guess_type(file_name)[0]
        # sometimes plone mimetypes registry could be more powerful
        if not content_type :
            mtr = getToolByName(context, 'mimetypes_registry')
            oct = mtr.globFilename(file_name)
            if oct is not None :
                content_type = str(oct)
        
        portal_type = getDataFromAllRequests(request, 'typeupload') or ''
        title =  getDataFromAllRequests(request, 'title') or ''
        description =  getDataFromAllRequests(request, 'description') or ''

        if not portal_type :
            ctr = getToolByName(context, 'content_type_registry')
            portal_type = ctr.findTypeName(file_name.lower(), content_type, '') or 'File'

        if file_data:
            if overwritten_file is not None:
                updater = IQuickUploadFileUpdater(context)
                logger.info("reuploading %s file with %s : title=%s, description=%s, content_type=%s" % \
                        (overwritten_file.absolute_url(), upload_with, title, description, content_type))
                try :
                    f = updater(overwritten_file, file_name, title,
                                description, content_type, file_data)
                except Exception, e:
                    logger.error("Error updating %s file : %s", file_name, str(e))
                    return json.dumps({u'error': u'serverError'})

            else:
                factory = IQuickUploadFileFactory(context)
                logger.info("uploading file with %s : filename=%s, title=%s, description=%s, content_type=%s, portal_type=%s" % \
                        (upload_with, file_name, title, description, content_type, portal_type))
                try :
                    f = factory(file_name, title, description, content_type, file_data, portal_type)
                except Exception, e:
                    logger.error("Error creating %s file : %s", file_name, str(e))
                    return json.dumps({u'error': u'serverError'})
Пример #3
0
    def quick_upload_file(self) :
        context = aq_inner(self.context)
        request = self.request
        response = request.RESPONSE

        response.setHeader('Expires', 'Sat, 1 Jan 2000 00:00:00 GMT')
        response.setHeader('Cache-control', 'no-cache')
        # the good content type woul be text/json or text/plain but IE
        # do not support it
        response.setHeader('Content-Type', 'text/html; charset=utf-8')
        # disable diazo themes
        request.response.setHeader('X-Theme-Disabled', 'True')

        if request.HTTP_X_REQUESTED_WITH :
            # using ajax upload
            file_name = urllib.unquote(request.HTTP_X_FILE_NAME)
            upload_with = "XHR"
            try :
                file = request.BODYFILE
                file_data = file.read()
                file.seek(0)
            except AttributeError :
                # in case of cancel during xhr upload
                logger.error("Upload of %s has been aborted", file_name)
                # not really useful here since the upload block
                # is removed by "cancel" action, but
                # could be useful if someone change the js behavior
                return  json.dumps({u'error': u'emptyError'})
            except :
                logger.error("Error when trying to read the file %s in request", file_name)
                return json.dumps({u'error': u'serverError'})
        else :
            # using classic form post method (MSIE<=8)
            file_data = request.get("qqfile", None)
            filename = getattr(file_data,'filename', '')
            file_name = filename.split("\\")[-1]
            file_name = IUserPreferredFileNameNormalizer(self.request
                            ).normalize(file_name)
            upload_with = "CLASSIC FORM POST"
            # we must test the file size in this case (no client test)
            if not self._check_file_size(file_data) :
                logger.info("Test file size : the file %s is too big, upload rejected" % filename)
                return json.dumps({u'error': u'sizeError'})

        if not self._check_file_id(file_name) or file_name in context:
            logger.debug("The file id for %s already exists, upload rejected" % file_name)
            return json.dumps({u'error': u'serverErrorAlreadyExists'})

        content_type = mimetypes.guess_type(file_name)[0]
        # sometimes plone mimetypes registry could be more powerful
        if not content_type :
            mtr = getToolByName(context, 'mimetypes_registry')
            oct = mtr.globFilename(file_name)
            if oct is not None :
                content_type = str(oct)

        portal_type = getDataFromAllRequests(request, 'typeupload') or ''
        title =  getDataFromAllRequests(request, 'title') or ''
        description =  getDataFromAllRequests(request, 'description') or ''

        if not portal_type :
            ctr = getToolByName(context, 'content_type_registry')
            portal_type = ctr.findTypeName(file_name.lower(), content_type, '') or 'File'

        if file_data:
            factory = IQuickUploadFileFactory(context)
            logger.info("uploading file with %s : filename=%s, title=%s, description=%s, content_type=%s, portal_type=%s" % \
                    (upload_with, file_name, title, description, content_type, portal_type))

            try :
                f = factory(file_name, title, description, content_type, file_data, portal_type)
            except Exception, e:
                logger.error("Error creating %s file : %s", file_name, str(e))
                return json.dumps({u'error': u'serverError'})

            if f['success'] is not None :
                o = f['success']
                logger.info("file url: %s" % o.absolute_url())
                msg = {
                    u'success': True,
                    u'uid': o.UID(),
                    u'name': o.getId(),
                    u'title': o.pretty_title_or_id()
                }
            else :
                msg = {u'error': f['error']}
    def quick_upload_file(self):
        context = aq_inner(self.context)
        request = self.request
        response = request.RESPONSE

        response.setHeader('Expires', 'Sat, 1 Jan 2000 00:00:00 GMT')
        response.setHeader('Cache-control', 'no-cache')
        # application/json is not supported by old IEs but text/html fails in
        # every browser with plone.protect 3.0.11
        response.setHeader('Content-Type', 'application/json; charset=utf-8')
        # disable diazo themes and csrf protection
        request.response.setHeader('X-Theme-Disabled', 'True')

        if request.HTTP_X_REQUESTED_WITH:
            # using ajax upload
            file_name = urllib.unquote(request.HTTP_X_FILE_NAME)
            upload_with = "XHR"
            try:
                file = request.BODYFILE
                file_data = file.read()
                file.seek(0)
            except AttributeError:
                # in case of cancel during xhr upload
                logger.error("Upload of %s has been aborted", file_name)
                # not really useful here since the upload block
                # is removed by "cancel" action, but
                # could be useful if someone change the js behavior
                return json.dumps({u'error': u'emptyError'})
            except:
                logger.error(
                    "Error when trying to read the file %s in request",
                    file_name)
                return self._error_response(u'serverError')
        else:
            # using classic form post method (MSIE<=8)
            file = request.get("qqfile", None)
            file_data = file.read()
            file.seek(0)
            filename = getattr(file, 'filename', '')
            file_name = filename.split("\\")[-1]
            try:
                file_name = file_name.decode('utf-8')
            except UnicodeDecodeError:
                pass

            file_name = IUserPreferredFileNameNormalizer(
                self.request).normalize(file_name)
            upload_with = "CLASSIC FORM POST"
            # we must test the file size in this case (no client test)
            if not self._check_file_size(file):
                logger.info("Test file size: the file %s is too big, upload "
                            "rejected" % filename)
                return self._error_response(u'sizeError')

        # overwrite file
        try:
            newid = get_id_from_filename(
                file_name, context, unique=self.qup_prefs.object_unique_id)
        except MissingExtension:
            return self._error_response(u'missingExtension')

        if (newid in context or file_name in context) and \
                not self.qup_prefs.object_unique_id:
            updated_object = context.get(newid, False) or context[file_name]
            mtool = getToolByName(context, 'portal_membership')
            override_setting = self.qup_prefs.object_override
            if override_setting and\
                    mtool.checkPermission(ModifyPortalContent, updated_object):
                can_overwrite = True
            else:
                can_overwrite = False

            if not can_overwrite:
                logger.debug(
                    "The file id for %s already exists, upload rejected" %
                    file_name)
                return self._error_response(u'serverErrorAlreadyExists')

            overwritten_file = updated_object
        else:
            overwritten_file = None

        content_type = get_content_type(context, file_data, file_name)

        portal_type = getDataFromAllRequests(request, 'typeupload') or ''
        title = getDataFromAllRequests(request, 'title') or ''
        description = getDataFromAllRequests(request, 'description') or ''
        if not title.strip() and self.qup_prefs.id_as_title:
            title = newid

        if not portal_type:
            ctr = getToolByName(context, 'content_type_registry')
            portal_type = ctr.findTypeName(file_name.lower(), content_type,
                                           '') or 'File'

        if not file_data:
            return self._error_response(u'emptyError')

        if overwritten_file is not None:
            updater = IQuickUploadFileUpdater(context)
            logger.info(
                "reuploading %s file with %s: title=%s, description=%s, "
                "content_type=%s" %
                (overwritten_file.absolute_url(), upload_with, title,
                 description, content_type))
            try:
                f = updater(overwritten_file, file_name, title, description,
                            content_type, file_data)
            except ConflictError:
                # Allow Zope to retry up to three times, and if that still
                # fails, handle ConflictErrors on client side if necessary
                raise
            except Exception as e:
                logger.error("Error updating %s file: %s", file_name, str(e))
                return self._error_response(u'serverError')

        else:
            factory = IQuickUploadFileFactory(context)
            logger.info("uploading file with %s: filename=%s, title=%s, "
                        "description=%s, content_type=%s, portal_type=%s" %
                        (upload_with, file_name, title, description,
                         content_type, portal_type))
            try:
                f = factory(file_name, title, description, content_type,
                            file_data, portal_type)
            except ConflictError:
                # Allow Zope to retry up to three times, and if that still
                # fails, handle ConflictErrors on client side if necessary
                raise
            except Exception as e:
                logger.error("Error creating %s file: %s", file_name, str(e))
                return self._error_response(u'serverError')

        if f['success'] is None:
            return self._error_response(f['error'])

        obj = f['success']
        logger.info("file url: %s" % obj.absolute_url())
        return self._success_response(obj)
    def quick_upload_file(self):
        context = aq_inner(self.context)
        request = self.request
        response = request.RESPONSE

        response.setHeader('Expires', 'Sat, 1 Jan 2000 00:00:00 GMT')
        response.setHeader('Cache-control', 'no-cache')
        # application/json is not supported by old IEs but text/html fails in
        # every browser with plone.protect 3.0.11
        response.setHeader('Content-Type', 'application/json; charset=utf-8')
        # disable diazo themes and csrf protection
        request.response.setHeader('X-Theme-Disabled', 'True')

        if request.HTTP_X_REQUESTED_WITH:
            # using ajax upload
            file_name = urllib.unquote(request.HTTP_X_FILE_NAME)
            upload_with = "XHR"
            try:
                file = request.BODYFILE
                file_data = file.read()
                file.seek(0)
            except AttributeError:
                # in case of cancel during xhr upload
                logger.error("Upload of %s has been aborted", file_name)
                # not really useful here since the upload block
                # is removed by "cancel" action, but
                # could be useful if someone change the js behavior
                return json.dumps({u'error': u'emptyError'})
            except:
                logger.error(
                    "Error when trying to read the file %s in request",
                    file_name
                )
                return json.dumps({u'error': u'serverError'})
        else:
            # using classic form post method (MSIE<=8)
            file = request.get("qqfile", None)
            file_data = file.read()
            file.seek(0)
            filename = getattr(file, 'filename', '')
            file_name = filename.split("\\")[-1]
            try:
                file_name = file_name.decode('utf-8')
            except UnicodeDecodeError:
                pass

            file_name = IUserPreferredFileNameNormalizer(
                self.request
            ).normalize(file_name)
            upload_with = "CLASSIC FORM POST"
            # we must test the file size in this case (no client test)
            if not self._check_file_size(file):
                logger.info("Test file size: the file %s is too big, upload "
                            "rejected" % filename)
                return json.dumps({u'error': u'sizeError'})

        # overwrite file
        try:
            newid = get_id_from_filename(
                file_name, context, unique=self.qup_prefs.object_unique_id)
        except MissingExtension:
            return json.dumps({u'error': u'missingExtension'})

        if (newid in context or file_name in context) and \
                not self.qup_prefs.object_unique_id:
            updated_object = context.get(newid, False) or context[file_name]
            mtool = getToolByName(context, 'portal_membership')
            override_setting = self.qup_prefs.object_override
            if override_setting and\
                    mtool.checkPermission(ModifyPortalContent, updated_object):
                can_overwrite = True
            else:
                can_overwrite = False

            if not can_overwrite:
                logger.debug(
                    "The file id for %s already exists, upload rejected"
                    % file_name
                )
                return json.dumps({u'error': u'serverErrorAlreadyExists'})

            overwritten_file = updated_object
        else:
            overwritten_file = None

        content_type = get_content_type(context, file_data, file_name)

        portal_type = getDataFromAllRequests(request, 'typeupload') or ''
        title = getDataFromAllRequests(request, 'title') or ''
        description = getDataFromAllRequests(request, 'description') or ''
        if not title.strip() and self.qup_prefs.id_as_title:
            title = newid

        if not portal_type:
            ctr = getToolByName(context, 'content_type_registry')
            portal_type = ctr.findTypeName(
                file_name.lower(), content_type, ''
            ) or 'File'

        if file_data:
            if overwritten_file is not None:
                updater = IQuickUploadFileUpdater(context)
                logger.info(
                    "reuploading %s file with %s: title=%s, description=%s, "
                    "content_type=%s"
                    % (overwritten_file.absolute_url(), upload_with, title,
                       description, content_type))
                try:
                    f = updater(overwritten_file, file_name, title,
                                description, content_type, file_data)
                except ConflictError:
                    # Allow Zope to retry up to three times, and if that still
                    # fails, handle ConflictErrors on client side if necessary
                    raise
                except Exception as e:
                    logger.error(
                        "Error updating %s file: %s", file_name, str(e)
                    )
                    return json.dumps({u'error': u'serverError'})

            else:
                factory = IQuickUploadFileFactory(context)
                logger.info(
                    "uploading file with %s: filename=%s, title=%s, "
                    "description=%s, content_type=%s, portal_type=%s"
                    % (upload_with, file_name, title,
                       description, content_type, portal_type))
                try:
                    f = factory(file_name, title, description, content_type,
                                file_data, portal_type)
                except ConflictError:
                    # Allow Zope to retry up to three times, and if that still
                    # fails, handle ConflictErrors on client side if necessary
                    raise
                except Exception as e:
                    logger.error(
                        "Error creating %s file: %s", file_name, str(e)
                    )
                    return json.dumps({u'error': u'serverError'})

            if f['success'] is not None:
                o = f['success']
                logger.info("file url: %s" % o.absolute_url())
                if HAS_UUID:
                    uid = IUUID(o)
                else:
                    uid = o.UID()

                msg = {
                    u'success': True,
                    u'uid': uid,
                    u'name': o.getId(),
                    u'title': o.pretty_title_or_id()
                }
            else:
                msg = {u'error': f['error']}
        else:
            msg = {u'error': u'emptyError'}

        return json.dumps(msg)