class LimitFileSizeEditForm(controlpanel.RegistryEditForm): """Media settings form. """ schema = ILimitFileSizePanel id = "LimitFileSizeEditForm" label = _(u"Limit file size settings") description = _(u"help_limit_file_size_panel", default=u"Set file size for file and image") @button.buttonAndHandler(_('Save'), name='save') def handleSave(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return changes = self.applyChanges(data) IStatusMessage(self.request).addStatusMessage(_(u"Changes saved"), "info") self.context.REQUEST.RESPONSE.redirect("@@limitfilesize-settings") @button.buttonAndHandler(_('Cancel'), name='cancel') def handleCancel(self, action): IStatusMessage(self.request).addStatusMessage(_(u"Edit cancelled"), "info") self.request.response.redirect( "%s/%s" % (self.context.absolute_url(), self.control_panel_view)) def updateWidgets(self): super(LimitFileSizeEditForm, self).updateWidgets() self.widgets['file_size'].maxlength = 5 self.widgets['file_size'].size = 5 self.widgets['image_size'].maxlength = 5 self.widgets['image_size'].size = 5
def patched__call__(self, value, *args, **kwargs): context = kwargs.get('instance', None) try: helper_view = api.content.get_view( name='lfsp_helpers_view', context=context, request=context.REQUEST, ) except InvalidParameterError: # the view is enabled only when the product is installed return if helper_view.canBypassValidation(): return True maxsize = helper_view.get_maxsize(self, **kwargs) if not maxsize: return self._old___call__(value, *args, **kwargs) size_check = helper_view.check_size(maxsize=maxsize, uploadfile=value) if size_check and not size_check.get('valid', False): msg = _( 'validation_error', default= u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)", # NOQA mapping={ 'size': safe_unicode("%.1f" % size_check.get('sizeMB')), 'max': safe_unicode("%.1f" % size_check.get('maxsize')) }) return recursiveTranslate(msg, **kwargs) return True
def patched__call__(self, value, *args, **kwargs): context = kwargs.get('instance', None) try: helper_view = api.content.get_view( name='lfsp_helpers_view', context=context, request=context.REQUEST, ) except InvalidParameterError: # the view is enabled only when the product is installed return if helper_view.canBypassValidation(): return True maxsize = helper_view.get_maxsize(self, **kwargs) if not maxsize: return self._old___call__(value, *args, **kwargs) size_check = helper_view.check_size( maxsize=maxsize, uploadfile=value) if size_check and not size_check.get('valid', False): msg = _('validation_error', default=u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)", # NOQA mapping={ 'size': safe_unicode("%.1f" % size_check.get('sizeMB')), 'max': safe_unicode("%.1f" % size_check.get('maxsize')) }) return recursiveTranslate(msg, **kwargs) return True
def check_size_dx(self, uploadfile, maxsize): """ check the size of given file """ result = { 'maxsize': maxsize, 'valid': True } if self.canBypassValidation(): return result if (isinstance(uploadfile, FileUpload) or hasattr(aq_base(uploadfile), 'tell')): # NOQA uploadfile.seek(0, 2) # eof size = float(uploadfile.tell()) uploadfile.seek(0) else: size = float(uploadfile.getSize()) sizeMB = (size / (1024 * 1024)) result['sizeMB'] = sizeMB if sizeMB > maxsize: result['valid'] = False msg = _( 'validation_error', default=u'Validation failed. Uploaded data is too large:' u' ${size}MB (max ${max}MB)', mapping={ 'size': safe_unicode('{0:.1f}'.format(sizeMB)), 'max': safe_unicode('{0:.1f}'.format(maxsize)) }) result['error'] = translate(msg, context=self.request) return result
def handleSave(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return changes = self.applyChanges(data) IStatusMessage(self.request).addStatusMessage(_(u"Changes saved"), "info") self.context.REQUEST.RESPONSE.redirect("@@limitfilesize-settings")
def handleSave(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return changes = self.applyChanges(data) IStatusMessage(self.request).addStatusMessage(_(u"Changes saved"), "info") self.context.REQUEST.RESPONSE.redirect("@@limitfilesize-settings")
class ILimitFileSizePanel(Interface): """ Settings used in the control panel """ file_size = schema.Int( title=_(u"Set the file-type size limit"), description=_( u"Type here a number in MB which will limit the file size upload"), default=30, ) image_size = schema.Int( title=_(u"Set the image-type size limit"), description=_( u"Type here a number in MB which will" u" limit the image size upload"), default=10, ) types_settings = schema.Tuple( title=_(u'Settings for other content types and fields'), description=_( 'help_types_settings', default=u"Use this section to provide size overrides of" u" values above.\nProvide a content type/field ID," u" and the size limit."), value_type=PersistentObject( ITypesSettings, title=_(u"Content/field settings")), required=False, default=(), missing_value=(), ) new_data_only = schema.Bool( title=_(u"Validate only new data"), description=_( "help_new_data_only", default=u"Keep selected to validate only new uploaded files and" u" images.\nIf you unselect this and the size " u"configurations above will be lowered, is possible that" u" users that edit contents wont be able to save the form " u"because the validator will check also data already" u" saved."), default=True, )
class ILimitFileSizePanel(Interface): """ Settings used in the control panel """ file_size = schema.Int( title=_(u"Set the file-type size limit"), description=_( u"Type here a number in MB which will limit the file size upload"), default=30, ) image_size = schema.Int( title=_(u"Set the image-type size limit"), description=_( u"Type here a number in MB which will limit the image size upload" ), default=10, ) new_data_only = schema.Bool( title=_(u"Validate only new data"), description= _("help_new_data_only", default= u"Keep selected to validate only new uploaded files and images.\n" u"If you unselect this and the size configurations above will be lowered, " u"is possible that users that edit contents wont be able to save the form " u"because the validator will check also data already saved."), default=True, )
class ITypesSettings(Interface): """A single unit of size limit for a type and field name""" content_type = schema.Choice( title=_(u"Content type"), vocabulary='plone.app.vocabularies.ReallyUserFriendlyTypes', required=True) field_name = schema.TextLine( title=_(u"Field name"), description=_( 'help_field_name', default=u"Low level field name, commonly \"image\" or \"file\"."), required=True) size = schema.Int( title=_(u"Size limit"), description=_( u"Type here a number in MB which will" u" limit the field size upload"), default=30, required=True )
def patched__call__(self, value, *args, **kwargs): if canBypassValidation(kwargs.get('instance', None)): return True registry = queryUtility(IRegistry) settings = None if registry: try: settings = registry.forInterface(ILimitFileSizePanel, check=True) except KeyError: pass if not settings: return self._old___call__(value, *args, **kwargs) maxsize = get_maxsize(self, settings, **kwargs) if not maxsize: return True # calculate size elif (isinstance(value, FileUpload) or isinstance(value, file) or hasattr(aq_base(value), 'tell')): value.seek(0, 2) # eof size = value.tell() value.seek(0) elif not settings.new_data_only: # we want to validate already saved data. Let use the default Atchetypes validation method try: size = len(value) except TypeError: size = 0 else: # We don't want to validate already saved data return True size = float(size) sizeMB = (size / (1024 * 1024)) if sizeMB > maxsize: msg = _( 'validation_error', default= u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)", mapping={ 'name': safe_unicode(self.name), 'size': safe_unicode("%.1f" % sizeMB), 'max': safe_unicode("%.1f" % maxsize) }) return recursiveTranslate(msg, **kwargs) else: return True
def patched__call__(self, value, *args, **kwargs): if canBypassValidation(kwargs.get('instance', None)): return True registry = queryUtility(IRegistry) settings = None if registry: try: settings = registry.forInterface(ILimitFileSizePanel, check=True) except KeyError: pass if not settings: return self._old___call__(value, *args, **kwargs) maxsize = get_maxsize(self, settings, **kwargs) if not maxsize: return True # calculate size elif (isinstance(value, FileUpload) or isinstance(value, file) or hasattr(aq_base(value), 'tell')): value.seek(0, 2) # eof size = value.tell() value.seek(0) elif not settings.new_data_only: # we want to validate already saved data. Let use the default Atchetypes validation method try: size = len(value) except TypeError: size = 0 else: # We don't want to validate already saved data return True size = float(size) sizeMB = (size / (1024 * 1024)) if sizeMB > maxsize: msg = _('validation_error', default=u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)", mapping={ 'name': safe_unicode(self.name), 'size': safe_unicode("%.1f" % sizeMB), 'max': safe_unicode("%.1f" % maxsize)}) return recursiveTranslate(msg, **kwargs) else: return True
def check_size(self, uploadfile, maxsize): """ check the size of given file """ result = { 'maxsize': maxsize, 'valid': True, } if self.canBypassValidation(): return result new_data_only = api.portal.get_registry_record( 'new_data_only', interface=ILimitFileSizePanel) # calculate size if (isinstance(uploadfile, FileUpload) or isinstance(uploadfile, file) or hasattr(aq_base(uploadfile), 'tell')): # NOQA uploadfile.seek(0, 2) # eof size = uploadfile.tell() uploadfile.seek(0) elif not new_data_only: # we want to validate already saved data. Let use the default # Archetypes validation method try: size = len(uploadfile) except TypeError: size = 0 else: # We don't want to validate already saved data return result size = float(size) sizeMB = (size / (1024 * 1024)) result['sizeMB'] = sizeMB if sizeMB > maxsize: result['valid'] = False msg = _( 'validation_error', default=u'Validation failed. Uploaded data is too large:' u' ${size}MB (max ${max}MB)', mapping={ 'size': safe_unicode('{0:.1f}'.format(sizeMB)), 'max': safe_unicode('{0:.1f}'.format(maxsize)) }) result['error'] = translate(msg, context=self.request) return result
def handleCancel(self, action): IStatusMessage(self.request).addStatusMessage(_(u"Edit cancelled"), "info") self.request.response.redirect("%s/%s" % (self.context.absolute_url(), self.control_panel_view))
def handleCancel(self, action): IStatusMessage(self.request).addStatusMessage(_(u"Edit cancelled"), "info") self.request.response.redirect( "%s/%s" % (self.context.absolute_url(), self.control_panel_view))