def reccurencevocabulary(context):
    return SimpleVocabulary.fromTitleItems([(-1, -1, _('None')),
                             (YEARLY, YEARLY, _('Yearly')),
                             (MONTHLY, MONTHLY, _('Monthly')),
                             (WEEKLY, WEEKLY, _('Weekly')),
                             (DAILY, DAILY, _('Daily')),
                             ])
Example #2
0
    def post_validate(self, REQUEST=None, errors=None):
        # Validates start and end date.
        # End date must be after start date.
        if 'startDate' in errors or 'endDate' in errors:
            # No point in validating bad input
            return

        rstartDate = REQUEST.get('startDate', None)
        rendDate = REQUEST.get('endDate', None)

        if rendDate:
            try:
                end = DateTime(rendDate)
            except:
                errors['endDate'] = _(u'error_invalid_end_date',
                                      default=u'End date is not valid.')
        else:
            end = self.end()
        if rstartDate:
            try:
                start = DateTime(rstartDate)
            except:
                errors['startDate'] = _(u'error_invalid_start_date',
                                        default=u'Start date is not valid.')
        else:
            start = self.start()

        if 'startDate' in errors or 'endDate' in errors:
            # No point in validating bad input
            return

        if start > end:
            errors['endDate'] = _(u'error_end_must_be_after_start_date',
                                  default=u'End date must be after start date.')
Example #3
0
    def post_validate(self, REQUEST=None, errors=None):
        # Validates start and end date.
        # End date must be after start date.
        if 'startDate' in errors or 'endDate' in errors:
            # No point in validating bad input
            return

        rstartDate = REQUEST.get('startDate', None)
        rendDate = REQUEST.get('endDate', None)

        if rendDate:
            try:
                end = DateTime(rendDate)
            except:
                errors['endDate'] = _(u'error_invalid_end_date',
                                      default=u'End date is not valid.')
        else:
            end = self.end()
        if rstartDate:
            try:
                start = DateTime(rstartDate)
            except:
                errors['startDate'] = _(u'error_invalid_start_date',
                                        default=u'Start date is not valid.')
        else:
            start = self.start()

        if 'startDate' in errors or 'endDate' in errors:
            # No point in validating bad input
            return

        if start > end:
            errors['endDate'] = _(
                u'error_end_must_be_after_start_date',
                default=u'End date must be after start date.')
class ImageBlobAttachment(object):
    adapts(IImageAttachment)
    implements(ISchemaExtender)

    fields = [
        ImageField(
            'image',
            required=True,
            primary=True,
            accessor='getImage',
            mutator='setImage',
            sizes=None,
            languageIndependent=True,
            storage=AnnotationStorage(migrate=True),
            swallowResizeExceptions=zconf.swallowImageResizeExceptions.enable,
            pil_quality=zconf.pil_config.quality,
            pil_resize_algo=zconf.pil_config.resize_algo,
            original_size=None,
            max_size=zconf.ATImage.max_image_dimension,
            default_content_type='image/png',
            allowable_content_types=('image/gif', 'image/jpeg', 'image/png'),
            validators=(('isNonEmptyFile', V_REQUIRED), ('checkImageMaxSize',
                                                         V_REQUIRED)),
            widget=ImageWidget(
                label=_('label_image', default='Image'),
                description=_(''),
                show_content_type=False,
            )),
    ]

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

    def getFields(self):
        return self.fields
class FileBlobAttachment(object):
    adapts(IFileAttachment)
    implements(ISchemaExtender)

    fields = [
        FileField('file',
                  required=True,
                  primary=True,
                  searchable=True,
                  accessor='getFile',
                  mutator='setFile',
                  index_method='getIndexValue',
                  languageIndependent=True,
                  storage=AnnotationStorage(migrate=True),
                  default_content_type='application/octet-stream',
                  validators=(('isNonEmptyFile', V_REQUIRED),
                              ('checkFileMaxSize', V_REQUIRED)),
                  widget=FileWidget(
                      label=_('label_file', default='File'),
                      description=_(''),
                      show_content_type=False,
                  )),
    ]

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

    def getFields(self):
        return self.fields
Example #6
0
def override(context):
    """ Zope 2 setup """


    from eea.relations.widget.referencewidget import EEAReferenceBrowserWidget
    from Products.ATContentTypes import ATCTMessageFactory as _

    from Products.ATContentTypes import content as atcontent
    from plone.app.blob import content as blobcontent

    widget = EEAReferenceBrowserWidget(
        label = _(u'Related Items'),
        description='',
        visible = {'edit' : 'visible', 'view' : 'invisible' },
        i18n_domain="plone"
    )


    # Event
    atcontent.event.ATEvent.schema['relatedItems'].widget = widget

    # News Item
    atcontent.newsitem.ATNewsItem.schema['relatedItems'].widget = widget

    # File
    atcontent.file.ATFile.schema['relatedItems'].widget = widget

    # Image
    atcontent.image.ATImage.schema['relatedItems'].widget = widget

    # Link
    atcontent.link.ATLink.schema['relatedItems'].widget = widget

    # Topic
    atcontent.topic.ATTopic.schema['relatedItems'].widget = widget

    # Document
    atcontent.document.ATDocument.schema['relatedItems'].widget = widget

    # Folder
    atcontent.folder.ATFolder.schema['relatedItems'].widget = widget

    # Blob
    blobcontent.ATBlob.schema['relatedItems'].widget = widget
Example #7
0
from Products.ATContentTypes.criteria import SORT_INDICES
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSortCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.CMFCore.permissions import View
from zope.interface import implementer


ATSortCriterionSchema = ATBaseCriterionSchema + Schema((
    BooleanField('reversed',
                 required=0,
                 mode="rw",
                 write_permission=ChangeTopics,
                 default=0,
                 widget=BooleanWidget(label=_(u'Reverse')),
                 ),

))


@implementer(IATTopicSortCriterion)
class ATSortCriterion(ATBaseCriterion):
    """A sort criterion"""
    security = ClassSecurityInfo()
    schema = ATSortCriterionSchema
    meta_type = 'ATSortCriterion'
    archetype_name = 'Sort Criterion'
    shortDesc = 'Sort'

    @security.protected(View)
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,)),
    ), marshall=PrimaryFieldMarshaller()
    )

# Title is pulled from the file name if we don't specify anything,
# so it's not strictly required, unlike in the rest of ATCT.
ATFileSchema['title'].required = False

finalizeATCTSchema(ATFileSchema)


class ATFile(ATCTFileContent):
    """An external file uploaded to the site."""

    schema = ATFileSchema
Example #9
0
class MapLayer(BaseFolder):#(BaseFolder): 
    '''Map Layer for CoGIS'''    
    #schema = extra_schema#BaseFolderSchema
    #schema = BaseFolderSchema
    
    actions = ({'id': 'details',
              'name': 'Details',
              'action': 'string:${object_url}/MapLayer_Details',
              'permissions': (permissions.ViewManagementScreens,)},   
              {'id': 'security',
              'name': 'Security',
              'action': 'string:${object_url}/Map_Layer_Security',
              'permissions': (permissions.ViewManagementScreens,)}, 
              {'id': 'pingLayer',
              'name': 'Ping Layer',
              'action': 'string:${object_url}/Map_Layer_Ping',
              'permissions': (permissions.ViewManagementScreens,)}, 
                                          
                )

    schema = BaseSchema + Schema([
        StringField('description',
                     required=False,                            
                     searchable = 1,                     
                     widget=StringWidget(label='Description',description="Enter project description")),
        ReferenceField(
                        'relatedItems', 
                        relationship = 'relatesTo', 
                        multiValued = True, 
                        isMetadata = True, 
                        languageIndependent = False, 
                        index = 'KeywordIndex', 
                        write_permission = ModifyPortalContent, 
                        widget = ReferenceBrowserWidget( allow_search = True, 
                                                         allow_browse = True, 
                                                         show_indexes = False, 
                                                         force_close_on_insert = True, 
                                                         label = _(u'label_related_items', default=u'Related Items'), 
                                                         description = '', 
                                                         visible = {'edit' : 'visible', 'view' : 'invisible' } 
                                                         ) 
                        )
      
                      ]) 

    #schema = schema + extra_schema 
    security = ClassSecurityInfo()      
    
    archetype_name             = 'MapLayer'
    meta_type                  = 'MapLayer'
    portal_type                = 'MapLayer'
    allowed_content_types      = [] #['LayerField'] 
    filter_content_types       = 1
    global_allow               = 0
    allow_discussion           = 0
    content_icon = "mapService_icon.gif"     

    def __init__(self, id,title=''):
        '''Initialize an instance of the class'''            
        self.id=id            
        self.sampleImage = ''
        self.abstract = ''
        self.keywords = ''        
        self.uniqueName = ''
        self.geometryField = ''
        self.geometryType = ''
        self.title = id
        self.wfsSRS = ''
        self.wmsStyleName = ''
        self.wfsBoundingBox = ''
        self.fields = ''
        self.source = ''
        self.error = ''
        self.wmsQueryable = ''
        self.wmsName = ''
        self.wfsName = ''
        self.wmsSRS = ''
        self.wmsTitle = ''
        self.hasWFSLayer = False
        self.wmsBoundingBox = ''
        self.describeFeatureResponse = ''
        self.availablePermissions = ['Render','Extract']
        self.security = PersistentMapping() # e.g {'Manager':{'Render':0,'Extract':1}}        
        self.wmsXML = ""
        self.wfsXML = ""
        self.organization = ""
        self.reindexObject()
        self._p_changed = 1
        
          
        
