Esempio n. 1
0
    def __init__(self, name, title='', description='', validators=(),
                 register=False):
        self.name = name
        self.title = title or name
        self.description = description
        self._v_mode = []
        self._chain = []

        if type(validators) not in (TupleType, ListType):
            validators = (validators, )
        for validator in validators:
            if type(validator) in (TupleType, ListType):
                self.append(validator[0], validator[1])
            else:
                self.appendRequired(validator)

        if register:
            validationService.register(self)
Esempio n. 2
0
    def __init__(self,
                 name,
                 title='',
                 description='',
                 validators=(),
                 register=False):
        self.name = name
        self.title = title or name
        self.description = description
        self._v_mode = []
        self._chain = []

        if type(validators) not in (TupleType, ListType):
            validators = (validators, )
        for validator in validators:
            if type(validator) in (TupleType, ListType):
                self.append(validator[0], validator[1])
            else:
                self.appendRequired(validator)

        if register:
            validationService.register(self)
Esempio n. 3
0
# additional imports from tagged value 'import'
from Products.OrderableReferenceField import OrderableReferenceField


from Products.CMFCore.utils import UniqueObject


##code-section module-header #fill in your manual code here
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.utils import DisplayList

from Products.validation.config import validation
from Products.validation.validators.RangeValidator import RangeValidator

validation.register(RangeValidator("isPositiveNumber", 1, 600))
##/code-section module-header

