예제 #1
0
    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)
예제 #2
0
    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)
예제 #3
0
    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
예제 #4
0
    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
예제 #5
0
    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
예제 #6
0
    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)
예제 #7
0
    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
예제 #8
0
    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 send_mail(obj, notification):    
    """
    Send mail to all recipients
    """
    member = getToolByName(obj, 'portal_membership').getAuthenticatedMember()
    from_email = member.getProperty('email')

    site_props = getToolByName(obj, 'portal_properties').site_properties
    encoding = site_props.getProperty('default_charset', 'UTF-8')

    registration = getToolByName(obj, 'portal_registration')
    if from_email and registration.isValidEmail(from_email):    
        pass
    else:
        return False, _(u"Your email address is invalid: %s" % str(from_email))

    host = obj.MailHost

    errors = {}

    kw = {}
    kw['REQUEST'] = self.request

    subject = recursiveTranslate(_(u'Your roles have changed in the GroupSpace ${content_title}', mapping= {'content_title': obj.Title()}), **kw) 

    for info in notification.values():
        
        old_roles = list(info['old_roles'])
        old_roles.sort()
        new_roles = list(info['new_roles'])
        old_roles.sort()

        msg = recursiveTranslate(_(u'You now have the following roles in the group \"${content_title}\":\n\t${new_roles}\nlocated at\n${content_url}\nBefore the change, you had the following roles in the group:\n\t${old_roles}', 
                                    mapping= {'content_title': obj.Title(), 
                                              'new_roles' : str(', '.join(new_roles)), 
                                              'content_url' : obj.absolute_url(), 
                                              'old_roles' : str(', '.join(old_roles))}),
                                  **kw)

        try:
            host.send(
                safe_unicode(msg),
                mto=info['email'],
                mfrom=from_email,
                subject=safe_unicode(subject),
                charset=encoding)
        except (SMTPServerDisconnected,
                SMTPSenderRefused,
                SMTPRecipientsRefused,
                SMTPDataError,
                SMTPConnectError,
                SMTPHeloError,
                SMTPAuthenticationError,
                socket.error,
                MailHostError), e:
            logger.error("collective.groupspace.mail error: %s", e, exc_info=1)
            errors[str(e)] = True
        except Exception, e:
            logger.error("collective.groupspace.mail error: %s", e, exc_info=1)
            raise
예제 #10
0
def send_mail(obj, notification):
    """
    Send mail to all recipients
    """
    member = getToolByName(obj, 'portal_membership').getAuthenticatedMember()
    from_email = member.getProperty('email')

    site_props = getToolByName(obj, 'portal_properties').site_properties
    encoding = site_props.getProperty('default_charset', 'UTF-8')

    registration = getToolByName(obj, 'portal_registration')
    if from_email and registration.isValidEmail(from_email):
        pass
    else:
        return False, _(u"Your email address is invalid: %s" % str(from_email))

    host = obj.MailHost

    errors = {}

    kw = {}
    kw['REQUEST'] = self.request

    subject = recursiveTranslate(
        _(u'Your roles have changed in the GroupSpace ${content_title}',
          mapping={'content_title': obj.Title()}), **kw)

    for info in notification.values():

        old_roles = list(info['old_roles'])
        old_roles.sort()
        new_roles = list(info['new_roles'])
        old_roles.sort()

        msg = recursiveTranslate(
            _(u'You now have the following roles in the group \"${content_title}\":\n\t${new_roles}\nlocated at\n${content_url}\nBefore the change, you had the following roles in the group:\n\t${old_roles}',
              mapping={
                  'content_title': obj.Title(),
                  'new_roles': str(', '.join(new_roles)),
                  'content_url': obj.absolute_url(),
                  'old_roles': str(', '.join(old_roles))
              }), **kw)

        try:
            host.send(safe_unicode(msg),
                      mto=info['email'],
                      mfrom=from_email,
                      subject=safe_unicode(subject),
                      charset=encoding)
        except (SMTPServerDisconnected, SMTPSenderRefused,
                SMTPRecipientsRefused, SMTPDataError, SMTPConnectError,
                SMTPHeloError, SMTPAuthenticationError, socket.error,
                MailHostError), e:
            logger.error("collective.groupspace.mail error: %s", e, exc_info=1)
            errors[str(e)] = True
        except Exception, e:
            logger.error("collective.groupspace.mail error: %s", e, exc_info=1)
            raise