##    def manage_afterAdd(self,item, container):
##        """
##        """      
##        self.manage_permission("View", roles=["Owner"], acquire=False)  
##        self.manage_permission("List folder contents", roles=["Owner"], acquire=False)  

    security.declarePublic('userIsOwner')
    def userIsOwner(self):
        """
        @summary: this is a zope specific method to get logged in user name
        @return: boolean, true if logged in user is the owner
        """        
        try:            
            ownerName = self.owner_info()['id']
            member =  self.portal_membership.getAuthenticatedMember()  
            userName = member.getUserName()            
            if userName == ownerName:
                return True
            else:
                return False            
            
        except:
            logger.exception('error')
            return False    
    
    def getSecurity(self):
        """
        @summary: returns the current security definitions dict
        @return: dict containing security info for roles defined in plone
        """            
        return dict(self.security)
    
    def getMetadata(self):
        """
        @summary: gets the metadata template for the layer
        @return: an html interface with metadata information
        """        
        return self.Map_Layer_Details_Stripped(self)
    
    def setSecurityVarOnly(self,securityDict):
        """
        """
        try:
            tmpDict = {}           
            for k in securityDict.keys():
                if k == 'fields':
                    continue
                
                cDict = {}
                if securityDict[k]['Render'] in ['false',0]:
                    cDict['Render'] = 0                
                if securityDict[k]['Render'] in ['true',1]:
                    cDict['Render'] = 1                
                if securityDict[k]['Extract'] in ['false',0]:
                    cDict['Extract'] = 0 
                if securityDict[k]['Extract'] in ['true',1]:
                    cDict['Extract'] = 1
                tmpDict[k] = cDict                
            
            # get a diff between current security settings and the passed security settings
            changed = {}
            for k in tmpDict.keys():
                if not k in self.security.keys():
                    changed[k] = tmpDict[k]   # its a new key
                if k in self.security.keys():
                    if self.security[k]['Render'] != tmpDict[k]['Render']:
                        changed[k] = tmpDict[k]        
            
            self.security = tmpDict        
            # only let the changes be propagated to children 
            
            # get all fields
            fields = []
            items =  self.objectItems()        
            for i in items:
                if i[1].meta_type == 'LayerField':                                
                    fields.append(i[1])                        
            
            for field in fields:
                tmpSec = field.getSecurity()             
                for k in changed.keys():
                    if not tmpSec.has_key(k):
                        tmpSec[k] = {'Render':0}  # add the key if it does not exist
                    tmpSec[k]['Render'] = changed[k]['Render']              
                field.setSecurityVarOnly(tmpSec)          
            return 1
        except:
            logger.exception('error')
    
    def setSecurity(self,securityDict):
        """
        @summary:
        @param securityDict: a dictionary containing permissions defined for certain roles defined in plone 
        """         
        try:
            tmpDict = {}           
            for k in securityDict.keys():
                if k == 'fields':
                    continue
                
                cDict = {}
                if securityDict[k]['Render'] in ['false',0]:
                    cDict['Render'] = 0                
                if securityDict[k]['Render'] in ['true',1]:
                    cDict['Render'] = 1                
                if securityDict[k]['Extract'] in ['false',0]:
                    cDict['Extract'] = 0 
                if securityDict[k]['Extract'] in ['true',1]:
                    cDict['Extract'] = 1
                tmpDict[k] = cDict                
            
            # get a diff between current security settings and the passed security settings
            changed = {}
            for k in tmpDict.keys():
                if not k in self.security.keys():
                    changed[k] = tmpDict[k]   # its a new key
                if k in self.security.keys():
                    if self.security[k]['Render'] != tmpDict[k]['Render']:
                        changed[k] = tmpDict[k]        
            
            self.security = tmpDict        
            # only let the changes be propagated to children 
            
            # get all fields
            fields = []
            items =  self.objectItems()        
            for i in items:
                if i[1].meta_type == 'LayerField':                                
                    fields.append(i[1])                        
            
            for field in fields:
                tmpSec = field.getSecurity()             
                for k in changed.keys():
                    if not tmpSec.has_key(k):
                        tmpSec[k] = {'Render':0}  # add the key if it does not exist
                    tmpSec[k]['Render'] = changed[k]['Render']              
                field.setSecurity(tmpSec)        
            
            self.aq_parent.updateSecurityForSingleLayer(self.uniqueName)        
            return 1        
        except:
            logger.exception('error')
    
    def getSampleImage(self,REQUEST=None):
        """
        @summary: converts the hex encoded image to binary
        @return: sample image in binary format
        """
        try:
            data = binascii.a2b_hex(self.sampleImage) 
            REQUEST.RESPONSE.setHeader("Content-type","image/png")
    
            return data      
        except:
            logger.exception('error')
    
    def pingWMSLayer(self,extent=['23.00','23.00','23.01','23.01']):
        """ 
        """        
        try:
            startTime = time.time()
            layerName = self.wmsName
            source = self.source[1]
            
            layerName = layerName.replace(" ","%20")
            strEnv = "%s,%s,%s,%s" %(extent[0],extent[1],extent[2],extent[3])
            theURL = source + WMS_GETMAP_EXTENSION + "&bbox=%s&styles=&Format=image/png&width=2&height=2&srs=EPSG:4326&layers=%s" %(strEnv,layerName) #"&request=GetLegendGraphic&version=1.0.0&format=%s&width=%s&height=%s&layer=%s" %(format,width,height,layer['wmsName'])        
            data = self._getURLContent(theURL,{})           
            
            if data.find("ServiceExceptionReport") != -1:
                return "Layer Unavailable"
            endTime = time.time()
            return str(endTime - startTime)
        except:
            import traceback
            sio = cStringIO.StringIO()
            traceback.print_exc(file=sio)
            sio.seek(0)
            trace = sio.read()            
            logger.exception('error')
            return MapServerTemplates.ogcServiceException %("Exception occured with _getSampleImage request, check log for details %s" %trace)                            

    def pingWFSLayer(self):
        """
        """        
        if self.hasWFSLayer:
            try:
                startTime = time.time()
                layerName = self.wfsName
                source = self.source[0]                 
                baseURL = source + WFS_DESCRIBEFEATURETYPE_EXTENSION   
                baseURL += "&typename=" + layerName.replace(" ","%20")                 
                data = self._getURLContent(baseURL)    
                
                if (data.find("ServiceException") != -1) or (data.find("ServiceExceptionReport") != -1) or (data.strip() == ""):     
                    return  "Layer Unavailable"  
                
                endTime = time.time()
                return str(endTime - startTime)
            
            except:
                import traceback
                sio = cStringIO.StringIO()
                traceback.print_exc(file=sio)
                sio.seek(0)
                trace = sio.read()
                logger.exception('error')
                return MapServerTemplates.ogcServiceException %("Exception occured with pingWFSLayer request, check log for details %s" %trace)                                   
            
        else:
            return "No WFS Source given."
        