schema = Schema(
    (
        IntegerField(
            name="ReportingLeadTime",
            widget=IntegerField._properties["widget"](
                description="How many minutes before the take the reporters have to be in the Chamber/Committee Room",
                label="Reporting Lead Time",
                label_msgid="Bungeni_label_ReportingLeadTime",
                description_msgid="Bungeni_help_ReportingLeadTime",
                i18n_domain="Bungeni",
            ),
            required=1,
            validators=("isPositiveNumber",),
Esempio n. 4
0
from Products.ATContentTypes.config import ICONMAP
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import ATCTFileContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATFile

from Products.ATContentTypes import ATCTMessageFactory as _

from Products.validation.validators.SupplValidators import MaxSizeValidator
from Products.validation.config import validation
from Products.validation import V_REQUIRED

LOG = logging.getLogger('ATCT')

validation.register(
    MaxSizeValidator('checkFileMaxSize', maxsize=zconf.ATFile.max_file_size))

ATFileSchema = ATContentTypeSchema.copy() + Schema(
    (FileField('file',
               required=True,
               primary=True,
               searchable=True,
               languageIndependent=True,
               storage=AnnotationStorage(migrate=True),
               validators=(('isNonEmptyFile', V_REQUIRED),
                           ('checkFileMaxSize', V_REQUIRED)),
               widget=FileWidget(
                   description='',
                   label=_(u'label_file', default=u'File'),
                   show_content_type=False,
               )), ),
from Products.ATContentTypes.content.document import ATDocumentBase
from Products.ATContentTypes.content.image import ATCTImageTransform
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATNewsItem

from Products.ATContentTypes import ATCTMessageFactory as _

from Products.CMFCore.permissions import View

from Products.validation.config import validation
from Products.validation.validators.SupplValidators import MaxSizeValidator
from Products.validation import V_REQUIRED

validation.register(
    MaxSizeValidator('checkNewsImageMaxSize',
                     maxsize=zconf.ATNewsItem.max_file_size))

ATNewsItemSchema = ATContentTypeSchema.copy() + Schema(
    (
        TextField(
            'text',
            required=False,
            searchable=True,
            primary=True,
            storage=AnnotationStorage(migrate=True),
            validators=('isTidyHtmlWithCleanup', ),
            #validators = ('isTidyHtml',),
            default_output_type='text/x-html-safe',
            widget=RichWidget(
                description='',
Esempio n. 6
0
def register():
    """ Register validators
    """
    validation.register(SerialTitle('serialTitle'))
        for k, v in attrs:
            if tag != 'a' and k.lower() != 'href':
                raise IllegalHTML, 'Attribute "%s" not allowed on <%s>.' % (
                    k, tag)
        return self._old_unknown_starttag(tag, attrs)

    StrippingParser.unknown_starttag = unknown_starttag


class SimpleHtmlValidator:
    """Succeed only if a limited list of HTML tags is found. Also, HTML must be good.
    """

    __implements__ = IValidator

    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description

    def __call__(self, value, *args, **kw):
        try:
            scrubHTML(value)
        except IllegalHTML, e:
            valid_tags = ",".join(["<%s>" % x for x in VALID_TAGS.keys()])
            return '%s Only the HTML tags %s accepted, and only the "href" attribute on <a>.' % (
                str(e), valid_tags)


validation.register(SimpleHtmlValidator('simple_safe_html'))
# Local imports
from Products.salesforcepfgadapter.config import PROJECTNAME, REQUIRED_MARKER, SF_ADAPTER_TYPES
from Products.salesforcepfgadapter import SalesforcePFGAdapterMessageFactory as _
from Products.salesforcepfgadapter import HAS_PLONE25, HAS_PLONE30
from Products.salesforcepfgadapter import validators
from Products.salesforcepfgadapter import interfaces
from Products.salesforcepfgadapter import config
from Products.salesforcepfgadapter.prepopulator import ExpressionChanged, sanitize_soql

if HAS_PLONE25:
    import zope.i18n

logger = logging.getLogger("PloneFormGen")

validation.register(validators.CircularDependencyValidator('CircularDependencyValidator'))

schema = FormAdapterSchema.copy() + Schema((
    StringField('SFObjectType',
        searchable=0,
        required=1,
        read_permission=ModifyPortalContent,
        default=u'Contact',
        mutator='setSFObjectType',
        widget=SelectionWidget(
            label='Salesforce Object Type',
            i18n_domain = "salesforcepfgadapter",
            label_msgid = "label_salesforce_type_text",
            ),
        vocabulary='displaySFObjectTypes',
        ),
Esempio n. 9
0
from zope import interface
from Products.Relations.field import RelationField
from Products.Bungeni.config import *

# additional imports from tagged value 'import'
from Products.OrderableReferenceField import OrderableReferenceField

from Products.CMFCore.utils import UniqueObject

##code-section module-header #fill in your manual code here
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.utils import DisplayList

from Products.validation.config import validation
from Products.validation.validators.RangeValidator import RangeValidator
validation.register(RangeValidator('isPositiveNumber', 1, 600))
##/code-section module-header

schema = Schema((
    IntegerField(
        name='ReportingLeadTime',
        widget=IntegerField._properties['widget'](
            description=
            "How many minutes before the take the reporters have to be in the Chamber/Committee Room",
            label="Reporting Lead Time",
            label_msgid='Bungeni_label_ReportingLeadTime',
            description_msgid='Bungeni_help_ReportingLeadTime',
            i18n_domain='Bungeni',
        ),
        required=1,
        validators=('isPositiveNumber', )),
Esempio n. 10
0
def register():
    """ Register validators
    """
    validation.register(ContentType('eea.relations.contenttype'))
    validation.register(Required('eea.relations.required'))
Esempio n. 11
0
class SlickSettingsValidator:
    implements(IValidator)

    def __init__(self, name):
        self.name = name

    def __call__(self, value, *args, **kwargs):
        try:
            json.loads(value)
        except ValueError:
            return ("Validation failed(%s): {\"key\": value}: %s" % (
                    self.name,
                    repr(value)))
        return 1

validation.register(SlickSettingsValidator('isValidSlickSettings'))


class SlickSettingsField(ExtensionField, StringField):
    """Stores the settings for slick"""


class SlickSettingsExtender(object):
    adapts(IListingBlock)
    implements(IOrderableSchemaExtender)

    fields = [
        SlickSettingsField(
            'slick_settings',
            searchable=False,
            default=u'{"autoplay": true, "autoplaySpeed": 3000}',
Esempio n. 12
0
from zope.interface import implements
import logging


origin_filename_validator = RegexValidator(
    'isSafeOriginFilename',
    r'^[^\/]*$',
    title='',
    description='',
    errmsg=_(
        u'origin_filename_validator_error',
        default=u'The filename must not contain "/".'
    )
)

validation.register(origin_filename_validator)


FileSchema = ATContentTypeSchema.copy() + atapi.Schema((
    FileField(
        'file',
        required=True,
        primary=True,
        searchable=True,
        languageIndependent=True,
        index_method='getIndexValue',
        storage=atapi.AnnotationStorage(migrate=True),
        validators=(('isNonEmptyFile', V_REQUIRED),
                    ('checkFileMaxSize', V_REQUIRED)),
        widget=atapi.FileWidget(
            description='',
Esempio n. 13
0

from Products.validation.config import validation

from XMLValidator import XMLValidator

validation.register(XMLValidator('isValidXML'))
Esempio n. 14
0
""" Content init module
"""

from Products.validation.config import validation
from eea.sparql.content.validators import SparqlQueryValidator
validation.register(SparqlQueryValidator('isSparqlOverLimit'))
Esempio n. 15
0
    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description

    def __call__(self, value, instance, *args, **kwargs):
        cat = getToolByName(instance, 'portal_enquiry_catalog')
        requestors = cat.searchResults(
            portal_type='EnquiryRequestor', Title=value)
        if requestors and requestors[0].getObject().UID() != instance.UID():
            return ("Your email already exists, please go 2 steps back in "
                    "your browser and request your password.")
        return 1

validation.register(UniqueRequestorValidator('isUnique'))

schema = Schema((

    StringField(
        name='title',
        widget=StringWidget(
            label="Email address",
            label_msgid='EEAEnquiry_label_title',
            i18n_domain='EEAEnquiry',
        ),
        required=True,
        accessor="Title",
        validators=('isEmail', 'isUnique',)
    ),
Esempio n. 16
0
    def __call__(self, value, *args, **kw):
        """
        essa eh o metodo chamado no momento da validacao.
        value contem o valor colocado no campo a ser validado. Ex:
        value = ea5c871e-f8d2-4c7a-a32d-fe7891993130
        args eh uma tupla com todos os parametros.
        kw contem informacoes do campo, do objeto, da requisicao, etc. Ex:
        kw = {'field': <Field patient(reference:rw)>, 
              'errors': {}, 
              'REQUEST': <HTTPRequest, URL=http://localhost:8080/wres3/Appointments/dteste/visittemp.2012-02-15.6261846328/SFValidate_integrity>, 
              'instance': <VisitTemp at /wres3/Appointments/dteste/visittemp.2012-02-15.6261846328>}
        """

        passwd = value
        instance = kw['instance']
        pm = instance.portal_membership
        if pm.testCurrentPassword(passwd):
            return True
        else:
            return 'Senha incorreta.'


listValidators.append(
    CurrentPasswordValidator('isCurrentPassword',
                             title='Validador de senhas',
                             description=''))

for validador in listValidators:
    validation.register(validador)
Esempio n. 17
0
    """
    implements(IValidator)

    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description

    def __call__(self, value, instance, *args, **kwargs):
        max_values = getattr(kwargs['field'].widget, 'maxValues', None)
        value = [val for val in value if val]
        if max_values is not None and len(value) > max_values:
            return "To many values, please choose max %s." % max_values
        return 1

validation.register(MaxValuesValidator('maxValues'))

schema = Schema((

    ThemesField(
        name='themes',
        schemata='categorization',
        validators=('maxValues',),
        widget=InAndOutWidget
        (
            maxValues=3,
            label="Themes",
            description="Choose max 3 themes",
            label_msgid='EEAContentTypes_label_themes',
            description_msgid='EEAContentTypes_help_themes',
            i18n_domain='EEAContentTypes',
Esempio n. 18
0
class SlickSettingsValidator:
    implements(IValidator)

    def __init__(self, name):
        self.name = name

    def __call__(self, value, *args, **kwargs):
        try:
            json.loads(value)
        except ValueError:
            return ("Validation failed(%s): {\"key\": value}: %s" %
                    (self.name, repr(value)))
        return 1


validation.register(SlickSettingsValidator('isValidSlickSettings'))


class SlickSettingsField(ExtensionField, StringField):
    """Stores the settings for slick"""


class SlickSettingsExtender(object):
    adapts(IListingBlock)
    implements(IOrderableSchemaExtender)

    fields = [
        SlickSettingsField(
            'slick_settings',
            searchable=False,
            default=u'{"autoplay": true, "autoplaySpeed": 3000}',
Esempio n. 19
0
# -*- coding: utf-8 -*-
from Products.validation.config import validation
from zope.i18nmessageid import MessageFactory

from plone.app.collection.validators import NonJavascriptValidator

PloneMessageFactory = MessageFactory('plone')


def initialize(context):
    from plone.app.collection import config
    from Products.Archetypes import atapi
    from Products.CMFCore import utils

    content_types, constructors, ftis = atapi.process_types(
        atapi.listTypes(config.PROJECTNAME),
        config.PROJECTNAME)

    for atype, constructor in zip(content_types, constructors):
        utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type),
            content_types=(atype, ),
            permission=config.ADD_PERMISSIONS[atype.portal_type],
            extra_constructors=(constructor, ),
            ).initialize(context)

validation.register(NonJavascriptValidator('javascriptDisabled'))

__all__ = ('PloneMessageFactory', )
Esempio n. 20
0
from zope.i18nmessageid import MessageFactory
from Products.Archetypes import atapi
from Products.CMFCore import utils

from Products.validation.config import validation
from Products.zhkath.browser.validators import FileSizeValidator

from monkey import patchCropAction

from Products.zhkath import config

zhkathMessageFactory = MessageFactory('zhkath')

validation.register(FileSizeValidator('isSmallEnoughForEditors'))

patchCropAction()    


def initialize(context):

    content_types, constructors, ftis = atapi.process_types(
        atapi.listTypes(config.PROJECTNAME),
        config.PROJECTNAME)

    for atype, constructor in zip(content_types, constructors):
        utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type),
            content_types=(atype, ),
            permission=config.ADD_PERMISSIONS[atype.portal_type],
            extra_constructors=(constructor,),
            ).initialize(context)
Esempio n. 21
0
from Products.validation.interfaces.IValidator import IValidator
from Products.validation.config import validation


class MimetypeValidator:
    """
    Validate the mimetype of uploaded file
    """

    implements(IValidator)

    def __init__(self, name, mime=''):
        self.name = name
        self.mime = mime

    def __call__(self, value, *args, **kwargs):
        # calculate mimetype
        if isinstance(value, FileUpload):
            content_type = value.headers.get('content-type')
        elif isinstance(value, file) or hasattr(aq_base(value), 'filename'):
            content_type = guess_type(value.filename)[0]
        else:
            content_type = None

        if content_type and 'xml' not in content_type:
            return "Validation failed: Uploaded file is not a XML file"
        return True


validation.register(MimetypeValidator('isXMLFile', 'xml'))
Esempio n. 22
0
    implements(IValidator)

    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description

    def __call__(self, value, instance, *args, **kwargs):
        max_values = getattr(kwargs['field'].widget, 'maxValues', None)
        value = [val for val in value if val]
        if max_values is not None and len(value) > max_values:
            return "To many values, please choose max %s." % max_values
        return 1


validation.register(MaxValuesValidator('maxValues'))

schema = Schema((ThemesField(
    name='themes',
    schemata='categorization',
    validators=('maxValues', ),
    widget=InAndOutWidget(
        maxValues=3,
        label="Themes",
        description="Choose max 3 themes",
        label_msgid='EEAContentTypes_label_themes',
        description_msgid='EEAContentTypes_help_themes',
        i18n_domain='EEAContentTypes',
    ),
    languageIndependent=True,
    vocabulary='_getMergedThemes',
Esempio n. 23
0
from Products.ATContentTypes.content.base import translateMimetypeAlias
from Products.ATContentTypes.content.document import ATDocumentBase
from Products.ATContentTypes.content.image import ATCTImageTransform
from Products.ATContentTypes.interfaces import IATNewsItem
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.ATContentTypes import ATCTMessageFactory as _

from Products.CMFCore.permissions import View

from Products.validation.config import validation
from Products.validation.validators.SupplValidators import MaxSizeValidator
from Products.validation import V_REQUIRED

validation.register(MaxSizeValidator('checkNewsImageMaxSize',
                                     maxsize=zconf.ATNewsItem.max_file_size))


ATNewsItemSchema = ATContentTypeSchema.copy() + Schema((
    TextField('text',
        required = False,
        searchable = True,
        primary = True,
        storage = AnnotationStorage(migrate=True),
        validators = ('isTidyHtmlWithCleanup',),
        #validators = ('isTidyHtml',),
        default_output_type = 'text/x-html-safe',
        widget = RichWidget(
            description = '',
            label = _(u'label_body_text', u'Body Text'),
            rows = 25,
Esempio n. 24
0
from Products.Archetypes import PloneMessageFactory as _
from Products.Archetypes.Schema import Schema
from Products.Archetypes.Field import StringField, BooleanField
from Products.Archetypes.Widget import StringWidget, BooleanWidget, SelectionWidget
from Products.validation.config import validation

from TT_Validators import AlreadySubscriber

validation.register(AlreadySubscriber('isAlreadySubscriber'))

subscriptbe_schema = Schema((

    StringField('salutation',
        searchable = 0,
        required = 0,
        regfield = 1,
        user_property = True,
        widget = SelectionWidget(
            label='Salutation',
            label_msgid='label_salutation',
            description="Choose an appropriate salutation",
            description_msgid='help_salutation',            
            i18n_domain='plone',
        ),
        vocabulary=(
            ("salutation_ms", "Ms."), 
            ("salutation_mr", "Mr.")
        )
    ),

    StringField('firstname',
Esempio n. 25
0
from Products.ATContentTypes.configuration import zconf
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import ATCTFileContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATImage

from Products.ATContentTypes.lib.imagetransform import ATCTImageTransform

from Products.ATContentTypes import ATCTMessageFactory as _

from Products.validation.config import validation
from Products.validation.validators.SupplValidators import MaxSizeValidator
from Products.validation import V_REQUIRED

validation.register(MaxSizeValidator('checkImageMaxSize',
                                     maxsize=zconf.ATImage.max_file_size))


ATImageSchema = ATContentTypeSchema.copy() + Schema((
    ImageField('image',
               required=True,
               primary=True,
               languageIndependent=True,
               storage=AnnotationStorage(migrate=True),
               swallowResizeExceptions=zconf.swallowImageResizeExceptions.enable,
               pil_quality=zconf.pil_config.quality,
               pil_resize_algo=zconf.pil_config.resize_algo,
               max_size=zconf.ATImage.max_image_dimension,
               sizes={'large': (768, 768),
                      'preview': (400, 400),
                      'mini': (200, 200),
Esempio n. 26
0
""" Custom content
"""
from Products.validation.config import validation
from Products.ATContentTypes.content.base import registerATCT
from eea.daviz.content.visualization import DavizVisualization
from eea.daviz.config import PACKAGE
from eea.daviz.content.validators import CSVFileValidator
from eea.daviz.content.validators import ExternalDataValidator
validation.register(CSVFileValidator('csvfile'))
validation.register(ExternalDataValidator('externalURL'))

def register():
    """ Register custom content-types
    """
    registerATCT(DavizVisualization, PACKAGE)
Esempio n. 27
0
    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description

    def __call__(self, value, instance, *args, **kwargs):
        cat = getToolByName(instance, 'portal_enquiry_catalog')
        requestors = cat.searchResults(portal_type='EnquiryRequestor',
                                       Title=value)
        if requestors and requestors[0].getObject().UID() != instance.UID():
            return ("Your email already exists, please go 2 steps back in "
                    "your browser and request your password.")
        return 1


validation.register(UniqueRequestorValidator('isUnique'))

schema = Schema((
    StringField(name='title',
                widget=StringWidget(
                    label="Email address",
                    label_msgid='EEAEnquiry_label_title',
                    i18n_domain='EEAEnquiry',
                ),
                required=True,
                accessor="Title",
                validators=(
                    'isEmail',
                    'isUnique',
                )),
    StringField(name='password',
    # monkey patch to disallow attrs other than a href. We actually could do this more elegantly,
    def unknown_starttag(self, tag, attrs):
        """ Delete all tags except for legal ones.
        """
        for k, v in attrs:
            if tag != 'a' and k.lower() != 'href':
                raise IllegalHTML, 'Attribute "%s" not allowed on <%s>.' % (k, tag)
        return self._old_unknown_starttag(tag, attrs)

    StrippingParser.unknown_starttag = unknown_starttag

class SimpleHtmlValidator:
    """Succeed only if a limited list of HTML tags is found. Also, HTML must be good.
    """

    __implements__ = IValidator
    
    def __init__(self, name, title='', description=''):
        self.name = name
        self.title = title or name
        self.description = description
    
    def __call__(self, value, *args, **kw):
        try:
            scrubHTML(value)
        except IllegalHTML, e:
            valid_tags = ",".join(["<%s>" % x for x in VALID_TAGS.keys()])
            return '%s Only the HTML tags %s accepted, and only the "href" attribute on <a>.' % (str(e), valid_tags)

validation.register(SimpleHtmlValidator('simple_safe_html'))
Esempio n. 29
0
from Products.validation.interfaces.IValidator import IValidator
from Products.validation.config import validation

class MimetypeValidator:
    """
    Validate the mimetype of uploaded file
    """

    implements(IValidator)

    def __init__(self, name, mime=''):
        self.name = name
        self.mime = mime

    def __call__(self, value, *args, **kwargs):
        # calculate mimetype
        if isinstance(value, FileUpload):
            content_type = value.headers.get('content-type')
        elif isinstance(value, file) or hasattr(aq_base(value), 'filename'):
            content_type = guess_type(value.filename)[0]
        else:
            content_type = None

        if content_type and 'xml' not in content_type:
            return "Validation failed: Uploaded file is not a XML file"
        return True


validation.register(MimetypeValidator('isXMLFile', 'xml'))
Esempio n. 30
0
def register():
    """ Register validators
    """
    validation.register(ContentType("eea.relations.contenttype"))
    validation.register(Required("eea.relations.required"))
Esempio n. 31
0
                if kw['REQUEST'].form.get('%s_delete' % kw['field'].getName(), None) == 'nochange':
                    type = kw['field'].getContentType(kw['instance'])
                else:
                    my_mime_types = getToolByName(kw['instance'], 'mimetypes_registry')
                    type = my_mime_types.lookupExtension(value.filename.lower())
                    #pdb.set_trace()
                    if type is None:
                        type = my_mime_types.globFilename(value.filename)
                    try:
                        file_type = type.my_mime_types[0]
                    except: # wasn't able to parse mimetype
                        try:
                            file_type=str(type)
                            #pdb.set_trace()
                        except:
                            file_type = None
                        if file_type in valid_types:
                            return 1
                        elif ((file_type not in valid_types) or (file_type in valid_types)) and (transcode_status == True):
                            return 1
                        elif file_type not in valid_types and transcode_status == False:
                            return error
            except:
                return error
        return 1
            
ValidatorsList.append(TranscodeVideoValidator('MyTranscodeValidator', title='', description=''))

for validator in ValidatorsList:
    validation.register(validator)
from zope.interface import implements

LeadImageMessageFactory = MessageFactory('collective.contentleadimage')

# import utils to register indexable attribute
import utils

def initialize(context):
    """Initializer called when used as a Zope 2 product."""

class ImageFormatValidator:
    implements(IValidator,)

    def __init__(self, name):
        self.name = name

    def __call__(self, value, *args, **kwargs):

        if value == 'DELETE_IMAGE':
            return 1

        content_type = value.headers.get('content-type', '')

        # Note: Scaling for SVG does not work.
        if content_type not in ('image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'):
            return "Image should be a web-friendly format, such as JPG, PNG, or GIF"

        return 1

validation.register(ImageFormatValidator('isValidImage'))
Esempio n. 33
0
from Products.validation.config import validation
from validators import LinkValidator

# registers validators
validation.register(LinkValidator('isLink'))
Esempio n. 34
0
# Local imports
from Products.salesforcepfgadapter.config import PROJECTNAME, REQUIRED_MARKER, SF_ADAPTER_TYPES
from Products.salesforcepfgadapter import SalesforcePFGAdapterMessageFactory as _
from Products.salesforcepfgadapter import HAS_PLONE25, HAS_PLONE30
from Products.salesforcepfgadapter import validators
from Products.salesforcepfgadapter import interfaces
from Products.salesforcepfgadapter import config
from Products.salesforcepfgadapter.prepopulator import ExpressionChanged, sanitize_soql

if HAS_PLONE25:
    import zope.i18n

logger = logging.getLogger("PloneFormGen")

validation.register(
    validators.CircularDependencyValidator('CircularDependencyValidator'))

schema = FormAdapterSchema.copy() + Schema((
    StringField(
        'SFObjectType',
        searchable=0,
        required=1,
        read_permission=ModifyPortalContent,
        default=u'Contact',
        mutator='setSFObjectType',
        widget=SelectionWidget(
            label='Salesforce Object Type',
            i18n_domain="salesforcepfgadapter",
            label_msgid="label_salesforce_type_text",
        ),
        vocabulary='displaySFObjectTypes',