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 __call__(self, value, *args, **kwargs): isEmpty = kwargs.get('isEmpty', False) instance = kwargs.get('instance', None) field = kwargs.get('field', None) # XXX: This is a temporary fix. Need to be fixed right for AT 2.0 # content_edit / BaseObject.processForm() calls # widget.process_form a second time! if instance and field: widget = field.widget request = getattr(instance, 'REQUEST', None) if request and request.form: form = request.form result = widget.process_form(instance, field, form, empty_marker=_marker, emptyReturnsMarker=True) if result is _marker or result is None: isEmpty = True if isEmpty: return True elif value == '' or value is None: return True else: if getattr(self, 'showError', False): msg = _(u"Validation failed($name): '$value' is not empty.", mapping = { 'name' : safe_unicode(self.name), 'value': safe_unicode(value)}) return recursiveTranslate(msg, **kwargs) else: return False
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 __call__(self, value, *args, **kwargs): if not value: msg = _(u"Validation failed($name): value is empty ($value).", mapping = {'name': self.name, 'value': repr(value)}) return recursiveTranslate(msg, **kwargs) if not isinstance(value, DateTime): try: value = DateTime(value) except: msg = _(u"Validation failed($name): could not convert $value to a date.", mapping = {'name': safe_unicode(self.name), 'value': safe_unicode(value)}) return recursiveTranslate(msg, **kwargs) 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 __call__(self, value, *args, **kwargs): if not value: return True if value.startswith('http'): return True try: url = str(value) url = url.lstrip('/') portal = api.portal.get() portal.restrictedTraverse(url) except: msg = _(u"Validation failed($name): $value is not a proper link.", mapping={'name': safe_unicode(self.name), 'value': safe_unicode(value)}) return recursiveTranslate(msg, **kwargs) return True
def __call__(self, id, instance, *args, **kwargs): try: # try to use the check_id script of CMFPlone check_id = aq_get(instance, 'check_id', None, 1) if check_id is None: raise AttributeError('check_id script not found') return check_id(id, required=kwargs.get('required', 0)) or 1 except AttributeError: # space test if ' ' in id: msg = _(u'Spaces are not allowed in ids') return recursiveTranslate(msg, **kwargs) # in parent test parent = aq_parent(aq_inner(instance)) # If the id is given to a different object already if id in parent.objectIds() and getattr( aq_base(parent), id) is not aq_base(instance): msg = _(u'Id $id is already in use', mapping={'id': safe_unicode(id)}) return recursiveTranslate(msg, **kwargs) # object manager test # XXX: This is f***ed try: ObjectManager.checkValidId(self, id, allow_dup=1) except BadRequest as m: return str(m) return 1
def __call__(self, value, instance, *args, **kwargs): kw={ 'here':instance, 'object':instance, 'instance':instance, 'value':value, 'args':args, 'kwargs':kwargs, } context=getEngine().getContext(kw) res=self.compiledExpression(context) if res: return True else: if self.errormsg and type(self.errormsg) == Message: #hack to support including values in i18n message, too. hopefully this works out #potentially it could unintentionally overwrite already present values self.errormsg.mapping = kw return recursiveTranslate(self.errormsg, **kwargs) elif self.errormsg: # support strings as errormsg for backward compatibility return self.errormsg % kw else: msg = _(u'validation failed, expr was:$expr', mapping={'expr': safe_unicode(self.expression)}) return recursiveTranslate(msg, **kwargs)
def __call__(self, id, instance, *args, **kwargs): try: # try to use the check_id script of CMFPlone check_id = aq_get(instance, 'check_id', None, 1) if check_id is None: raise AttributeError('check_id script not found') return check_id(id, required=kwargs.get('required', 0)) or 1 except AttributeError: # space test if ' ' in id: msg = _(u'Spaces are not allowed in ids') return recursiveTranslate(msg, **kwargs) # in parent test parent = aq_parent(aq_inner(instance)) # If the id is given to a different object already if id in parent.objectIds() and getattr(aq_base(parent), id) is not aq_base(instance): msg = _(u'Id $id is already in use', mapping = {'id': safe_unicode(id)}) return recursiveTranslate(msg, **kwargs) # objet manager test # XXX: This is f***ed try: ObjectManager.checkValidId(self, id, allow_dup=1) except BadRequest, m: return str(m) return 1
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 __call__(self, value, *args, **kwargs): instance = kwargs.get('instance', None) field = kwargs.get('field', None) # get max size if kwargs.has_key('maxsize'): maxsize = kwargs.get('maxsize') elif hasattr(aq_base(instance), 'getMaxSizeFor'): maxsize = instance.getMaxSizeFor(field.getName()) elif hasattr(field, 'maxsize'): maxsize = field.maxsize else: # set to given default value (default defaults to 0) maxsize = self.maxsize 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) else: try: size = len(value) except TypeError: size = 0 size = float(size) sizeMB = (size / (1024 * 1024)) if sizeMB > maxsize: msg = _( "Validation failed($name: Uploaded data is too large: ${size}MB (max ${max}MB)", mapping={ 'name': safe_unicode(self.name), 'size': safe_unicode("%.3f" % sizeMB), 'max': safe_unicode("%.3f" % maxsize) }) return recursiveTranslate(msg, **kwargs) else: return True
def __call__(self, value, *args, **kwargs): instance = kwargs.get('instance', None) field = kwargs.get('field', None) # get max size if kwargs.has_key('maxsize'): maxsize = kwargs.get('maxsize') elif hasattr(aq_base(instance), 'getMaxSizeFor'): maxsize = instance.getMaxSizeFor(field.getName()) elif hasattr(field, 'maxsize'): maxsize = field.maxsize else: # set to given default value (default defaults to 0) registry = getUtility(IRegistry) settings = registry.forInterface(ITranscodeSetings) maxsize = settings.max_file_size 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) else: try: size = len(value) except TypeError: size = 0 size = float(size) sizeMB = (size / (1024 * 1024)) if sizeMB > maxsize: msg = _("Validation failed(Uploaded data is too large: ${size}MB (max ${max}MB))", mapping = { 'size' : safe_unicode("%.3f" % sizeMB), 'max' : safe_unicode("%.3f" % maxsize) }) return recursiveTranslate(msg, **kwargs) else: return True
def __call__(self, value, *args, **kwargs): if not value: msg = _(u"Validation failed($name): value is empty ($value).", mapping={ 'name': self.name, 'value': repr(value) }) return recursiveTranslate(msg, **kwargs) if not isinstance(value, DateTime): try: value = DateTime(value) except: msg = _( u"Validation failed($name): could not convert $value to a date.", mapping={ 'name': safe_unicode(self.name), 'value': safe_unicode(value) }) return recursiveTranslate(msg, **kwargs) return True
def __call__(self, value, *args, **kwargs): phone = re.compile('^(0|\+|00)[\d \'-/]{6,}$') if not phone.match(value): msg = _( "Validation failed($name: no valid phone number)", mapping={ 'name': safe_unicode(self.name), }, ) return msg return True
def __call__(self, value, *args, **kwargs): if len(args) >= 1: minval = args[0] else: minval = self.minval if len(args) >= 2: maxval = args[1] else: maxval = self.maxval assert (minval <= maxval) try: nval = float(value) except ValueError: msg = _( u"Validation failed($name): could not convert '$value' to number", mapping={ 'name': safe_unicode(self.name), 'value': safe_unicode(value) }) return recursiveTranslate(msg, **kwargs) if minval <= nval < maxval: return 1 msg = _(u"Validation failed($name): '$value' out of range($min, $max)", mapping={ 'name': safe_unicode(self.name), 'value': safe_unicode(value), 'min': safe_unicode(minval), 'max': safe_unicode(maxval), }) return recursiveTranslate(msg, **kwargs)
def __call__(self, value, *args, **kwargs): if len(args) >= 1: minval = args[0] else: minval = self.minval if len(args) >= 2: maxval = args[1] else: maxval = self.maxval assert minval <= maxval try: nval = float(value) except ValueError: msg = _( u"Validation failed($name): could not convert '$value' to number", mapping={"name": safe_unicode(self.name), "value": safe_unicode(value)}, ) return recursiveTranslate(msg, **kwargs) if minval <= nval < maxval: return 1 msg = _( u"Validation failed($name): '$value' out of range($min, $max)", mapping={ "name": safe_unicode(self.name), "value": safe_unicode(value), "min": safe_unicode(minval), "max": safe_unicode(maxval), }, ) return recursiveTranslate(msg, **kwargs)
def __call__(self, value, *args, **kwargs): if type(value) != StringType: msg = _( u"Validation failed($name): $value of type $type, expected 'string'", mapping={ 'name': safe_unicode(self.name), 'value': safe_unicode(value), 'type': safe_unicode(type(value)) }) return recursiveTranslate(msg, **kwargs) ignore = kwargs.get('ignore', None) if ignore: value = ignoreRE(value, ignore) elif self.ignore: value = ignoreRE(value, self.ignore) for r in self.regex: m = r.match(value) if not m: msg = _(u"Validation failed($name): '$value' $errmsg", mapping={ 'name': safe_unicode(self.name), 'value': safe_unicode(value), 'errmsg': safe_unicode(self.errmsg) }) return recursiveTranslate(msg, **kwargs) return 1
def __call__(self, value, *args, **kwargs): if type(value) != StringType: msg = _(u"Validation failed($name): $value of type $type, expected 'string'", mapping = { 'name' : safe_unicode(self.name), 'value': safe_unicode(value), 'type' : safe_unicode(type(value)) }) return recursiveTranslate(msg, **kwargs) ignore = kwargs.get('ignore', None) if ignore: value = ignoreRE(value, ignore) elif self.ignore: value = ignoreRE(value, self.ignore) for r in self.regex: m = r.match(value) if not m: msg = _(u"Validation failed($name): '$value' $errmsg", mapping={ 'name' : safe_unicode(self.name), 'value': safe_unicode(value), 'errmsg' : safe_unicode(self.errmsg) }) return recursiveTranslate(msg, **kwargs) return 1
def __call__(self, value, *args, **kwargs): mail = re.compile("^(\w&.%#$&'\*+-/=?^_`{}|~]+!)*[\w&.%#$&'\*+-/=" + "?^_`{}|~]+@(([0-9a-z]([0-9a-z-]*[0-9a-z])?" + "\.)+[a-z]{2,6}|([0-9]{1,3}\.){3}[0-9]{1,3})$") if not mail.match(value): msg = _( "Validation failed($name: no valid email)", mapping={ 'name': safe_unicode(self.name), }, ) return recursiveTranslate(msg) return True
def fallback_check_id(instance, id, **kwargs): # space test if ' ' in id: msg = _(u'Spaces are not allowed in ids') return recursiveTranslate(msg, **kwargs) # in parent test parent = aq_parent(aq_inner(instance)) # If the id is given to a different object already if (id in parent.objectIds() and getattr(aq_base(parent), id) is not aq_base(instance)): msg = _(u'Id $id is already in use', mapping = {'id': safe_unicode(id)}) return recursiveTranslate(msg, **kwargs) # object manager test try: # Note: we used to pass 'self' (the validator) instead of 'instance', # which makes no sense. ObjectManager.checkValidId(instance, id, allow_dup=1) except BadRequest as m: return str(m) return 1
def upload(self): # NOQA """Adds uploaded file""" context = aq_inner(self.context) if not IFolderish.providedBy(context): context = aq_parent(context) request = context.REQUEST ctr_tool = getToolByName(context, 'content_type_registry') utility = getToolByName(context, 'portal_tinymce') uploadfile = request['uploadfile'] id = uploadfile.filename content_type = uploadfile.headers["Content-Type"] typename = ctr_tool.findTypeName(id, content_type, "") # Permission checks based on code by Danny Bloemendaal # 1) check if the current user has permissions to add stuff if not context.portal_membership.checkPermission( 'Add portal content', context): return self.errorMessage( _("You do not have permission to upload files in this folder")) # 2) check image types uploadable in folder. # priority is to content_type_registry image type allowed_types = [t.id for t in context.getAllowedTypes()] if typename in allowed_types: uploadable_types = [typename] else: uploadable_types = [] if content_type.split('/')[0] == 'image': image_portal_types = utility.imageobjects.split('\n') uploadable_types += [ t for t in image_portal_types if t in allowed_types and t not in uploadable_types] # limitfilesizepanel check size_check = self.check_file_size(uploadable_types, request) if size_check and not size_check.get('valid', False): msg = lfspmf( '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 self.errorMessage(msg) # end otf limitfilesizepanel check # Get an unused filename without path id = self.cleanupFilename(id) for metatype in uploadable_types: try: newid = context.invokeFactory(type_name=metatype, id=id) if newid is None or newid == '': newid = id break except ValueError: continue except BadRequest: return self.errorMessage(_("Bad filename, please rename.")) else: return self.errorMessage( _("Not allowed to upload a file of this type to this folder")) obj = getattr(context, newid, None) # Set title + description. # Attempt to use Archetypes mutator if there is one, in case it uses # a custom storage title = request['uploadtitle'] description = request['uploaddescription'] if title: try: obj.setTitle(title) except AttributeError: obj.title = title if description: try: obj.setDescription(description) except AttributeError: obj.description = description if HAS_DEXTERITY and IDexterityContent.providedBy(obj): if not self.setDexterityItem(obj, uploadfile, id): msg = _( "The content-type '${type}' has no image- or file-field!", mapping={'type': metatype}) return self.errorMessage(msg) else: # set primary field pf = obj.getPrimaryField() pf.set(obj, uploadfile) if not obj: return self.errorMessage(_("Could not upload the file")) obj.reindexObject() folder = obj.aq_parent.absolute_url() if utility.link_using_uids: path = "resolveuid/%s" % (uuidFor(obj)) else: path = obj.absolute_url() tiny_pkg = pkg_resources.get_distribution("Products.TinyMCE") if tiny_pkg.version.startswith('1.2'): # Plone < 4.3 return self.okMessage(path) else: # Plone >= 4.3 return self.okMessage(path, folder)
def upload(self): # NOQA """Adds uploaded file""" context = aq_inner(self.context) if not IFolderish.providedBy(context): context = aq_parent(context) request = context.REQUEST ctr_tool = getToolByName(context, 'content_type_registry') utility = getToolByName(context, 'portal_tinymce') uploadfile = request['uploadfile'] id = uploadfile.filename content_type = uploadfile.headers["Content-Type"] typename = ctr_tool.findTypeName(id, content_type, "") # Permission checks based on code by Danny Bloemendaal # 1) check if the current user has permissions to add stuff if not context.portal_membership.checkPermission( 'Add portal content', context): return self.errorMessage( _("You do not have permission to upload files in this folder")) # 2) check image types uploadable in folder. # priority is to content_type_registry image type allowed_types = [t.id for t in context.getAllowedTypes()] if typename in allowed_types: uploadable_types = [typename] else: uploadable_types = [] if content_type.split('/')[0] == 'image': image_portal_types = utility.imageobjects.split('\n') uploadable_types += [ t for t in image_portal_types if t in allowed_types and t not in uploadable_types ] # limitfilesizepanel check size_check = self.check_file_size(uploadable_types, request) if size_check and not size_check.get('valid', False): msg = lfspmf( '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 self.errorMessage(msg) # end otf limitfilesizepanel check # Get an unused filename without path id = self.cleanupFilename(id) for metatype in uploadable_types: try: newid = context.invokeFactory(type_name=metatype, id=id) if newid is None or newid == '': newid = id break except ValueError: continue except BadRequest: return self.errorMessage(_("Bad filename, please rename.")) else: return self.errorMessage( _("Not allowed to upload a file of this type to this folder")) obj = getattr(context, newid, None) # Set title + description. # Attempt to use Archetypes mutator if there is one, in case it uses # a custom storage title = request['uploadtitle'] description = request['uploaddescription'] if title: try: obj.setTitle(title) except AttributeError: obj.title = title if description: try: obj.setDescription(description) except AttributeError: obj.description = description if HAS_DEXTERITY and IDexterityContent.providedBy(obj): if not self.setDexterityItem(obj, uploadfile, id): msg = _( "The content-type '${type}' has no image- or file-field!", mapping={'type': metatype}) return self.errorMessage(msg) else: # set primary field pf = obj.getPrimaryField() pf.set(obj, uploadfile) if not obj: return self.errorMessage(_("Could not upload the file")) obj.reindexObject() folder = obj.aq_parent.absolute_url() if utility.link_using_uids: path = "resolveuid/%s" % (uuidFor(obj)) else: path = obj.absolute_url() tiny_pkg = pkg_resources.get_distribution("Products.TinyMCE") if tiny_pkg.version.startswith('1.2'): # Plone < 4.3 return self.okMessage(path) else: # Plone >= 4.3 return self.okMessage(path, folder)