##        if self.hasWFSLayer:
##            try:
##                startTime = time.time()
##                layerName = self.wfsName
##                source = self.source[0]                
##                data = ''
##                baseURL = source + WFS_DESCRIBEFEATURETYPE_EXTENSION
##                baseURL += "&typename=" + layerName.replace(" ","%20") 
##                data = self._getURLContent(baseURL)  
##                if data.find("ServiceExceptionReport") != -1:
##                    return "Layer Unavailable"
##                
##                endTime = time.time()
##                return str(endTime - startTime)
##            except:
##                import traceback
##                sio = cStringIO.StringIO()
##                traceback.print_exc(file=sio)
##                sio.seek(0)
##                trace = sio.read()
##                
##                return MapServerTemplates.ogcServiceException %("Exception occured with pingWFSLayer request, check log for details %s" %trace)                            
##                    
##        else:
##            return "No WFS Source given."
##        
##        return 1
    
    
    def _getURLContent(self,url,data={}):
        """        
        """        
        try:             
            if data:
                if type(data) == unicode:                    
                    data = str(urllib.unquote(data))                                
                if type(data) == str:                    
                    f = urllib.urlopen(url,data)  
                else:
                    params = urllib.urlencode(data)
                    f = urllib.urlopen(url,params) 
            else:
                f = urllib.urlopen(url)        
            data = f.read()
            f.close()        
            return data
        except:
            import traceback
            sio = cStringIO.StringIO()
            traceback.print_exc(file=sio)
            sio.seek(0)
            trace = sio.read()
            logger.exception('error')             
            return MapServerTemplates.ogcServiceException %("Exception occured getURLContent request, check log for details %s" %trace) 
Example #10
0
from Products.ATContentTypes.permission import ChangeTopics


###
# AT Base Criterion
###