예제 #11
0
    def send(self, mails, send_from_address, send_to_members, message):
        """
        Send the mail
        """

        context = aq_inner(self.context)

        encoding = self.site_properties.getProperty('default_charset', 'UTF-8')

        host = context.MailHost

        to_emails = []
        for user_name, user_id, user_email in mails:
            if user_id in send_to_members:
                to_emails.append(user_email)

        member = self.portal_membership.getAuthenticatedMember()
        from_name = member.getProperty(
            'fullname',
            '') != '' and member.getProperty('fullname') or member.getId()

        kw = {}
        kw['REQUEST'] = self.request

        untranslated = _(
            u"""The following message has been written by ${from_name} to the group ${content_title} located at ${content_url}:\n${message}""",
            mapping={
                'from_name': from_name,
                'content_title': context.Title(),
                'content_url': context.absolute_url(),
                'message': message
            })

        msg = recursiveTranslate(untranslated, **kw)

        subject = recursiveTranslate(
            _(u"""Message to the group \"${content_title}\" """,
              mapping={'content_title': context.Title()}), **kw)

        try:
            host.send(safe_unicode(msg),
                      mto=to_emails,
                      mfrom=send_from_address,
                      subject=safe_unicode(subject),
                      charset=encoding)

        except (SMTPServerDisconnected, SMTPSenderRefused,
                SMTPRecipientsRefused, SMTPDataError, SMTPConnectError,
                SMTPHeloError, SMTPAuthenticationError, socket.error,
                MailHostError), e:
            return False, _(u"An error occurred while sending the email. %s" %
                            str(e))
예제 #12
0
 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 send(self, mails, send_from_address, send_to_members, message):
        """
        Send the mail
        """

        context = aq_inner(self.context)

        encoding = self.site_properties.getProperty('default_charset', 'UTF-8')
                            
        host = context.MailHost
    
        to_emails = []
        for user_name, user_id, user_email in mails:
            if user_id in send_to_members:
                to_emails.append(user_email)
                          
        member  = self.portal_membership.getAuthenticatedMember()
        from_name = member.getProperty('fullname', '') != '' and member.getProperty('fullname') or member.getId()

        kw = {}
        kw['REQUEST'] = self.request

        untranslated = _(u"""The following message has been written by ${from_name} to the group ${content_title} located at ${content_url}:\n${message}""", 
                          mapping = {'from_name' : from_name, 'content_title' : context.Title(), 'content_url' : context.absolute_url(), 'message' : message}
                        )

        msg = recursiveTranslate(untranslated, **kw)

        subject = recursiveTranslate(_(u"""Message to the group \"${content_title}\" """, mapping = {'content_title' : context.Title()}), **kw)

        try:
            host.send(
                safe_unicode(msg),
                mto=to_emails,
                mfrom=send_from_address,
                subject=safe_unicode(subject),
                charset=encoding)

        except (SMTPServerDisconnected,
                SMTPSenderRefused,
                SMTPRecipientsRefused,
                SMTPDataError,
                SMTPConnectError,
                SMTPHeloError,
                SMTPAuthenticationError,
                socket.error,
                MailHostError), e:
            return False, _(u"An error occurred while sending the email. %s" % str(e)) 
예제 #14
0
    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 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
예제 #17
0
 def __call__(self, value, instance, *args, **kwargs):
     
     kw={
        'here':instance,
        'object':instance,
        'instance':instance,
        'value':value,
        'chars':self.chars,
        'args':args,
        'kwargs':kwargs,
        }
     
     # get text
     if not self.strict:
         text = value 
     else:
         ttool = getToolByName(instance, 'portal_transforms')
         text = ttool.convertToData('text/plain', value)
     
     # \xc2\xa0 seems used widely by TinyMCE...
     stripped = re.sub(r'(\s|\xc2\xa0)', '', text)
     
     if len(stripped)>=self.chars:
         return True
     
     kw['current'] = len(stripped)
             
     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
         if self.errormsg.mapping:
             self.errormsg.mapping.update(**kw)
         return recursiveTranslate(self.errormsg, **kwargs)
     elif self.errormsg:
         # support strings as errormsg for backward compatibility
         return self.errormsg % kw
     else:
         msg = _('min_chars_error_msg',
                 default=u'Required min $chars chars, provided ${current}',
                 mapping={'chars': self.chars, 'current': len(stripped)})
         return recursiveTranslate(msg, **kwargs)
