def set(self, data, filename, content_type): """ Set """ error = '' obj = self.context primaryField = obj.getPrimaryField() if primaryField is not None: mutator = primaryField.getMutator(obj) # mimetype arg works with blob files mutator(data, content_type=content_type, mimetype=content_type) if not obj.getFilename(): obj.setFilename(filename) #patch: #check if setFilename worked, # if not we set the filename on the blob if not obj.getFilename(): field = obj.getPrimaryField() if field: blob = field.getUnwrapped(obj) if blob is not None: if shasattr(blob, 'setFilename'): blob.setFilename(filename) #end of patch obj.reindexObject() else: # some products remove the 'primary' attribute # on ATFile or ATImage (which is very bad) error = 'serverError' logger.info( "An error happens : impossible to get the primary field" " for file %s, rawdata can't be created", obj.absolute_url()) return error
def __call__(self, filename, title, description, content_type, data, portal_type): context = aq_inner(self.context) error = '' result = {} result['success'] = None newid = get_id_from_filename(filename, context) chooser = INameChooser(context) newid = chooser.chooseName(newid, context) # consolidation because it's different upon Plone versions if not title: # try to split filenames because we don't want # big titles without spaces title = filename.rsplit('.', 1)[0]\ .replace('_', ' ')\ .replace('-', ' ') if newid in context: # only here for flashupload method since a check_id is done # in standard uploader - see also XXX in quick_upload.py raise NameError, 'Object id %s already exists' % newid else: upload_lock.acquire() try: transaction.begin() try: from zope.publisher.browser import TestRequest request = TestRequest() dataobj = FileObj(data) dataobj.filename = filename request.form['doc'] = dataobj request.form['ajax'] = '1' from fhnw.office2plone.browser.docx_importer import DocxImporter docximport = DocxImporter(self.context, request) docximport.docx_import() except ImportError: error = '' except Unauthorized: error = u'serverErrorNoPermission' except ConflictError: # rare with xhr upload / happens sometimes with flashupload error = u'serverErrorZODBConflict' except ValueError: error = u'serverErrorDisallowedType' except Exception, e: error = u'serverError' logger.exception(e) if error: if error == u'serverError': logger.info( "An error happens with setId from filename, " "the file has been created with a bad id, " "can't find %s", newid) else: pass #@TODO : rollback if there has been an error transaction.commit() finally:
def flash_upload_file(self) : context = aq_inner(self.context) request = self.request self._auth_with_ticket() file_name = request.form.get("Filename", "") file_data = request.form.get("Filedata", None) content_type = mimetypes.guess_type(file_name)[0] portal_type = request.form.get('typeupload', '') title = request.form.get("title", None) description = request.form.get("description", None) 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.debug("Uploading file with flash: filename=%s, title=%s, " "description=%s, content_type=%s, portal_type=%s" % ( file_name, title, description, content_type, portal_type) ) try : f = factory(file_name, title, description, content_type, file_data, portal_type) except : # XXX todo : improve errors handlers for flashupload raise if f['success'] is not None : o = f['success'] logger.info("file url: %s" % o.absolute_url()) SecurityManagement.setSecurityManager(self.old_sm) return o.absolute_url()
def set(self, data, filename, content_type): """ Set """ error = '' obj = self.context primaryField = obj.getPrimaryField() if primaryField is not None: mutator = primaryField.getMutator(obj) # mimetype arg works with blob files mutator(data, content_type=content_type, mimetype=content_type) if not obj.getFilename(): obj.setFilename(filename) #patch: #check if setFilename worked, # if not we set the filename on the blob if not obj.getFilename(): field = obj.getPrimaryField() if field: blob = field.getUnwrapped(obj) if blob is not None: if shasattr(blob, 'setFilename'): blob.setFilename(filename) #end of patch obj.reindexObject() else: # some products remove the 'primary' attribute # on ATFile or ATImage (which is very bad) error = 'serverError' logger.info("An error happens : impossible to get the primary field" " for file %s, rawdata can't be created", obj.absolute_url()) return error
def __call__(self, filename, title, description, content_type, data, portal_type): context = aq_inner(self.context) error = '' result = {} result['success'] = None newid = get_id_from_filename(filename, context) chooser = INameChooser(context) newid = chooser.chooseName(newid, context) # consolidation because it's different upon Plone versions if not title : # try to split filenames because we don't want # big titles without spaces title = filename.rsplit('.', 1)[0].replace('_',' ').replace('-',' ') if newid in context: # only here for flashupload method since a check_id is done # in standard uploader - see also XXX in quick_upload.py raise NameError, 'Object id %s already exists' %newid else : upload_lock.acquire() try: transaction.begin() try: context.invokeFactory(type_name=portal_type, id=newid, title=title, description=description) except Unauthorized : error = u'serverErrorNoPermission' except ConflictError : # rare with xhr upload / happens sometimes with flashupload error = u'serverErrorZODBConflict' except ValueError: error = u'serverErrorDisallowedType' except Exception, e: error = u'serverError' logger.exception(e) if error: if error == u'serverError': logger.info("An error happens with setId from filename, " "the file has been created with a bad id, " "can't find %s", newid) else: obj = getattr(context, newid) if obj: error = IQuickUploadFileSetter(obj).set(data, filename, content_type) obj._at_rename_after_creation = False try: obj.processForm() except AttributeError: pass del obj._at_rename_after_creation #@TODO : rollback if there has been an error transaction.commit() finally:
def set(self, data, filename, content_type): error = '' obj = self.context ttool = getToolByName(obj, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [ field for name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] if len(file_fields) == 0: error = u'serverError' logger.info( "An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(field): value = NamedBlobImage( data=data, contentType=content_type, filename=unicode(filename)) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile( data=data, contentType=content_type, filename=unicode(filename)) elif INamedImageField.providedBy(file_field): value = NamedImage( data=data, contentType=content_type, filename=unicode(file_field)) elif INamedFileField.providedBy(file_field): value = NamedFile( data=data, contentType=content_type, filename=unicode(filename)) file_field.set(obj, value) obj.reindexObject() notify(ObjectInitializedEvent(obj)) return error
def __call__(self, filename, title, description, content_type, data, portal_type): context = aq_inner(self.context) charset = context.getCharset() name = filename.decode(charset) error = '' result = {} result['success'] = None normalizer = component.getUtility(IIDNormalizer) chooser = INameChooser(self.context) # normalize all filename but dots normalized = ".".join([normalizer.normalize(n) for n in name.split('.')]) newid = chooser.chooseName(normalized, context) # consolidation because it's different upon Plone versions newid = newid.replace('_','-').replace(' ','-').lower() if not title : # try to split filenames because we don't want # big titles without spaces title = name.split('.')[0].replace('_',' ').replace('-',' ') if newid in context.objectIds() : # only here for flashupload method since a check_id is done # in standard uploader - see also XXX in quick_upload.py raise NameError, 'Object id %s already exists' %newid else : upload_lock.acquire() try: transaction.begin() try: context.invokeFactory(type_name=portal_type, id=newid, title=title, description=description) except Unauthorized : error = u'serverErrorNoPermission' except ConflictError : # rare with xhr upload / happens sometimes with flashupload error = u'serverErrorZODBConflict' except Exception, e: error = u'serverError' logger.exception(e) if error: error = u'serverError' logger.info("An error happens with setId from filename, " "the file has been created with a bad id, " "can't find %s", newid) else: obj = getattr(context, newid) if obj: error = IQuickUploadFileSetter(obj).set(data, filename, content_type) #@TODO : rollback if there has been an error transaction.commit() finally:
def set(self, data, filename, content_type): error = '' obj = self.context ttool = getToolByName(obj, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [ field for name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] if len(file_fields) == 0: error = u'serverError' logger.info( "An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(file_field): value = NamedBlobImage(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif INamedImageField.providedBy(file_field): value = NamedImage(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif INamedFileField.providedBy(file_field): value = NamedFile(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) file_field.set(obj, value) return error
def set(self, data, filename, content_type): error = '' obj = self.context primaryField = obj.getPrimaryField() if primaryField is not None: mutator = primaryField.getMutator(obj) # mimetype arg works with blob files mutator(data, content_type=content_type, mimetype=content_type) if not obj.getFilename(): obj.setFilename(filename) obj.reindexObject() else: # some products remove the 'primary' attribute on ATFile or ATImage (which is very bad) error = u'serverError' logger.info( "An error happens : impossible to get the primary field " "for file %s, rawdata can't be created", obj.absolute_url()) return error
def set(self, data, filename, content_type): error = '' obj = self.context primaryField = obj.getPrimaryField() if primaryField is not None: mutator = primaryField.getMutator(obj) # mimetype arg works with blob files mutator(data, content_type=content_type, mimetype=content_type) if not obj.getFilename() : obj.setFilename(filename) obj.reindexObject() else : # some products remove the 'primary' attribute on ATFile or ATImage (which is very bad) error = u'serverError' logger.info("An error happens : impossible to get the primary field " "for file %s, rawdata can't be created", obj.absolute_url()) return error
def _auth_with_ticket(self): """ with flashupload authentication is done using a ticket """ context = aq_inner(self.context) request = self.request url = context.absolute_url() ticket = getDataFromAllRequests(request, 'ticket') if ticket is None: raise Unauthorized('No ticket specified') logger.info('Authenticate using ticket, the ticket is "%s"' % str(ticket)) username = ticketmod.ticketOwner(url, ticket) if username is None: logger.info('Ticket "%s" was invalidated, cannot be used ' 'any more.' % str(ticket)) raise Unauthorized('Ticket is not valid') self.old_sm = SecurityManagement.getSecurityManager() user = find_user(context, username) SecurityManagement.newSecurityManager(self.request, user) logger.info('Switched to user "%s"' % username)
def _auth_with_ticket(self): """ with flashupload authentication is done using a ticket """ context = aq_inner(self.context) request = self.request url = context.absolute_url() ticket = getDataFromAllRequests(request, "ticket") if ticket is None: raise Unauthorized("No ticket specified") logger.info('Authenticate using ticket, the ticket is "%s"' % str(ticket)) username = ticketmod.ticketOwner(url, ticket) if username is None: logger.info('Ticket "%s" was invalidated, cannot be used ' "any more." % str(ticket)) raise Unauthorized("Ticket is not valid") self.old_sm = SecurityManagement.getSecurityManager() user = find_user(context, username) SecurityManagement.newSecurityManager(self.request, user) logger.info('Switched to user "%s"' % username)
def __call__( self, filename, title, description, content_type, data, portal_type): context = aq_inner(self.context) error = '' result = {} result['success'] = None charset = context.getCharset() name = filename.decode(charset) name, ext = name.rsplit('.', 1) # check the given portal type with the # qu addable types from the registry registry = getUtility(IRegistry) upload_addable = registry.get( 'ftw.tabbedview.interfaces.ITabbedView.quickupload_addable_types') if portal_type not in upload_addable and upload_addable: portal_type = upload_addable[0] newid = generate_id(name, self.context) title = name # copied from collective.quickupload upload_lock.acquire() try: transaction.begin() try: context.invokeFactory( type_name=portal_type, id=newid, title=title, description=description) except Unauthorized: error = u'serverErrorNoPermission' except ConflictError: # rare with xhr upload / happens sometimes with flashupload error = u'serverErrorZODBConflict' except Exception, e: error = u'serverError' logger.exception(e) if error: error = u'serverError' logger.info("An error happens with setId from filename, " "the file has been created with a bad id, " "can't find %s", newid) else: obj = getattr(context, newid) if obj: error = IQuickUploadFileSetter(obj).set( data, filename, content_type) if base_hasattr(obj, 'processForm'): # AT: includes reindexing the object. obj.processForm() else: # Dexterity obj.reindexObject() #@TODO : rollback if there has been an error transaction.commit()
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'})
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'})
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)
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)
class QuickUploadFile(QuickUploadAuthenticate): """ Upload a file """ def __call__(self): """ """ if self.use_flashupload: return self.flash_upload_file() return self.quick_upload_file() def flash_upload_file(self): context = aq_inner(self.context) request = self.request self._auth_with_ticket() file_name = request.form.get("Filename", "") file_data = request.form.get("Filedata", None) content_type = get_content_type(context, file_data, file_name) portal_type = request.form.get('typeupload', '') title = request.form.get("title", None) description = request.form.get("description", None) 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.debug( "Uploading file with flash: filename=%s, title=%s, " "description=%s, content_type=%s, portal_type=%s" % (file_name, title, description, content_type, portal_type)) try: f = factory(file_name, title, description, content_type, file_data, portal_type) except: raise if f['success'] is not None: o = f['success'] logger.info("file url: %s" % o.absolute_url()) SecurityManagement.setSecurityManager(self.old_sm) return o.absolute_url() 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') response.setHeader('Content-Type', 'application/json; 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): 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'}) 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']}
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']}