ATBaseCriterionSchema = Schema((
    StringField(
        'id',
        required=1,
        mode="r",
        default=None,
        write_permission=ChangeTopics,
        widget=IdWidget(
            label=_(u'label_short_name', default=u'Short Name'),
            description=_(
                u'help_shortname',
                default=u"Should not contain spaces, underscores or mixed "
                u"case. Short Name is part of the item's web address."),
            visible={'view': 'invisible'}
        ),
    ),

    StringField(
        'field',
        required=1,
        mode="r",
        accessor="Field",
        write_permission=ChangeTopics,
        default=None,
Example #11
0
# Constants for enableConstrainMixin.
# Acquire locallyAllowedTypes from parent (default):
ACQUIRE = -1
# Use default behavior of PortalFolder which uses the FTI information:
DISABLED = 0
# Allow types from locallyAllowedTypes only:
ENABLED = 1

# Note: ACQUIRED means get allowable types from parent (regardless of
#  whether it supports IConstrainTypes) but only if parent is the same
#  portal_type (folder within folder). Otherwise, use the global_allow/default
#  behaviour (same as DISABLED).

enableDisplayList = IntDisplayList((
    (ACQUIRE,
     _(u'constraintypes_acquire_label',
       default=u'Use parent folder settings')),
    (DISABLED, _(u'constraintypes_disable_label',
                 default=u'Use portal default')),
    (ENABLED, _(u'constraintypes_enable_label', default=u'Select manually')),
))

ConstrainTypesMixinSchema = Schema((
    IntegerField(
        'constrainTypesMode',
        required=False,
        default_method="_ct_defaultConstrainTypesMode",
        vocabulary=enableDisplayList,
        languageIndependent=True,
        write_permission=ATCTPermissions.ModifyConstrainTypes,
        widget=SelectionWidget(
            label=_(u'label_contrain_types_mode',
        if hasattr(aq_base(instance), blobScalesAttr):
            delattr(aq_base(instance), blobScalesAttr)

##/code-section module-header

schema = Schema((

    TextField('text',
      required=False,
      searchable=True,
      primary=True,
      storage = AnnotationStorage(migrate=True),
      default_output_type = 'text/html',
      widget = RichWidget(
                description = '',
                label = _(u'Text', default=u'Text'),
                rows = 25,
                allow_file_upload = False,
        ),
    ),

    StringField(
        name='external_link',
        widget=StringField._properties['widget'](
        label = _(u'External link', default=u'External link'),
        ),
    ),

    TCExtensionImageBlobField('image',
        sizes = None,
        storage = AnnotationStorage(migrate=True),
Example #13
0
from Products.ATContentTypes import ATCTMessageFactory as _

ATPathCriterionSchema = ATBaseCriterionSchema + Schema((
    ReferenceField('value',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Value",
                mutator="setValue",
                allowed_types_method="getNavTypes",
                multiValued=True,
                keepReferencesOnCopy=True,
                relationship="paths",
                widget=ReferenceBrowserWidget(
                    allow_search=1,
                    label=_(u'label_path_criteria_value', default=u'Folders'),
                    description=_(u'help_path_criteria_value',
                                  default=u'Folders to search in.'),
                    base_query={'is_folderish': True},
                    restrict_browse=True,
                    startup_directory='../')
                ),
    BooleanField('recurse',
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Recurse",
                default=False,
                widget=BooleanWidget(
                    label=_(u'label_path_criteria_recurse', default=u'Search Sub-Folders'),
                    description='',
                    ),
Example #14
0

ATDocumentSchema = 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=TinyMCEWidget(
                description="",
                label=_(u"label_body_text", default=u"Body Text"),
                rows=25,
                allow_file_upload=zconf.ATDocument.allow_document_upload,
            ),
        ),
        BooleanField(
            "tableContents",
            required=False,
            languageIndependent=True,
            widget=BooleanWidget(
                label=_(u"help_enable_table_of_contents", default=u"Table of contents"),
                description=_(
                    u"help_enable_table_of_contents_description",
                    default=u"If selected, this will show a table of contents " u"at the top of the page.",
                ),
            ),
Example #15
0
schema = Schema((
    copied_fields['title'],
    
    MultimediaField('file',
        searchable=True,
        languageIndependent=True,
        validators = (
            ('isNonEmptyFile', V_REQUIRED),
            ('isMaxSize'),
            IsFileExtension("Is Media", content_types=accepted_content_types)
        ),
        widget = MultimediaWidget(
            description = 'You can upload SWF, MP3 and FLV file types.  '
                          'Max file size is %smb.' % (max_file_size),
            label=_(u'label_file', default=u'File'),
            show_content_type = False,
        )
    ),
    ImageField('backgroundImage',
        required = False,
        storage = AnnotationStorage(migrate=True),
        languageIndependent = True,
        sizes= {'large'   : (768, 768),
                'preview' : (400, 400),
                'mini'    : (200, 200),
                'thumb'   : (128, 128),
                'tile'    :  (64, 64),
                'icon'    :  (32, 32),
                'listing' :  (16, 16)
        },
Example #16
0
from Products.ATContentTypes.interfaces import IATEvent
from Products.ATContentTypes.lib.calendarsupport import CalendarSupportMixin
from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.permissions import View
from zope.interface import implementer


ATEventSchema = ATContentTypeSchema.copy() + Schema((
    StringField(
        'location',
        searchable=True,
        write_permission=ModifyPortalContent,
        widget=StringWidget(
            description='',
            label=_(u'label_event_location', default=u'Event Location')
        )
    ),

    DateTimeField(
        'startDate',
        required=True,
        searchable=False,
        accessor='start',
        write_permission=ModifyPortalContent,
        default_method=DateTime,
        languageIndependent=True,
        widget=DatetimeWidget(
            description='',
            label=_(u'label_event_start', default=u'Event Starts')
        )
Example #17
0
from Products.validation.validators.RegexValidator import RegexValidator
from zope.interface import implementer


isPoint = RegexValidator(
    "isPoint",
    r"^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?,([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$",
    title="",
    description="",
    errmsg="is not a pair of decimal numbers.",
)
validation.register(isPoint)

GeoPredicates = DisplayList(
    (
        ("intersection", _(u"Intersection")),
        ("distance", _(u"Distance")),
        ("nearest", _(u"Nearest")),
        #                  , ('min', _(u'Greater than'))
        #                  , ('max', _(u'Less than'))
        #                  , ('min:max', _(u'Between'))
    )
)

GeolocationCriterionSchema = ATBaseCriterionSchema + Schema(
    (
        StringField(
            "lowerLeft",
            required=1,
            mode="rw",
            write_permission=ChangeTopics,
Example #18
0
from Products.CMFCore.permissions import ModifyPortalContent
from Products.Archetypes.Widget import RelatedItemsWidget

# for ATContentTypes we want to have the description in the edit view
# just like CMF
ATContentTypeSchema = BaseSchema.copy() + MetadataSchema(
    (
        BooleanField(
            'excludeFromNav',
            required=False,
            languageIndependent=True,
            schemata='metadata',  # moved to 'default' for folders
            widget=BooleanWidget(
                description=_(
                    u'help_exclude_from_nav',
                    default=
                    u'If selected, this item will not appear in the navigation tree'
                ),
                label=_(u'label_exclude_from_nav',
                        default=u'Exclude from navigation'),
                visible={
                    'view': 'hidden',
                    'edit': 'visible'
                },
            ),
        ), ), )

ATContentTypeSchema['id'].searchable = True
ATContentTypeSchema['id'].validators = ('isValidId', )

# Update the validation layer after change the validator in runtime
Example #19
0
from Products.EasyShop.interfaces import IShop
from Products.EasyShop.interfaces import IImageConversion

schema = 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', default=u'Body Text'),
                        rows = 25,
                        allow_file_upload = zconf.ATDocument.allow_document_upload),
    ),

    StringField(
        name="shopOwner",
        widget=StringWidget(
            label="Shop Owner",
            label_msgid="schema_shop_owner_label",
            description = "",
            description_msgid="schema_shop_owner_description",
            i18n_domain="EasyShop",
        ),
    ),
        
Example #20
0
            delattr(aq_base(instance), blobScalesAttr)


##/code-section module-header

schema = Schema((
    TextField(
        'text',
        required=False,
        searchable=True,
        primary=True,
        storage=AnnotationStorage(migrate=True),
        default_output_type='text/html',
        widget=RichWidget(
            description='',
            label=_(u'Text', default=u'Text'),
            rows=25,
            allow_file_upload=False,
        ),
    ),
    TCExtensionImageBlobField(
        'image',
        sizes=None,
        storage=AnnotationStorage(migrate=True),
        original_size=None,
        default_content_type='image/png',
        allowable_content_types=('image/gif', 'image/jpeg', 'image/png'),
        swallowResizeExceptions=zconf.swallowImageResizeExceptions.enable,
        pil_quality=zconf.pil_config.quality,
        pil_resize_algo=zconf.pil_config.resize_algo,
        widget=ImageWidget(
               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),
                      'thumb': (128, 128),
                      'tile': (64, 64),
                      'icon': (32, 32),
                      'listing': (16, 16),
                     },
               validators=(('isNonEmptyFile', V_REQUIRED),
                           ('checkImageMaxSize', V_REQUIRED)),
               widget=ImageWidget(
                        description='',
                        label=_(u'label_image', default=u'Image'),
                        show_content_type=False,)),

    ), marshall=PrimaryFieldMarshaller()
    )

# Title is pulled from the file name if we don't specify anything,
# so it's not strictly required, unlike in the rest of ATCT.
ATImageSchema['title'].required = False

finalizeATCTSchema(ATImageSchema)


class ATImage(ATCTFileContent, ATCTImageTransform):
    """An image, which can be referenced in documents or displayed in an album."""
Example #22
0
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,
            allow_file_upload = zconf.ATDocument.allow_document_upload)
        ),
    ImageField('image',
        required = False,
        storage = AnnotationStorage(migrate=True),
        languageIndependent = True,
        max_size = zconf.ATNewsItem.max_image_dimension,
        sizes= {'large'   : (768, 768),
                'preview' : (400, 400),
                'mini'    : (200, 200),
                'thumb'   : (128, 128),
                'tile'    :  (64, 64),
                'icon'    :  (32, 32),
                'listing' :  (16, 16),
Example #23
0
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,
               )), ),
    marshall=PrimaryFieldMarshaller())

# Title is pulled from the file name if we don't specify anything,
# so it's not strictly required, unlike in the rest of ATCT.
ATFileSchema['title'].required = False

finalizeATCTSchema(ATFileSchema)


class ATFile(ATCTFileContent):
    """An external file uploaded to the site."""

    schema = ATFileSchema
Example #24
0
""" Overrides default keywords widget
"""
from zope.interface import implements
from archetypes.schemaextender.interfaces import ISchemaModifier
from archetypes.schemaextender.interfaces import IBrowserLayerAwareExtender
from eea.relations.browser.interfaces import IEEARelationsLayer
from eea.relations.widget.referencewidget import EEAReferenceBrowserWidget
from Products.ATContentTypes import ATCTMessageFactory as _

widget = EEAReferenceBrowserWidget(label=_(u'Related Items'),
                                   description='',
                                   visible={
                                       'edit': 'visible',
                                       'view': 'invisible'
                                   },
                                   i18n_domain="plone")


class SchemaModifier(object):
    """ EEA Relations widget
    """
    implements(ISchemaModifier, IBrowserLayerAwareExtender)
    layer = IEEARelationsLayer

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

    def fiddle(self, schema):
        """ Modify schema
        """
        if 'relatedItems' in schema:
Example #25
0
from Products.Archetypes.atapi import IntegerField
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import StringField
from Products.ATContentTypes import ATCTMessageFactory as _
from Products.ATContentTypes.criteria import DATE_INDICES
from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.CMFCore.permissions import View
from zope.interface import implementer

DateOptions = IntDisplayList((
    (0, _(u'Now')),
    (1, _(u'1 Day')),
    (2, _(u'2 Days')),
    (5, _(u'5 Days')),
    (7, _(u'1 Week')),
    (14, _(u'2 Weeks')),
    (31, _(u'1 Month')),
    (31 * 3, _(u'3 Months')),
    (31 * 6, _(u'6 Months')),
    (365, _(u'1 Year')),
    (365 * 2, _(u'2 Years')),
))

CompareOperations = DisplayList((
    ('more', _(u'More than')),
    ('less', _(u'Less than')),
from Products.CMFCore.permissions import View
from Products.CMFCore.utils import getToolByName
from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import FIELD_INDICES
from Products.ATContentTypes.criteria.selection import ATSelectionCriterion
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion

from Products.ATContentTypes import ATCTMessageFactory as _

ATPortalTypeCriterionSchema = ATSelectionCriterion.schema.copy()
# and/or operator makes no sense for type selection, as no item can ever be
# two types at the same time fulfilling an AND condition
ATPortalTypeCriterionSchema.delField("operator")

val_widget = ATPortalTypeCriterionSchema['value'].widget
val_widget.description = _(u'help_portal_type_criteria_value',
                           default=u'One of the available content types.')
ATPortalTypeCriterionSchema['value'].widget = val_widget

VOCAB_ID = u'plone.app.vocabularies.ReallyUserFriendlyTypes'


class ATPortalTypeCriterion(ATSelectionCriterion):
    """A portal_types criterion"""

    implements(IATTopicSearchCriterion)

    security = ClassSecurityInfo()
    schema = ATPortalTypeCriterionSchema
    meta_type = 'ATPortalTypeCriterion'
    archetype_name = 'Portal Types Criterion'
    shortDesc = 'Select content types'
Example #27
0
from plone.app.event.base import default_timezone
from plone.app.event.base import DT
from plone.event.utils import pydt


ATEventSchema = ATContentTypeSchema.copy() + atapi.Schema((

    atapi.DateTimeField('startDate',
        required=True,
        searchable=False,
        accessor='start',
        write_permission=ModifyPortalContent,
        default_method=default_start_DT,
        languageIndependent=True,
        widget=DatetimeWidget(
            label=_(u'label_event_start', default=u'Event Starts'),
            description=_(u'help_start_location', default=u""),
            with_time=1,
            ),
        ),

    atapi.DateTimeField('endDate',
        required=True,
        searchable=False,
        accessor='end',
        write_permission=ModifyPortalContent,
        default_method=default_end_DT,
        languageIndependent=True,
        widget=DatetimeWidget(
            label=_(u'label_event_end', default=u'Event Ends'),
            description=_(u'help_end_location', default=u""),
Example #28
0
from Products.ATContentTypes.criteria import FIELD_INDICES
from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.CMFCore.permissions import View
from zope.interface import implements

ATBooleanCriterionSchema = ATBaseCriterionSchema + Schema((BooleanField(
    'bool',
    required=1,
    mode="rw",
    write_permission=ChangeTopics,
    default=None,
    widget=BooleanWidget(label=_(u'label_boolean_criteria_bool',
                                 default=u'Value'),
                         description=_(u'help_boolean_criteria_bool',
                                       default=u'True or false')),
), ))


class ATBooleanCriterion(ATBaseCriterion):
    """A boolean criterion"""

    implements(IATTopicSearchCriterion)

    security = ClassSecurityInfo()
    schema = ATBooleanCriterionSchema
    meta_type = 'ATBooleanCriterion'
    archetype_name = 'Boolean Criterion'
    shortDesc = 'Boolean (True/False)'
Example #29
0
from zope.interface import implementer

import urlparse

ATLinkSchema = ATContentTypeSchema.copy() + Schema((
    StringField(
        'remoteUrl',
        required=True,
        searchable=True,
        primary=True,
        default="http://",
        # either mailto, absolute url or relative url
        validators=(),
        widget=StringWidget(
            description='',
            label=_(u'label_url', default=u'URL'),
            maxlength='511',
        )), ))
finalizeATCTSchema(ATLinkSchema)


@implementer(IATLink)
class ATLink(ATCTContent):
    """A link to an internal or external resource."""

    schema = ATLinkSchema

    portal_type = 'Link'
    archetype_name = 'Link'
    _atct_newTypeFor = {'portal_type': 'CMF Link', 'meta_type': 'Link'}
    assocMimetypes = ()
Example #30
0
from Products.ATContentTypes.permission import ChangeTopics

from Products.ATContentTypes import ATCTMessageFactory as _

RELEVANT_INDICES=list(DATE_INDICES)
RELEVANT_INDICES.remove('DateRangeIndex')
RELEVANT_INDICES = tuple(RELEVANT_INDICES)

ATDateRangeCriterionSchema = ATBaseCriterionSchema + Schema((
    DateTimeField('start',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                default=None,
                widget=CalendarWidget(
                    label=_(u'label_date_range_criteria_start', default=u'Start Date'),
                    description=_(u'help_date_range_criteria_start',
                                  default=u'The beginning of the date range to search')
                    ),
                ),
    DateTimeField('end',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                default=None,
                widget=CalendarWidget(
                    label=_(u'label_date_range_criteria_end', default=u'End Date'),
                    description=_(u'help_date_range_criteria_end',
                                  default=u'The ending of the date range to search.')

                    ),
Example #31
0
ActionListSchema = ATContentTypeSchema.copy() + atapi.Schema(
    (ReferenceField('service',
                    relationship='forService',
                    multiValued=False,
                    languageIndependent=True,
                    write_permission=ModifyPortalContent,
                    widget=ReferenceBrowserWidget(
                        allow_search=True,
                        allow_browse=True,
                        show_indexes=False,
                        show_path=1,
                        force_close_on_insert=True,
                        startup_directory='/catalog',
                        base_query={'portal_type': 'Service'},
                        label=_(u'label_service', default=u'Related service'),
                        description='',
                        visible={
                            'edit': 'visible',
                            'view': 'invisible'
                        })),
     ReferenceField('actionItems',
                    relationship='hasActionItem',
                    multiValued=True,
                    isMetadata=True,
                    languageIndependent=False,
                    index='KeywordIndex',
                    write_permission=ModifyPortalContent,
                    widget=ReferenceBrowserWidget(
                        allow_search=True,
                        allow_browse=True,
Example #32
0
class MapServer(BaseFolder):
    '''Map Server for CoGIS'''
    schema = BaseFolderSchema

    schema = BaseSchema + Schema([
        StringField('description',
                    required=False,
                    searchable=1,
                    widget=StringWidget(
                        label='Description',
                        description="Enter project description")),
        ReferenceField('relatedItems',
                       relationship='relatesTo',
                       multiValued=True,
                       isMetadata=True,
                       languageIndependent=False,
                       index='KeywordIndex',
                       write_permission=ModifyPortalContent,
                       widget=ReferenceBrowserWidget(
                           allow_search=True,
                           allow_browse=True,
                           show_indexes=False,
                           force_close_on_insert=True,
                           label=_(u'label_related_items',
                                   default=u'Related Items'),
                           description='',
                           visible={
                               'edit': 'visible',
                               'view': 'invisible'
                           }))
    ], )

    actions = (
        {
            'id': 'publish',
            'name': 'Publish',
            'action': 'string:${object_url}/Map_Server_PublishAll',
            'permissions': (permissions.ViewManagementScreens, )
        },
        {
            'id': 'pingServer',
            'name': 'Ping Server',
            'action': 'string:${object_url}/Map_Server_PingServer',
            'permissions': (permissions.ViewManagementScreens, )
        },
        {
            'id': 'licenseAgreement',
            'name': 'License Agreement',
            'action': 'string:${object_url}/Map_Server_LicenseAgreement_Edit',
            'permissions': (permissions.ViewManagementScreens, )
        },
    )

    #schema = schema + extra_schema
    content_icon = "mapServer.gif"
    security = ClassSecurityInfo()

    archetype_name = 'MapServer'
    meta_type = 'MapServer'
    portal_type = 'MapServer'
    allowed_content_types = []  #['MapLayer']
    filter_content_types = 1
    global_allow = 0
    allow_discussion = 0
    content_icon = "mapServer.gif"

    def __init__(self, id, title=''):
        '''Initialize an instance of the class'''
        self.id = id
        if title == '':
            self.title = id
        else:
            self.title = title

        self.organization = ""
        self.wmsSource = ""
        self.wfsSource = ""
        self.enableLicenseAgreement = False
        # licenseAgreent is the text to display in the tbx
        self.licenseAgreement = "Put the license text here \nPlease read license before publishing"
        # its a list of usernames that have accepted the license agreement
        self.acceptedUserNames = []

    def dummyTest(self):
        """
        """
        return dir(self)

    def updateLicenseAgreement(self, REQUEST=None):
        """
        @summary: udpate the server license agreement and disables/enables the agreement
        """
        try:
            self.acceptedUserNames = []

            if REQUEST.has_key('enableIt'):
                enable = True
            else:
                enable = False

            licenseText = REQUEST.form['licenseText']

            self.enableLicenseAgreement = enable
            self.licenseAgreement = licenseText

            self._p_changed = 1
            transaction.savepoint(True)

            status_message = "License Agreement Updated"

            REQUEST.RESPONSE.redirect(
                "%s/Map_Server_LicenseAgreement_Edit?portal_status_message=%s"
                % (self.absolute_url(), status_message))
        except:
            logger.exception('failed updateLicenseAgreement')

    security.declarePublic('userIsOwner')

    def userIsOwner(self):
        """
        @summary: this is a zope specific method to get logged in user name
        @return: boolean, true if logged in user is the owner
        """
        try:
            ownerName = self.owner_info()['id']
            member = self.portal_membership.getAuthenticatedMember()
            userName = member.getUserName()
            if userName == ownerName:
                return True
            else:
                return False
        except:
            logger.exception('failed user is owner')

    def publishLayersForRoles(self, rolesToPublish):
        """
        @summary : publishes layer for the given roles passed
        @param   : a list of roles to publish layers for
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getPublishedStructureForRoles(rolesToPublish))
            return 1
        except:
            logger.exception('failed publishLayersForRoles')

    def publishAllLayers(self):
        """
        @summary: this will publish all the layers in the server
        @return: 1
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getPublishedSecurityStructure())
            return 1
        except:
            logger.exception('failed publishAllLayers')

    def retractAllLayers(self):
        """
        @summary: this will retract all the layers in the server
        @return: 1
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getRetractedSecurityStructure())
            return 1
        except:
            logger.exception('failed retractAllLayers')

    def pingServer(self):
        """
        """
        try:
            startTime = time.time()
            wmsPingRes = self._getURLContent(self.wmsSource)
            endTime = time.time()
            wmsTime = endTime - startTime
            if wmsPingRes.find("Exception occured") != -1:
                wmsTime = "Server Unavailable"

            startTime = time.time()
            wfsPingRes = self._getURLContent(self.wfsSource)
            endTime = time.time()
            wfsTime = endTime - startTime
            if wfsPingRes.find("Exception occured") != -1:
                wfsTime = "Server Unavailable"

            return [str(wfsTime), str(wmsTime)]
        except:
            logger.exception('failed pingServer')

    def pingAllLayers(self):
        """
        """
        try:
            results = {}
            items = self.objectItems()
            for i in items:
                layer = i[1]
                pingResWMS = layer.pingWMSLayer()
                pingResWFS = layer.pingWFSLayer()
                results[layer.uniqueName] = [pingResWFS, pingResWMS]
            return results
        except:
            logger.exception('error')

    def getPublishedSecurityStructure(self):
        """
        @summary: builds a security structure that will expose all layers
        @return: a dictionary with all the roles as keys and another dict as value
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                tmpDict[role] = {'Render': 1, 'Extract': 1}
            return tmpDict
        except:
            logger.exception('failed getPublishedSercurityStructure')

    def getPublishedStructureForRoles(self, theRoles):
        """
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                if role in theRoles:
                    tmpDict[role] = {'Render': 1, 'Extract': 1}
                else:
                    tmpDict[role] = {'Render': 0, 'Extract': 0}
            return tmpDict
        except:
            logger.exception('Error')

    def getRetractedSecurityStructure(self):
        """
        @summary: builds a security structure that will expose all layers
        @return: a dictionary with all the roles as keys and another dict as value
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                tmpDict[role] = {'Render': 0, 'Extract': 0}
            return tmpDict
        except:
            logger.exception('Error')

    def _getURLContent(self, url, data={}):
        """        
        """
        try:
            if data:
                if type(data) == unicode:
                    data = str(urllib.unquote(data))
                if type(data) == str:
                    f = urllib.urlopen(url, data)
                else:
                    params = urllib.urlencode(data)
                    f = urllib.urlopen(url, params)
            else:
                f = urllib.urlopen(url)
            data = f.read()
            f.close()
            return data
        except:
            import traceback
            sio = StringIO.StringIO()
            traceback.print_exc(file=sio)
            sio.seek(0)
            trace = sio.read()
            logger.exception('Error')
            return MapServerTemplates.ogcServiceException % (
                "Exception occured getURLContent request, check log for details %s"
                % trace)
Example #33
0
from zope.interface import implements

ATPathCriterionSchema = ATBaseCriterionSchema + Schema((
    ReferenceField('value',
                   required=1,
                   mode="rw",
                   write_permission=ChangeTopics,
                   accessor="Value",
                   mutator="setValue",
                   allowed_types_method="getNavTypes",
                   multiValued=True,
                   keepReferencesOnCopy=True,
                   relationship="paths",
                   widget=RelatedItemsWidget(
                       allow_search=1,
                       label=_(u'label_path_criteria_value',
                               default=u'Folders'),
                       description=_(u'help_path_criteria_value',
                                     default=u'Folders to search in.'),
                       base_query={'is_folderish': True},
                       restrict_browse=True,
                       startup_directory='../')),
    BooleanField(
        'recurse',
        mode="rw",
        write_permission=ChangeTopics,
        accessor="Recurse",
        default=False,
        widget=BooleanWidget(
            label=_(u'label_path_criteria_recurse',
                    default=u'Search Sub-Folders'),
            description='',
Example #34
0
        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),
            'thumb': (128, 128),
            'tile': (64, 64),
            'icon': (32, 32),
            'listing': (16, 16),
        },
        validators=(('isNonEmptyFile', V_REQUIRED),
                    ('checkImageMaxSize', V_REQUIRED)),
        widget=ImageWidget(
            description='',
            label=_(u'label_image', default=u'Image'),
            show_content_type=False,
        )), ),
    marshall=PrimaryFieldMarshaller())

# Title is pulled from the file name if we don't specify anything,
# so it's not strictly required, unlike in the rest of ATCT.
ATImageSchema['title'].required = False

finalizeATCTSchema(ATImageSchema)


@implementer(IATImage)
class ATImage(ATCTFileContent, ATCTImageTransform):
    """An image, which can be referenced in documents.
Example #35
0
]

ATTopicSchema = 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", default=u"Body Text"),
                rows=25,
                allow_file_upload=zconf.ATDocument.allow_document_upload,
            ),
        ),
        BooleanField(
            "acquireCriteria",
            required=False,
            mode="rw",
            default=False,
            write_permission=ModifyPortalContent,
            widget=BooleanWidget(
                label=_(u"label_inherit_criteria", default=u"Inherit Criteria"),
                description=_(
                    u"help_inherit_collection_criteria",
                    default=u"Narrow down the search results from the parent Collection(s) "
Example #36
0
from Products.mediaWork.interfaces import IWork
from Products.mediaWork.config import PROJECTNAME

WorkSchema = folder.ATFolderSchema.copy() + document.ATDocumentSchema.copy() + atapi.Schema((

    # -*- Your Archetypes field definitions here ... -*-
    DateTimeField('date',
        required=False,
        searchable=False,
        accessor='date',
        write_permission = ModifyPortalContent,
        default_method=None,
        languageIndependent=True,
        widget = CalendarWidget(
              description= '',
              label=_(u'label_date', default=u'Date'),
              starting_year = 1900
              )),
))

# Set storage on fields copied from ATFolderSchema, making sure
# they work well with the python bridge properties.

WorkSchema['title'].storage = atapi.AnnotationStorage()
WorkSchema['description'].storage = atapi.AnnotationStorage()
WorkSchema['text'].storage = atapi.AnnotationStorage()
WorkSchema['date'].storage = atapi.AnnotationStorage()

WorkSchema.moveField('date', before='text')

schemata.finalizeATCTSchema(
Example #37
0
from Products.ATContentTypes.interfaces import IATDocument

from Products.ATContentTypes import ATCTMessageFactory as _

ATDocumentSchema = 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', default=u'Body Text'),
                        rows=25,
                        allow_file_upload=zconf.ATDocument.allow_document_upload),
    ),

    BooleanField('presentation',
        required=False,
        languageIndependent=True,
        widget=BooleanWidget(
            label=_(
                u'help_enable_presentation',
                default=u'Presentation mode'),
            description=_(
                u'help_enable_presentation_description',
                default=u'If selected, this will give users the ability to view the contents as presentation slides.')
            ),
Example #38
0
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import LinesWidget
from Products.Archetypes.atapi import DisplayList

from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import LIST_INDICES
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics

from Products.ATContentTypes import ATCTMessageFactory as _

CompareOperators = DisplayList((
    ('and', _(u'and')),
    ('or', _(u'or')),
    ))

ATListCriterionSchema = ATBaseCriterionSchema + Schema((
    LinesField('value',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Value",
                mutator="setValue",
                default=[],
                widget=LinesWidget(
                    label=_(u'label_list_criteria_value', default=u'Values'),
                    description=_(u'help_list_criteria_value',
                                  default=u'Values, each on its own line.')
Example #39
0
from Products.Archetypes.atapi import LinesField
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import LinesWidget
from Products.Archetypes.atapi import DisplayList

from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import LIST_INDICES
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics

from Products.ATContentTypes import ATCTMessageFactory as _

CompareOperators = DisplayList((('and', _(u'and')), ('or', _(u'or'))))

ATListCriterionSchema = ATBaseCriterionSchema + Schema((
    LinesField(
        'value',
        required=1,
        mode="rw",
        write_permission=ChangeTopics,
        accessor="Value",
        mutator="setValue",
        default=[],
        widget=LinesWidget(
            label=_(u'label_list_criteria_value', default=u'Values'),
            description=_(u'help_list_criteria_value',
                          default=u'Values, each on its own line.')),
    ),
        default = '',
        searchable = 1,
        accessor = "Description",
        schemata = 'default',
        widget = TextAreaWidget(
            visible = {'view': 'visible', 'edit': 'invisible'},
            label=PMF(u'label_description', default=u'Description'),
            description=PMF(u'help_description', default=u'A short summary of the content'),
        ),
    ),

    FileField(
        name = 'vdex',
        allowable_content_types = ["text/xml"],
        widget = FileWidget(
            label=_(u'IMSVDEXVocabulary_label_vdex', default=u'VDEX-XML-Data'),
            description=_(u'IMSVDEXVocabulary_description_vdex', 
                            default=u'upload the IMS Vocabulary Definition Format '
                            'compliant XML file into this text field.'),
            allow_file_upload = True,
        ),
        default_output_type = "text/plain",
        default_content_type = "text/xml"
    ),
    BooleanField(
        name = 'showTermPath',
        default = True,
        widget = BooleanWidget(
            label=_(u'label_showTermPath', default=u'Show Term Path'),
            visible = {'view': 'visible', 'edit': 'visible'},
        ),
Example #41
0
from Products.Archetypes.atapi import BooleanField
from Products.Archetypes.atapi import BooleanWidget
from Products.ATContentTypes import ATCTMessageFactory as _
from Products.CMFCore.permissions import ModifyPortalContent

from archetypes.referencebrowserwidget import ReferenceBrowserWidget

# for ATContentTypes we want to have the description in the edit view
# just like CMF
ATContentTypeSchema = BaseSchema.copy() + MetadataSchema((
    BooleanField('excludeFromNav',
        required = False,
        languageIndependent = True,
        schemata = 'metadata', # moved to 'default' for folders
        widget = BooleanWidget(
            description=_(u'help_exclude_from_nav', default=u'If selected, this item will not appear in the navigation tree'),
            label = _(u'label_exclude_from_nav', default=u'Exclude from navigation'),
            visible={'view' : 'hidden',
                     'edit' : 'visible'},
            ),
        ),
    ),)

ATContentTypeSchema['id'].searchable = True
ATContentTypeSchema['id'].validators = ('isValidId',)

# Update the validation layer after change the validator in runtime
ATContentTypeSchema['id']._validationLayer()

ATContentTypeSchema['description'].schemata = 'default'
Example #42
0
from Products.ATContentTypes import ATCTMessageFactory as _
from Products.ATContentTypes.permission import ChangeTopics

###
# AT Base Criterion
###

ATBaseCriterionSchema = Schema((
    StringField(
        'id',
        required=1,
        mode="r",
        default=None,
        write_permission=ChangeTopics,
        widget=IdWidget(
            label=_(u'label_short_name', default=u'Short Name'),
            description=_(
                u'help_shortname',
                default=u"Should not contain spaces, underscores or mixed "
                u"case. Short Name is part of the item's web address."),
            visible={'view': 'invisible'}),
    ),
    StringField(
        'field',
        required=1,
        mode="r",
        accessor="Field",
        write_permission=ChangeTopics,
        default=None,
        widget=StringWidget(
            label=_(u'label_criteria_field_name', default=u'Field name'),
Example #43
0
]

ATTopicSchema = 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',
        write_permission=ChangeTopics,
        widget=RichWidget(
            description='',
            label=_(u'label_body_text', default=u'Body Text'),
            rows=25,
            allow_file_upload=zconf.ATDocument.allow_document_upload),
    ),
    BooleanField(
        'acquireCriteria',
        required=False,
        mode="rw",
        default=False,
        write_permission=ChangeTopics,
        widget=BooleanWidget(
            label=_(u'label_inherit_criteria', default=u'Inherit Criteria'),
            description=_(
                u'help_inherit_collection_criteria',
                default=
                u"Narrow down the search results from the parent Collection(s) "
# the following code is based on the rotation code of Photo
if HAS_PIL:
    import PIL.Image

LOG = logging.getLogger('ATCT.image')

# transpose constants, taken from PIL.Image to maintain compatibilty
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
ROTATE_90 = 2
ROTATE_180 = 3
ROTATE_270 = 4

TRANSPOSE_MAP = {
    FLIP_LEFT_RIGHT: _(u'Flip around vertical axis'),
    FLIP_TOP_BOTTOM: _(u'Flip around horizontal axis'),
    ROTATE_270: _(u'Rotate 90 clockwise'),
    ROTATE_180: _(u'Rotate 180'),
    ROTATE_90: _(u'Rotate 90 counterclockwise'),
}

AUTO_ROTATE_MAP = {
    0: None,
    90: ROTATE_270,
    180: ROTATE_180,
    270: ROTATE_90,
}


class ATCTImageTransform(Base):
Example #45
0
from Products.CMFCore.permissions import View
from zope.interface import implements

RELEVANT_INDICES = list(DATE_INDICES)
RELEVANT_INDICES.remove('DateRangeIndex')
RELEVANT_INDICES = tuple(RELEVANT_INDICES)

ATDateRangeCriterionSchema = ATBaseCriterionSchema + Schema((
    DateTimeField(
        'start',
        required=1,
        mode="rw",
        write_permission=ChangeTopics,
        default=None,
        widget=CalendarWidget(
            label=_(u'label_date_range_criteria_start', default=u'Start Date'),
            description=_(
                u'help_date_range_criteria_start',
                default=u'The beginning of the date range to search')),
    ),
    DateTimeField(
        'end',
        required=1,
        mode="rw",
        write_permission=ChangeTopics,
        default=None,
        widget=CalendarWidget(
            label=_(u'label_date_range_criteria_end', default=u'End Date'),
            description=_(u'help_date_range_criteria_end',
                          default=u'The ending of the date range to search.')),
    ),
Example #46
0
from ZPublisher.HTTPRequest import HTTPRequest

ATDocumentSchema = 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=TinyMCEWidget(
                description='',
                label=_(u'label_body_text', default=u'Body Text'),
                rows=25,
                allow_file_upload=zconf.ATDocument.allow_document_upload),
        ),
        BooleanField(
            'tableContents',
            required=False,
            languageIndependent=True,
            widget=BooleanWidget(
                label=_(u'help_enable_table_of_contents',
                        default=u'Table of contents'),
                description=_(
                    u'help_enable_table_of_contents_description',
                    default=u'If selected, this will show a table of contents '
                    u'at the top of the page.')),
        )),
Example #47
0
    # 'portal_type' # portal type and Type might differ!
    ]

ATTopicSchema = 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',
              write_permission=ChangeTopics,
              widget=RichWidget(
                    description='',
                    label=_(u'label_body_text', default=u'Body Text'),
                    rows=25,
                    allow_file_upload=zconf.ATDocument.allow_document_upload),
    ),
    BooleanField('acquireCriteria',
                required=False,
                mode="rw",
                default=False,
                write_permission=ChangeTopics,
                widget=BooleanWidget(
                        label=_(u'label_inherit_criteria', default=u'Inherit Criteria'),
                        description=_(u'help_inherit_collection_criteria',
                                      default=u"Narrow down the search results from the parent Collection(s) "
                                               "by using the criteria from this Collection."),
                        # Only show when the parent object is a Topic also,
                        condition="python:object.aq_parent.portal_type == 'Topic'"),
Example #48
0
TodoItemSchema = BaseSchema + Schema((

    StringField('responsibleParty',
        index="FieldIndex:schema",
        widget=SelectionWidget(),
    ),

    DateTimeField('endDate',
                  required=True,
                  searchable=False,
                  accessor='end',
                  #default_method=DateTime,
                  widget = CalendarWidget(
                        description = '',
                        label = _(u'label_event_end', default=u'Event Ends')
                        )),
    relatedItemsField,
    # BooleanField('notify'),

    ))

class TodoItem(BaseContent):
    """ todo  item """
    implements(ITodoItemContent)

    schema = TodoItemSchema

    def Description(self):
        return self.aq_inner.aq_parent.Title()
Example #49
0
from Products.Archetypes.atapi import MultiSelectionWidget
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import DisplayList

from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import LIST_INDICES
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema

from Products.ATContentTypes import ATCTMessageFactory as _

CompareOperators = DisplayList((
                    ('and', _(u'and'))
                  , ('or', _(u'or'))
    ))

ATSelectionCriterionSchema = ATBaseCriterionSchema + Schema((
    LinesField('value',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Value",
                mutator="setValue",
                default=[],
                vocabulary="getCurrentValues",
                widget=MultiSelectionWidget(
                    label=_(u'label_criteria_values', default=u'Values'),
                    description=_(u'help_criteria_values', default=u'Existing values.')
                     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,
                allow_file_upload=zconf.ATDocument.allow_document_upload)),
        ImageField(
            'image',
            required=False,
            storage=AnnotationStorage(migrate=True),
            languageIndependent=True,
            max_size=zconf.ATNewsItem.max_image_dimension,
            sizes={
                'large': (768, 768),
                'preview': (400, 400),
                'mini': (200, 200),
                'thumb': (128, 128),
                'tile': (64, 64),
                'icon': (32, 32),
from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import SORT_INDICES
from Products.ATContentTypes.interfaces import IATTopicSortCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema

from Products.ATContentTypes import ATCTMessageFactory as _

ATSortCriterionSchema = ATBaseCriterionSchema + Schema((BooleanField(
    'reversed',
    required=0,
    mode="rw",
    write_permission=ChangeTopics,
    default=0,
    widget=BooleanWidget(label=_(u'Reverse')),
), ))


class ATSortCriterion(ATBaseCriterion):
    """A sort criterion"""

    implements(IATTopicSortCriterion)
    security = ClassSecurityInfo()
    schema = ATSortCriterionSchema
    meta_type = 'ATSortCriterion'
    archetype_name = 'Sort Criterion'
    shortDesc = 'Sort'

    security.declareProtected(View, 'getCriteriaItems')
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATEvent
from Products.ATContentTypes.lib.calendarsupport import CalendarSupportMixin
from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin

from Products.ATContentTypes import ATCTMessageFactory as _

ATEventSchema = ATContentTypeSchema.copy() + Schema((
    StringField('location',
                searchable=True,
                write_permission=ModifyPortalContent,
                widget=StringWidget(description='',
                                    label=_(u'label_event_location',
                                            default=u'Event Location'))),
    DateTimeField('startDate',
                  required=True,
                  searchable=False,
                  accessor='start',
                  write_permission=ModifyPortalContent,
                  default_method=DateTime,
                  languageIndependent=True,
                  widget=CalendarWidget(description='',
                                        label=_(u'label_event_start',
                                                default=u'Event Starts'))),
    DateTimeField('endDate',
                  required=True,
                  searchable=False,
                  accessor='end',
                  write_permission=ModifyPortalContent,
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.base import registerATCT

from Products.Archetypes.atapi import Schema, LinesField, DisplayList
from zope.interface import implements

from my.test.content.interfaces import IATTestContent

from abstract.widgets.multitree.widget import MultiTreeWidget
from AccessControl import ClassSecurityInfo


ATTestContentSchema = ATContentTypeSchema.copy() + Schema((
    LinesField('myfield',
                widget=MultiTreeWidget(
                label=_(u'My Label'),
                description=_(u'My long description My long description My long description My long description '),
                singleshot_overlay=True,
                sources=[('my.vocabolary.source',_(u"Source1")),('my.vocabolary.source2',_(u"Source2"))])),
))


finalizeATCTSchema(ATTestContentSchema)

class ATTestContent(ATCTContent):

    """A page in the site. Can contain rich text."""

    schema         =  ATTestContentSchema

    meta_type = portal_type    = 'ATTestContent'
Example #54
0
from Products.Archetypes.atapi import IntegerWidget
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import DisplayList

from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import LIST_INDICES
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema

from Products.ATContentTypes import ATCTMessageFactory as _

DirectionOperations = DisplayList((
                    ('', _(u'Equal to'))
                  , ('min', _(u'Greater than'))
                  , ('max', _(u'Less than'))
                  , ('min:max', _(u'Between'))
    ))

ATSimpleIntCriterionSchema = ATBaseCriterionSchema + Schema((
    IntegerField('value',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Value",
                mutator="setValue",
                default=None,
                widget=IntegerWidget(
                    label=_(u'label_int_criteria_value', default=u'Value'),
Example #55
0
from Products.ATContentTypes import permission as ATCTPermissions

from Products.ATContentTypes.interfaces import ISelectableConstrainTypes

# constants for enableConstrainMixin
ACQUIRE = -1  # acquire locallyAllowedTypes from parent (default)
DISABLED = 0  # use default behavior of PortalFolder which uses the FTI information
ENABLED = 1  # allow types from locallyAllowedTypes only

# Note: ACQUIRED means get allowable types from parent (regardless of
#  whether it supports IConstrainTypes) but only if parent is the same
#  portal_type (folder within folder). Otherwise, use the global_allow/default
#  behaviour (same as DISABLED).

enableDisplayList = IntDisplayList((
    (ACQUIRE, _(u'constraintypes_acquire_label', default=u'Use parent folder settings')),
    (DISABLED, _(u'constraintypes_disable_label', default=u'Use portal default')),
    (ENABLED, _(u'constraintypes_enable_label', default=u'Select manually')),
    ))

ConstrainTypesMixinSchema = Schema((
    IntegerField('constrainTypesMode',
        required=False,
        default_method="_ct_defaultConstrainTypesMode",
        vocabulary=enableDisplayList,
        languageIndependent=True,
        write_permission=ATCTPermissions.ModifyConstrainTypes,
        widget=SelectionWidget(
            label=_(u'label_contrain_types_mode',
                    default=u'Constrain types mode'),
            description=_(u'description_constrain_types_mode',
Example #56
0
from Products.Archetypes.atapi import IntegerWidget
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import StringField
from Products.ATContentTypes import ATCTMessageFactory as _
from Products.ATContentTypes.criteria import LIST_INDICES
from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics
from Products.CMFCore.permissions import View
from zope.interface import implementer

DirectionOperations = DisplayList((
    ('', _(u'Equal to')),
    ('min', _(u'Greater than')),
    ('max', _(u'Less than')),
    ('min:max', _(u'Between')),
))

ATSimpleIntCriterionSchema = ATBaseCriterionSchema + Schema((
    IntegerField(
        'value',
        required=1,
        mode="rw",
        write_permission=ChangeTopics,
        accessor="Value",
        mutator="setValue",
        default=None,
        widget=IntegerWidget(label=_(u'label_int_criteria_value',
Example #57
0
from Products.ATContentTypes.permission import ChangeTopics
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema

from Products.ATContentTypes import ATCTMessageFactory as _

ATSimpleStringCriterionSchema = ATBaseCriterionSchema + Schema((
    StringField('value',
                required=1,
                mode="rw",
                write_permission=ChangeTopics,
                accessor="Value",
                mutator="setValue",
                default="",
                widget=StringWidget(
                    label=_(u'label_string_criteria_value', default=u'Value'),
                    description=_(u'help_string_criteria_value',
                                  default=u'A string value.'))
                ),
    ))


class ATSimpleStringCriterion(ATBaseCriterion):
    """A simple string criterion"""

    __implements__ = ATBaseCriterion.__implements__ + (IATTopicSearchCriterion, )
    security       = ClassSecurityInfo()
    schema         = ATSimpleStringCriterionSchema
    meta_type      = 'ATSimpleStringCriterion'
    archetype_name = 'Simple String Criterion'
    shortDesc      = 'Text'
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATLink

from Products.ATContentTypes import ATCTMessageFactory as _

ATLinkSchema = ATContentTypeSchema.copy() + Schema((
    StringField('remoteUrl',
        required=True,
        searchable=True,
        primary=True,
        default="http://",
        # either mailto, absolute url or relative url
        validators=(),
        widget=StringWidget(
            description='',
            label=_(u'label_url', default=u'URL'),
            maxlength='511',
            )),
    ))
finalizeATCTSchema(ATLinkSchema)


class ATLink(ATCTContent):
    """A link to an internal or external resource."""

    schema = ATLinkSchema

    portal_type = 'Link'
    archetype_name = 'Link'
    _atct_newTypeFor = {'portal_type': 'CMF Link', 'meta_type': 'Link'}
    assocMimetypes = ()
Example #59
0
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import DisplayList
from Products.Archetypes.atapi import IntDisplayList

from Products.ATContentTypes.criteria import registerCriterion
from Products.ATContentTypes.criteria import DATE_INDICES
from Products.ATContentTypes.criteria.base import ATBaseCriterion
from Products.ATContentTypes.criteria.schemata import ATBaseCriterionSchema
from Products.ATContentTypes.interfaces import IATTopicSearchCriterion
from Products.ATContentTypes.permission import ChangeTopics

from Products.ATContentTypes import ATCTMessageFactory as _

DateOptions = IntDisplayList((
                    (     0, _(u'Now')      )
                  , (     1, _(u'1 Day')    )
                  , (     2, _(u'2 Days')   )
                  , (     5, _(u'5 Days')   )
                  , (     7, _(u'1 Week')   )
                  , (    14, _(u'2 Weeks')  )
                  , (    31, _(u'1 Month')  )
                  , (  31*3, _(u'3 Months') )
                  , (  31*6, _(u'6 Months') )
                  , (   365, _(u'1 Year')   )
                  , ( 365*2, _(u'2 Years')  )
    ))

CompareOperations = DisplayList((
                    ('more', _(u'More than'))
                  , ('less', _(u'Less than'))