예제 #18
0
 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
예제 #19
0
 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
예제 #20
0
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
예제 #21
0
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
예제 #22
0
 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 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
예제 #24
0
    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
예제 #25
0
    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
예제 #26
0
    def __call__(self, value, instance, *args, **kwargs):
        acl_users = getToolByName(instance, 'acl_users')
        
        invalid_groups = []
        for group in value:
            if not acl_users.getGroupById(group) and not acl_users.getGroupByName(group):
                invalid_groups.append(group)

        if invalid_groups:
            if len(invalid_groups) == 1:
                msg = _('invalid_group_error_msg',
                        default=u"The ${group} group doesn't exist",
                        mapping={'group': invalid_groups[0]})
            else:
                msg = _('invalid_groups_error_msg',
                        default=u"The following groups don't exist: ${groups}",
                        mapping={'groups': ', '.join(invalid_groups)})
            return recursiveTranslate(msg, **kwargs)
        else:
            return True
 def __call__(self, value, *args, **kwargs):
     field = kwargs['field']
     if not isinstance(field.widget, DataGridWidget):
         # can't apply
         return True
     required_cols = []
     for cid, cdef in field.widget.columns.items():
         if cdef.required:
             required_cols.append(cid)
     if not required_cols:
         return True
     missing_columns = []
     for row in value:
         if not row.get('orderindex_', '').isdigit():
             # skipping the "template_row_marker" when on edit
             continue
         for cname, cvalue in row.items():
             if cname in required_cols and not cvalue and cname not in missing_columns:
                 missing_columns.append(cname)
     if missing_columns:
         missing_column_labels = []
         for cname in missing_columns:
             # Try to get a translated label.
             try:
                 cdef = field.widget.columns.get(cname)
                 label = cdef.getLabel(context=kwargs.get('REQUEST'))
             except:
                 # fall back to the column id.
                 label = cname
             missing_column_labels.append(label)
         return recursiveTranslate(_('missing_columns',
                                     default = u"The following columns are required but not all rows "
                                               u"have been filled: ${columns}",
                                     mapping = {'columns': ', '.join(missing_column_labels)})
                                   , **kwargs)
     return True
    def __call__(self, value, instance, *args, **kwargs):
        
        kw={
           'here': instance,
           'object': instance,
           'instance': instance,
           'value': value,
           'observed': self.observed,
           'warnValue': self.warnValue,
           'wantedValue': self.wantedValue,
           'kwargs': kwargs,
           }
        
        form = kwargs['REQUEST'].form
        
        # *** Checking warnValue ***
        if type(self.warnValue)!=bool:
            # Warn value is a specific value
            if form.get(self.observed)!=self.warnValue:
                return True
            kw['warnValue'] = '"%s"' % self.warnValue
        else: # boolean values
            if self.warnValue:
                if not form.get(self.observed):
                    return True
                kw['warnValue'] = _(u'not empty')
            else:
                if form.get(self.observed):
                    return True
                kw['warnValue'] = _(u'empy')

        # *** Checking wantedValue ***
        if type(self.wantedValue)!=bool:
            if value==self.wantedValue:
                return True
            kw['wantedValue'] = '"%s"' % self.wantedValue
        elif self.wantedValue:
            if value and self.eval_DataGridTrueValue(value):
                return True
            kw['wantedValue'] = _(u"a value")
        else:
            if not value and not self.eval_DataGridTrueValue(value):
                return True
            kw['wantedValue'] = _(u"no value")

        # We are here only when validation fails
        kw['observed'] = instance.getField(self.observed).widget.label
                
        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
            if self.errormsg.mapping:
                self.errormsg.mapping.update(**kw)
            return recursiveTranslate(self.errormsg, **kwargs)
        elif self.errormsg:
            # support strings as errormsg for backward compatibility
            return self.errormsg % kw
        else:
            msg = _('dependency_check_error_msg',
                    default=u'"$observed" field value is $warnValue. This requires that this field contains $wantedValue.',
                    mapping={'observed': kw['observed'], 'warnValue': kw['warnValue'],
                             'wantedValue': kw['wantedValue']})
            return recursiveTranslate(msg, **kwargs)