Exemple #1
0
    def test_stringValidators(self):
        """ Test string validation
        """

        from Products.validation.exceptions import UnknowValidatorError
        from Products.validation import validation as v
        
        self.assertRaises(UnknowValidatorError, v.validate, 'noValidator', 'test')
            
        self.failIfEqual( v.validate('pfgv_isEmail', 'test'), 1 )

        self.failUnlessEqual( v.validate('pfgv_isEmail', '*****@*****.**'), 1 )

        self.failUnlessEqual( v.validate('pfgv_isZipCode', '12345-1234'), 1 )
    def test_stringValidators(self):
        """ Test string validation
        """

        from Products.validation.exceptions import UnknowValidatorError
        from Products.validation import validation as v

        self.assertRaises(UnknowValidatorError, v.validate, "noValidator", "test")

        self.failIfEqual(v.validate("pfgv_isEmail", "test"), 1)

        self.failUnlessEqual(v.validate("pfgv_isEmail", "*****@*****.**"), 1)

        self.failUnlessEqual(v.validate("pfgv_isZipCode", "12345"), 1)
        self.failUnlessEqual(v.validate("pfgv_isZipCode", "12345-1234"), 1)
        # Canadian zip codes
        self.failUnlessEqual(v.validate("pfgv_isZipCode", "T2X 1V4"), 1)
        self.failUnlessEqual(v.validate("pfgv_isZipCode", "T2X1V4"), 1)
        self.failUnlessEqual(v.validate("pfgv_isZipCode", "t2x 1v4"), 1)
Exemple #3
0
    def test_stringValidators(self):
        """ Test string validation
        """

        from Products.validation.exceptions import UnknowValidatorError
        from Products.validation import validation as v

        self.assertRaises(UnknowValidatorError, v.validate, 'noValidator',
                          'test')

        self.failIfEqual(v.validate('pfgv_isEmail', 'test'), 1)

        self.failUnlessEqual(v.validate('pfgv_isEmail', '*****@*****.**'), 1)

        self.failUnlessEqual(v.validate('pfgv_isZipCode', '12345'), 1)
        self.failUnlessEqual(v.validate('pfgv_isZipCode', '12345-1234'), 1)
        # Canadian zip codes
        self.failUnlessEqual(v.validate('pfgv_isZipCode', 'T2X 1V4'), 1)
        self.failUnlessEqual(v.validate('pfgv_isZipCode', 'T2X1V4'), 1)
        self.failUnlessEqual(v.validate('pfgv_isZipCode', 't2x 1v4'), 1)
                if entry.get('range'):
                    entry['formatted_citation'] = entry['range']
                    del entry['range']
                    migrated += 1
                elif not entry.get('formatted_citation'):
                    entry['formatted_citation'] = getattr(
                        obj, '%s|%s|range' % (fname, key), ''
                    )
                    print(u"Updated citation for {} to '{}' using {}".format(
                        '/'.join(obj.getPhysicalPath()),
                        entry['formatted_citation'],
                        u'%s|%s|range' % (fname, key)))
                    migrated += 1

                identifier = entry.get('identifier', '')
                if validation.validate('isURL', identifier) != 1:
                    entry['identifier'] = identifier.strip()
                    continue
                if not identifier.strip():
                    entry['identifier'] = ''
                    continue

                if (entry.get('bibliographic_uri', '').strip() or
                        entry.get('access_uri', '').strip()):
                    migrated += 1
                    continue

                for site_name in BIB_SITES:
                    if site_name in identifier:
                        entry['bibliographic_uri'] = identifier
                        break
    def create_subscribers(self, csv_data=None):
        """Create newsletter subscribers from uploaded CSV file.
        """

        # Do nothing if no submit button was hit
        if 'form.button.Import' not in self.request.form:
            return

        context = aq_inner(self.context)
        lang = context.Language()
        plone_utils = getToolByName(context, 'plone_utils')
        encoding = plone_utils.getSiteEncoding()
        existing = set(context.objectIds())
        success = []
        fail = []
        data = []


        def error(msg):
            IStatusMessage(self.request).addStatusMessage(msg, type='error')
            return self.request.response.redirect(
                context.absolute_url() + '/@@upload_csv')

        # Show error if no file was specified
        filename = self.request.form.get('csv_upload', None)
        if not filename:
            return error(_('No file specified.'))

        # Detect the dialect of the CSV, and load it
        dialect = csv.Sniffer().sniff(filename.read())
        filename.seek(0)
        reader = csv.reader(filename, dialect=dialect)

        # Verify header
        header = normalize_list(reader.next(), encoding)
        expected_header = normalize_list(
            [context.translate(_(x)) for x in CSV_HEADER], None)
        if header != expected_header:
            return error(_("CSV file header doesn't match expected one."))

        for index, line in enumerate(reader):
            # Check the length of the line
            if len(line) != 4:
                msg =_('The number of entries on the line ${line} is not correct.',
                       mapping=dict(line=index))
                fail.append({'failure': msg})
                continue

            try:
                subscriber = decode_list(line, encoding)
            except UnicodeDecodeError:
                msg = _('The CSV file is not encoded in ${encoding}.',
                        mapping=dict(encoding=encoding))
                fail.append({'failure': msg})
                continue

            salutation = subscriber[0]
            fullname = subscriber[1]
            email = subscriber[2]
            organization = subscriber[3]

            if validation.validate('isEmail', email.encode('utf-8')) != 1:
                msg = _('This email is not a valid email address.')
                fail.append(
                    {'salutation': salutation,
                     'fullname': fullname,
                     'email': email,
                     'organization': organization,
                     'failure': msg})
                continue                
            identifier = plone_utils.normalizeString(email).lower()
            if identifier in existing:
                msg = _('This email address is already registered.')
                fail.append(
                    {'salutation': salutation,
                     'fullname': fullname,
                     'email': email,
                     'organization': organization,
                     'failure': msg})
                continue
            title = u" - ".join((email, fullname))
            try:
                context.invokeFactory('ENLSubscriber',
                    id=identifier,
                    title=title,
                    description="",
                    language=lang)
                obj = context._getOb(identifier)
                obj.email = email
                obj.fullname = fullname
                obj.organization = organization
                obj.salutation = salutation
                obj.reindexObject()
                existing.add(identifier)
                success.append(
                    {'salutation': salutation,
                     'fullname': fullname,
                     'email': email,
                     'organization': organization})
            except Exception, e:
                fail.append(
                    {'salutation': salutation,
                     'fullname': fullname,
                     'email': email,
                     'organization': organization,
                     'failure': 'An error occured while creating this subscriber: %s' % str(e)})