def test_finalize_schema_additional_hide(self):
        schema = ATContentTypeSchema.copy()
        finalize(schema, hide=['title'])

        self.assertEquals(ManagePortal, schema['title'].write_permission)
        self.assertEquals({'view': 'invisible', 'edit': 'invisible'},
                          schema['title'].widget.visible)
    def test_finalize_schema_do_not_hide(self):
        schema = ATContentTypeSchema.copy()
        finalize(schema, show=['subject'])

        self.assertNotEqual(ManagePortal, schema['subject'].write_permission)
        self.assertNotEquals({'view': 'invisible', 'edit': 'invisible'},
                             schema['subject'].widget.visible)
    def test_finalize_schema(self):
        schema = ATContentTypeSchema.copy()
        finalize(schema)

        for name in DEFAULT_TO_HIDE:
            if name in schema:
                self.assertEquals(ManagePortal, schema[name].write_permission)
                self.assertEquals({'view': 'invisible', 'edit': 'invisible'},
                                  schema[name].widget.visible)

        self.assertTrue(schema['excludeFromNav'].default)
class Foo(ATCTContent):
    """ sample content type for testing purposes """

    schema = ATContentTypeSchema.copy()
    portal_type = 'Foo'
    index_counter = 0

    def indexObject(self):
        """ overridden index method calling its super variant """
        super(Foo, self).indexObject()
        self.index_counter += 1
        assert self.index_counter < 42, 'indexing loop detected'
from Products.ZMetadata.config import *
from Products.ATContentTypes.content.schemata import ATContentTypeSchema

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#LogContainer_schema = BaseFolderSchema.copy() + schema.copy()
LogContainer_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class LogContainer(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'LogContainer'

    meta_type = 'LogContainer'
    portal_type = 'LogContainer'
from Products.ZMetadata.config import *
from Products.ATContentTypes.content.schemata import ATContentTypeSchema

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Archive_schema = BaseFolderSchema.copy() +  schema.copy()
Archive_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class Archive(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'Archive'

    meta_type = 'Archive'
    portal_type = 'Archive'
Exemple #7
0
from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from zope.interface import implements
from Products.FacultyStaffDirectory.interfaces.facultystaffdirectory import IFacultyStaffDirectory
from Products.FacultyStaffDirectory.config import *
from Products.CMFCore.permissions import View, ManageUsers
from Products.CMFCore.utils import getToolByName
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema, finalizeATCTSchema
from Products.membrane.at.interfaces import IPropertiesProvider
from Products.membrane.utils import getFilteredValidRolesForPortal
from Acquisition import aq_inner, aq_parent
from Products.FacultyStaffDirectory import FSDMessageFactory as _

schema = ATContentTypeSchema.copy() + Schema((
    LinesField(
        'roles_',
        accessor='getRoles',
        mutator='setRoles',
        edit_accessor='getRawRoles',
        vocabulary='getRoleSet',
        default=['Member'],
        multiValued=1,
        write_permission=ManageUsers,
        widget=MultiSelectionWidget(
            label=_("FacultyStaffDirectory_label_FacultyStaffDirectoryRoles",
                    default="Roles"),
            description=_(
                "FacultyStaffDirectory_description_FacultyStaffDirectoryRoles",
                default=
Exemple #8
0
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.configuration import zconf

from Products.PloneFormGen.config import PROJECTNAME
from Products.PloneFormGen.interfaces import IPloneFormGenThanksPage

from Products.PloneFormGen import PloneFormGenMessageFactory as _
from Products.PloneFormGen import HAS_PLONE30, dollarReplace
from Products.PloneFormGen import implementedOrProvidedBy

import zope.i18n


ThanksPageSchema = ATContentTypeSchema.copy() + Schema((
    BooleanField('showAll',
        required=0,
        searchable=0,
        default='1',
        widget=BooleanWidget(
            label="Show All Fields",
            description="""
                Check this to display input for all fields
                (except label and file fields). If you check
                this, the choices in the pick box below
                will be ignored.
                """,
            label_msgid = "label_showallfields_text",
            description_msgid = "help_showallfields_text",
            i18n_domain = "ploneformgen",
                                    default=u"Options Vocabulary"),
            description=_(u'help_fgtvocabulary_text', default=u"""
                A TALES expression that will be evaluated when the form is displayed
                to get the field options.
                Leave empty if unneeded.
                Your TALES expression should evaluate as a list of (key, value) tuples.
                PLEASE NOTE: errors in the evaluation of this expression will cause
                an error on form display.
            """),
            size=70,
            ),
        )

# establish a bare baseline
# only label field uses this without change
BareFieldSchema = ATContentTypeSchema.copy()
BareFieldSchema['title'].searchable = False
BareFieldSchema['title'].widget.label = _(u'label_fieldlabel_text', default=u'Field Label')
BareFieldSchema['description'].searchable = False
BareFieldSchema['description'].widget.label = _(u'label_fieldhelp_text', default=u'Field Help')
BareFieldSchema['description'].widget.description = None

###
# BaseFieldSchema -- more common baseline
# Used as a base schema for several fields

BaseFieldSchema = BareFieldSchema.copy() + Schema((
        BooleanField('required',
            searchable=0,
            required=0,
            widget=BooleanWidget(
class CustomMigrationForm(BrowserView):

    template = ViewPageTemplateFile('custom_migration.pt')
    at_metadata_fields = ATContentTypeSchema.keys()
    dx_metadata_fields = list(at_metadata_fields)
    # some metadata names are different between AT and DX...
    dx_metadata_fields.remove('allowDiscussion')
    dx_metadata_fields.remove('excludeFromNav')
    dx_metadata_fields.append('allow_discussion')
    dx_metadata_fields.append('exclude_from_nav')

    def __call__(self):
        # check that we can actually access this form,
        # aka the current user has an advice to add or edit
        form = self.request.form
        cancelled = form.get('form.button.Cancel', False)
        submitted = form.get('form.button.Migrate', False)
        # test = form.get('form.button.Test', False)
        if submitted:
            # proceed, call the migration methdd
            results = self.migrate()
            messages = IStatusMessage(self.request)
            for migration_result in results:
                res_type = migration_result.get('type')
                res_infos = migration_result.get('infos')
                if res_infos.get('errors'):
                    messages.add(u'Error when migrating "%s" type. Check the '
                                 u'log for other informations.' % res_type,
                                 type=u"error")
                else:
                    msg = translate(
                        'Migration applied succesfully for %s "%s" items.' %
                        (res_infos.get('counter'), res_type),
                        domain='plone.app.contenttypes')
                    messages.add(msg, type=u"info")
        elif cancelled:
            self.request.response.redirect(form.get('form.HTTP_REFERER'))
        return self.index()

    def getAllArchetypeTypes(self):
        at_types = self.getATFTIs()
        at_types.extend(self.getATTypesWithoutFTI())
        return at_types

    def getATFTIs(self):
        '''Returns a list of all AT types with existing instances
        (including default-types).
        '''
        results = []
        archetype_tool = getToolByName(self.context, 'archetype_tool', None)
        # if we do not have archetype_tool, it means that we have
        # no registered AT types
        if not archetype_tool:
            return results

        typesTool = getToolByName(self.context, 'portal_types')
        catalog = getToolByName(self.context, 'portal_catalog')
        registeredTypeNames = [
            registered['name']
            for registered in archetype_tool.listRegisteredTypes()
        ]
        for fti in typesTool.listTypeInfo():
            ftiId = fti.getId()
            if hasattr(fti, 'content_meta_type') and \
               fti.content_meta_type in registeredTypeNames and \
               catalog(portal_type=ftiId):
                results.append({
                    'id': ftiId,
                    'title': fti.Title(),
                    'removed': False
                })
        return results

    def getATTypesWithoutFTI(self):
        """Returns a list of the id's of archetypes-types that are
           not registered in portal_types but still have instances.
        """
        results = []
        all_registered_types = [i['id'] for i in self.getATFTIs()]
        catalog = getToolByName(self.context, 'portal_catalog')
        for meta_type in catalog.uniqueValuesFor('meta_type'):
            # querying for meta_type will only return at-types
            brain = catalog(meta_type=meta_type, sort_limit=1)[0]
            if IDexterityContent.providedBy(brain.getObject()):
                continue
            typename = brain.portal_type
            if typename not in all_registered_types:
                results.append({
                    'id': typename,
                    'title': typename,
                    'removed': True
                })
        return results

    def getDXFTIs(self):
        '''Returns the FTI's of all DX-Types (including default-types).'''
        results = []
        portal = self.context
        ttool = getToolByName(portal, 'portal_types')
        for fti in ttool.listTypeInfo():
            if IDexterityFTI.providedBy(fti):
                results.append({'id': fti.getId(), 'title': fti.Title()})
        return results

    def getFieldsForATType(self, typeinfo):
        '''Returns schema fields (name and type) for the given AT typename.'''
        if typeinfo['removed']:
            return self.getFieldsForATTypeWithoutFTI(typeinfo['id'])
        return self.getFieldsForATTypeWithFTI(typeinfo['id'])

    def getFieldsForATTypeWithFTI(self, typename):
        '''Returns schema fields (name and type) from the fti.'''
        results = []
        typesTool = getToolByName(self.context, 'portal_types')
        fti = typesTool.getTypeInfo(typename)
        archetype_tool = getToolByName(self.context, 'archetype_tool', None)
        if not fti or not archetype_tool:
            return results
        schema = None
        # a schema instance is stored in the archetype_tool
        for regType in archetype_tool.listRegisteredTypes():
            if regType['meta_type'] == fti.content_meta_type:
                if HAS_EXTENDER:
                    schema = instanceSchemaFactory(regType['klass'])
                else:
                    schema = regType['schema']
                break
        if not schema:
            return results
        for field in schema.fields():
            if not field.getName() in self.at_metadata_fields:
                translated_label = translate(field.widget.label)
                results.append({
                    'id':
                    field.getName(),
                    'title':
                    '%s (%s)' % (translated_label, field.getType()),
                    'type':
                    field.getType()
                })
        return results

    def getFieldsForATTypeWithoutFTI(self, typename):
        """Returns a list of fields for archetypes-types without a fti.
           Instead of iterating over the schema in the fti it takes one
           instance and gets the schema from that.
        """
        catalog = getToolByName(self.context, 'portal_catalog')
        results = []
        brains = catalog(portal_type=typename, sort_limit=1)
        if not brains:
            return results
        obj = brains[0].getObject()
        for field_name in obj.schema._fields:
            field = obj.schema._fields[field_name]
            if not field.getName() in self.at_metadata_fields:
                translated_label = translate(field.widget.label)
                results.append({
                    'id':
                    field.getName(),
                    'title':
                    '%s (%s)' % (translated_label, field.getType()),
                    'type':
                    field.getType()
                })
        return results

    def getFieldsForDXType(self, typename):
        '''Returns schema fields (name and type) for the given DX typename.'''
        results = []
        typesTool = getToolByName(self.context, 'portal_types')
        fti = typesTool.getTypeInfo(typename)
        if not fti:
            return results

        for schemata in iterSchemataForType(typename):
            for fieldName, field in schemata.namesAndDescriptions():
                # ignore Dublin Core fields
                if fieldName in self.dx_metadata_fields:
                    continue
                translated_title = translate(field.title)
                class_name = field.__class__.__name__
                results.append({
                    'id':
                    fieldName,
                    'title':
                    '%s (%s)' % (translated_title, class_name),
                    'type':
                    class_name
                })
        return results

    def getPossibleTargetField(self, fieldtype):
        ''' a list of DX-field types'''

    def isFolderish(self):
        ''' decide which base-class we use for the migrator'''

    def migrate(self, dry_run=False):
        '''Build data from the migration form. We will build a dict like :
           {'MyATPortalType':
                {'MyDXPortalType': (
                    {'AT_field_name': 'fieldname1',
                     'AT_field_type': 'Products.Archetypes.Field.TextField',
                     'DX_field_name': 'field_name1',
                     'DX_field_type': 'RichText'}, )}}
        Call the migrateCustomAT migrator for each AT content_type we choose
        to migrate.
        '''
        data = {}
        form = self.request.form
        # manipulate what we receive in the form and build a useable data dict
        for k in self.request.form.keys():
            if k.startswith('dx_select_'):
                # we found select where we choose a DX type regarding an AT
                # type the selelect name is like 'dx_select_MyATPortalType'
                if not form[k] or (dry_run and k != form.get('tested_type')):
                    # nothing selected in this select, continue
                    continue
                form_at_typename = k[10:]
                form_dx_typename = form[k]
                at_typename = form_at_typename.replace('_space_', ' ')
                dx_typename = form_dx_typename.replace('_space_', ' ')

                data[at_typename] = {
                    'target_type': dx_typename,
                    'field_mapping': []
                }
                # now handle fields mapping for found DX/AT type migration
                # definition we have 2 keys with relevant mappings, first key
                # is the AT typename second key is a particular key like
                # 'dx_DXPortalType__for__MyATPortalType
                dx_key = 'dx_%s__for__%s' % (form_dx_typename,
                                             form_at_typename)
                for at_field in form[form_at_typename]:
                    if form.get(dx_key) is None:
                        # No field-mappings
                        continue
                    dx_field = form[dx_key][form[form_at_typename].index(
                        at_field)]
                    if not dx_field:
                        # Do not migrate field
                        continue
                    at_field_name, at_field_type = at_field.split('__type__')
                    dx_field_name, dx_field_type = dx_field.split('__type__')
                    field_data = {
                        'AT_field_name': at_field_name,
                        'AT_field_type': at_field_type,
                        'DX_field_name': dx_field_name,
                        'DX_field_type': dx_field_type,
                    }
                    data[at_typename]['field_mapping'].append(field_data)

        # now that the data dict contains relevant information, we can call
        # the custom migrator
        migration_results = []
        for at_typename in data:
            fields_mapping = data[at_typename]['field_mapping']
            res = migrateCustomAT(fields_mapping=fields_mapping,
                                  src_type=at_typename,
                                  dst_type=data[at_typename]['target_type'],
                                  dry_run=dry_run)
            migration_results.append({'type': at_typename, 'infos': res})
        return migration_results
                    i18n_domain='ZMetadata',
                )),
    StringField(name='type',
                widget=SelectionWidget(
                    label='Type',
                    label_msgid='ZMetadata_label_type',
                    i18n_domain='ZMetadata',
                ),
                vocabulary=Global.config.getMetadataTypes()),
), )

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Standard_schema = BaseSchema.copy() + schema.copy()
Standard_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema


class Standard(ATCTContent):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(ATCTContent, '__implements__', ()), )

    # This name appears in the 'add' box
    archetype_name = 'Standard'

    meta_type = 'Standard'
from Products.Archetypes.public import ReferenceField
from Products.Archetypes.public import BooleanField
from Products.Archetypes.public import BooleanWidget
from Products.Archetypes.public import registerType
from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget
from Products.EventRegistration import config
from Products.EventRegistration.utils import getPropSheet
from Products.ATContentTypes.configuration import zconf
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.permission import ChangeEvents
from Products.ATContentTypes.content import base
from Products.ATContentTypes.lib.constraintypes import ConstrainTypesMixinSchema


RegisterableEventSchema = ATContentTypeSchema.copy() + ConstrainTypesMixinSchema + Schema(
(
    DateTimeField('startDate',
             required=True,
             searchable=False,
             accessor='start',
             write_permission=ChangeEvents,
             default_method=DateTime,
             languageIndependent=True,
             widget=CalendarWidget(
                 description="",
                 description_msgid="help_event_start",
                 label="Event Starts",
                 label_msgid="label_event_start",
                 i18n_domain="plone",
             ),
Exemple #13
0
    security = ClassSecurityInfo()
    # isPrincipiaFolderish = True # already on Container
    # dsn = FieldProperty(IBioSQLRoot['dsn'])
    dsn = 'postgres://postgres@localhost/plone4bio'
    seqrecord_key = FieldProperty(IBioSQLRoot['seqrecord_key'])
    _v_thread_local = local()

    def __init__(self, *args, **kwargs):
        if kwargs.has_key('parent'):
            parent = kwargs['parent']
            del(kwargs['parent'])
        super(BioSQLRoot, self).__init__(*args, **kwargs)
"""

Plone4BioSchema = ATContentTypeSchema.copy() + atapi.Schema((
    atapi.StringField("dsn",
                      required=True,
                      widget=atapi.StringWidget(label="dsn",
                                                label_msgid="dsn_label",
                                                description="DSN "
                                                "... "
                                                "...",
                                                description_msgid="dsn_help",
                                                i18n_domain="plone4bio")),
    atapi.StringField(
        "seqrecord_key",
        required=True,
        enforceVocabulary=True,
        default='bioentry_id',
        vocabulary=[
import urlparse
import FieldsConfig
import urllib
from ZipUtil import ZipUtil

##code-section module-header #fill in your manual code here
from Products.CMFPlone import PloneMessageFactory as _
##/code-section module-header

schema = Schema((), )

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#MetadataManager_schema =  BaseFolderSchema.copy() +  schema.copy()
MetadataManager_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema


class MetadataManager(BaseFolder):
    """
    """

    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder, '__implements__', ()), )

    # This name appears in the 'add' box
    archetype_name = 'MetadataManager'
Exemple #15
0
try:
    from Products.Archetypes.Widget import RelatedItemsWidget as ReferenceBrowserWidget
except ImportError:
    try:
        from archetypes.referencebrowserwidget.widget import ReferenceBrowserWidget
    except ImportError:
        from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget

from Products.CMFBibliographyAT.marshall import BibtexMarshaller
from Products.CMFBibliographyAT.config import REFERENCE_TYPES
from Products.ATExtensions.ateapi import FormattableNamesField
from Products.ATExtensions.ateapi import FormattableNamesWidget
from Products.ATExtensions.ateapi import CommentField, CommentWidget
from Products.ATExtensions.ateapi import RecordsField, RecordsWidget

HeaderSchema = BaseSchema.copy()
HeaderSchema['id'].widget.macro_edit = "widgets/string"
# XXX ugly hack as long as IdWidget subclasses TypesWidget
HeaderSchema['id'].widget.size = 40
HeaderSchema['id'].widget.maxlength = 255
HeaderSchema[
    'id'].widget.condition = 'python: object.visibleIdsEnabled() and not object.getBibFolder().getCookIdsAfterBibRefEdit()'

CookIdWarningField = StringField(
    'shortname_cookid_warning',
    schemata="default",
    mode="rw",
    accessor="getCookIdWarning",
    widget=StringWidget(
        label="Short Name",
        label_msgid="label_shortname_cookid_warning",
Exemple #16
0
from Products.Archetypes.public import RFC822Marshaller

from Products.Archetypes.public import BaseSchema, Schema
from Products.Archetypes.public import StringField, IntegerField
from Products.Archetypes.public import StringWidget
from Products.Archetypes.public import BaseContent, registerType
from Products.Archetypes.Marshall import PrimaryFieldMarshaller
from Products.CMFCore import permissions as CMFCorePermissions
from Products.COREBlog2.config import PROJECTNAME

from AccessControl import ClassSecurityInfo
from Products.CMFCore.permissions import View

from actions_proxy import updateAliases, base_aliases

COREBlogTrackbackSchema = ATContentTypeSchema.copy() + Schema(
    (

        #Comment content data
        StringField(
            'url',
            searchable=1,
            widget=StringWidget(
                label='URL',
                description='',
                label_msgid="label_coreblog_trackback_url",
                description_msgid="help_coreblog_trackback_url",
                i18n_domain="plone",
                size=60),
        ),
        StringField(
Exemple #17
0
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import StringWidget
from Products.Archetypes.atapi import LinesField
from Products.Archetypes.atapi import LinesWidget
from Products.Archetypes.atapi import TextField
from Products.Archetypes.atapi import RichWidget
from Products.ATContentTypes.content.schemata import ATContentTypeSchema

from Products.ATContentTypes.configuration import zconf
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.PloneGlossary.utils import PloneGlossaryMessageFactory as _


# PloneGlossary schema
PloneGlossarySchema = ATContentTypeSchema.copy()
PloneGlossarySchema['description'].schemata = 'default'

finalizeATCTSchema(PloneGlossarySchema, folderish=True)

# PloneGlossaryDefinition schema
PloneGlossaryDefinitionSchema = ATContentTypeSchema.copy() + Schema((
    StringField(
        'title',
        required=True,
        searchable=True,
        default='',
        accessor='Title',
        widget=StringWidget(
            label=_('label_glossary_term', default="Term"),
            description=_('help_glossary_term',
Exemple #18
0
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import translateMimetypeAlias
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATDocument
from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.permissions import View
from Products.CMFCore.utils import getToolByName
from Products.GenericSetup.interfaces import IDAVAware
from types import TupleType
from zope.interface import implements
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),
Exemple #19
0
"""Definition of the ServiceComponent content type
"""

from zope.interface import implements

from Products.Archetypes import atapi
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content import schemata

# -*- Message Factory Imported Here -*-

from pcp.contenttypes.interfaces import IActionItem
from pcp.contenttypes.config import PROJECTNAME

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

    # -*- Your Archetypes field definitions here ... -*-
))

schemata.finalizeATCTSchema(ActionItemSchema,
                            folderish=False,
                            moveDiscussion=False)


class ActionItem(atapi.BaseContent):
    """Component of an EUDAT service"""
    implements(IActionItem)

    meta_type = "ActionItem"
    schema = ActionItemSchema
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),
                      'thumb': (128, 128),
                      'tile': (64, 64),
                      'icon': (32, 32),
from Products.Archetypes.public import *
from Products.Archetypes.utils import shasattr

from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.content.base import registerATCT

from Products.TALESField import TALESString

from Products.PloneFormGen import PloneFormGenMessageFactory as _
from Products.PloneFormGen.config import *
from Products.PloneFormGen.interfaces import IPloneFormGenActionAdapter

FormAdapterSchema = ATContentTypeSchema.copy() + Schema((
    TALESString(
        'execCondition',
        schemata='overrides',
        searchable=0,
        required=0,
        validators=('talesvalidator', ),
        default='',
        write_permission=EDIT_TALES_PERMISSION,
        read_permission=ModifyPortalContent,
        isMetadata=True,  # just to hide from base view
        widget=StringWidget(
            label=_('label_execcondition_text', default="Execution Condition"),
            description=_('help_execcondition_text',
                          default="""
                A TALES expression that will be evaluated to determine whether or not
from Products.Archetypes.atapi import TextAreaWidget
from Products.Archetypes.atapi import TextField
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.lib.constraintypes \
    import ConstrainTypesMixinSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.PloneSurvey import PloneSurveyMessageFactory as _
from Products.PloneSurvey.config import NOTIFICATION_METHOD
from Products.PloneSurvey.config import TEXT_INPUT_TYPE
from Products.PloneSurvey.config import SELECT_INPUT_TYPE
from Products.PloneSurvey.config import TEXT_LOCATION
from Products.PloneSurvey.config import COMMENT_TYPE
from Products.PloneSurvey.config import LIKERT_OPTIONS

SurveySchema = ATContentTypeSchema.copy() + ConstrainTypesMixinSchema + Schema((

    TextField(
        'body',
        searchable=1,
        required=0,
        schemata="Introduction",
        default_content_type='text/html',
        default_output_type='text/html',
        allowable_content_types=('text/plain',
                                 'text/structured',
                                 'text/html', ),
        widget=RichWidget(
            label=_('label_introduction',
                    default=u"Introduction"),
            description=_(
Exemple #23
0
"""
from Products.CMFCore.permissions import View
from AccessControl import ClassSecurityInfo
from Acquisition import aq_parent

from zope.interface import implements
from Products.Archetypes import atapi
from Products.ATContentTypes.content import schemata
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from plone.app.blob.field import ImageField
from jarn.kommuner.config import PROJECTNAME
from jarn.kommuner.interfaces import IPerson
from jarn.kommuner import kommunerMessageFactory as _

PersonSchema = ATContentTypeSchema.copy() + atapi.Schema((
    atapi.TextField(
        'body',
        required=False,
        searchable=True,
        validators=('isTidyHtmlWithCleanup', ),
        default_output_type='text/x-html-safe',
        widget=atapi.RichWidget(description='',
                                label=_(u'label_body_text',
                                        default=u'Body Text'),
                                rows=25),
    ),
    atapi.StringField('description',
                      widget=atapi.StringWidget(
                          label=_(u"Job title"),
                          description=_(u"The position the person holds.")),
Exemple #24
0
from AccessControl import ClassSecurityInfo
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from ftw.book.config import PROJECTNAME
from ftw.book.interfaces import IRemark
from ftw.contentpage.content import textblock
from ftw.contentpage.content.schema import finalize
from zope.interface import implements


try:
    from Products.LinguaPlone import public as atapi
except ImportError:
    from Products.Archetypes import atapi


remark_schema = ATContentTypeSchema.copy() + \
    textblock.default_schema.copy()
remark_schema['title'].required = False
remark_schema['title'].searchable = 0
finalize(remark_schema, hide=['description', 'showTitle'])


class Remark(textblock.TextBlock):
    """A simplelayout block used for comments
    """

    security = ClassSecurityInfo()
    implements(IRemark)
    schema = remark_schema

Exemple #25
0
import time
from StringIO import StringIO
import Global
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.CMFCore import permissions

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((), )

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Logs_schema = BaseFolderSchema.copy() + schema.copy()
Logs_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema


class Logs(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder, '__implements__', ()), )

    # This name appears in the 'add' box
    archetype_name = 'Logs'

    meta_type = 'Logs'
Exemple #26
0
        ##    StringField(
        ##        name='name',
        ##        widget=StringWidget(
        ##            label='Name',
        ##            label_msgid='ZMetadata_label_name',
        ##            i18n_domain='ZMetadata',
        ##        )
        ##    ),
    ), )

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Custodian_schema = BaseFolderSchema.copy() +  schema.copy()
Custodian_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema


class Custodian(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder, '__implements__', ()), )

    # This name appears in the 'add' box
    archetype_name = 'Custodian'

    meta_type = 'Custodian'
# -*- coding: utf-8 -*-

from AccessControl import ClassSecurityInfo
from Products.Archetypes import atapi
from zope.interface import implements

from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin

from vindula.streaming.config import PROJECTNAME
from vindula.streaming.content.interfaces import IVindulaStreaming

from Products.ATContentTypes.content.schemata import ATContentTypeSchema

from vindula.content.models.content_field import ContentField

StreamingSchema = ATContentTypeSchema.copy() + atapi.Schema(
    (
        atapi.StringField(
            name="duracao",
            widget=atapi.StringField._properties["widget"](
                label="Tempo de Duração", description="Informe o tempo de duração desta multimídia"
            ),
            required=True,
        ),
        atapi.StringField(
            name="ano",
            widget=atapi.StringField._properties["widget"](
                label="Ano da Multimídia", description="Informe o ano desta multimídia"
            ),
            required=False,
        ),
Exemple #28
0
import plone.api
from zope.interface import implements

from Products.Archetypes import atapi
from Products.ATContentTypes.content import schemata
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.Archetypes.atapi import ReferenceField
from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget
from Products.CMFCore.permissions import ModifyPortalContent
from Products.ATContentTypes import ATCTMessageFactory as _

from pcp.contenttypes.interfaces import IActionList
from pcp.contenttypes.config import PROJECTNAME

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='',
Exemple #29
0
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,
            allow_file_upload = zconf.ATDocument.allow_document_upload)
        ),
    ImageField('image',
from Products.ZMetadata.config import *
from Products.ATContentTypes.content.schemata import ATContentTypeSchema

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#MetadataContainer_schema = BaseFolderSchema.copy() + schema.copy()
MetadataContainer_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class MetadataContainer(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'MetadataContainer'

    meta_type = 'MetadataContainer'
    portal_type = 'MetadataContainer'
Exemple #31
0
class ECQResult(ATCTContent, HistoryAwareMixin):
    """A quiz result."""
    """ This class contains all the candidate-specific information for
        an ECQuiz.  They are:

        questionResults:

          A dictionary that contains all the information concerning a
          single question, e. g. the suggested answer, the answer
          given by the candidate, the grade.

          The keys are the UIDs of the question.
                                   
        questionContainerIds:

          A list of the IDs of the 'ECQAbstractGroup'
          instances that the candidate saw.

        questionUIDs:

          A list of IDs of the questions that the candidate saw in
          their quiz.  Unfortunately 'questionResults.keys()' cannot
          be used since it does not preserve the order of the UIDs.
                                   
        timeStart:

          The time when the candidate first saw the quiz.
        
        timeFinish:

          The time when the candidate submitted their quiz.
    """

    schema = ATContentTypeSchema.copy() + Schema((
        ObjectField(
            'questionResults',
            read_permission=PERMISSION_RESULT_READ,
            default={},
        ),
        ObjectField(
            'possiblePointsCache',
            read_permission=PERMISSION_RESULT_READ,
            default={},
        ),
        ObjectField(
            'candidatePointsCache',
            read_permission=PERMISSION_RESULT_READ,
            default={},
        ),
        ObjectField(
            'questionContainerIds',
            read_permission=PERMISSION_RESULT_READ,
            default=[],
        ),
        ObjectField(
            'questionUIDs',
            read_permission=PERMISSION_RESULT_READ,
            default=[],
        ),
        DateTimeField(
            'timeStart',
            read_permission=PERMISSION_RESULT_READ,
        ),
        DateTimeField(
            'timeFinish',
            read_permission=PERMISSION_RESULT_READ,
            default=None,
        ),
        IntegerField(
            'currentPageNum',
            read_permission=PERMISSION_RESULT_READ,
            write_permission=PERMISSION_RESULT_WRITE,
            default=0,
        ),
    ), )

    # Don't list this type in the portal navigation.
    navigation_exclude = True

    security = ClassSecurityInfo()

    security.declarePrivate('getQR')

    def getQR(self, caller, question, dontThrow=False):
        questionUID = question.UID()
        qrs = self.getQuestionResults()
        retVal = qrs.get(questionUID, None)
        if (retVal is not None) or dontThrow:
            return retVal
        else:
            txt = "%s() called for questionUID not in self.questionUIDs\n" \
                  "questionUID: %s\n" \
                  "self.questionUIDs: %s" \
                  % (caller, repr(questionUID), repr(self.getQuestionUIDs()))
            log(txt)
            raise Exception(txt)

    security.declarePrivate('storeQR')

    def storeQR(self, question, result):
        qrs = self.getQuestionResults()
        qrs[question.UID()] = result
        # Instead of saving "qrs" directly, save a copy of it,
        # "dict(qrs)".  If we don't do that, there is a chance that
        # Zope will return an old, cached value the next time
        # "self.getQuestionResults()" is called because it *thinks*
        # the cached dictionary is the same as the stored one because
        # the memory location didn't change.
        self.setQuestionResults(dict(qrs))

    security.declarePrivate('setSuggestedAnswer')

    def setSuggestedAnswer(self, question, suggestedAnswer):
        """ Saves the suggested answer values to a question the
            candidate was asked.
            
            @param suggestedAnswer The value or list of values
            of the answer suggested to the candidate.
                                        
            @param question The question that the answer belongs to.
                              
            @param questionContainerId The ID of the question
            container that contains the question.
        """
        # The list 'questionContainerIds' is neccessary because
        # 'self.questionResults.keys()' does not return the
        # questionUIDs in the order they were added.
        questionContainerId = getParent(question).getId()
        questionUID = question.UID()
        questionContainerIds = self.getQuestionContainerIds()
        if questionContainerId not in questionContainerIds:
            self.setQuestionContainerIds(questionContainerIds +
                                         [questionContainerId])
        questionUIDs = self.getQuestionUIDs()
        if questionUID not in questionUIDs:
            self.setQuestionUIDs(questionUIDs + [questionUID])
        qr = QuestionResult(suggestedAnswer)
        self.storeQR(question, qr)

    security.declareProtected(PERMISSION_RESULT_READ, 'getSuggestedAnswer')

    def getSuggestedAnswer(self, question):
        """ Returns the suggested answer values for a question the
            candidate was asked.  With the standard question and
            answer types this will be a list of IDs of answer objects.
        """
        qr = self.getQR("getAnswer", question)
        return qr.getSuggestedAnswer()

    security.declareProtected(PERMISSION_RESULT_READ, 'getCandidateAnswer')

    def getCandidateAnswer(self, question):
        """ Returns the candidate's answer to the question.  If this
        question was not part of their quiz, an exception will be
        raised.
        """
        qr = self.getQR("getCandidateAnswer", question)
        return qr.getCandidateAnswer()

    security.declareProtected(PERMISSION_RESULT_WRITE, 'setCandidateAnswer')

    def setCandidateAnswer(self, question, answerValue):
        """ Saves the candidate's answer to a question.
            
            @param answerValue The value or list of values of the
            answer(s) the candidate gave. With the standard question
            and answer types this will be the ID (list of IDs) of the
            answer(s) the candidate selected.
        """
        qr = self.getQR("setCandidateAnswer", question)
        qr.setCandidateAnswer(answerValue)
        self.storeQR(question, qr)

    security.declareProtected(PERMISSION_RESULT_WRITE, 'unsetCandidateAnswer')

    def unsetCandidateAnswer(self, question):
        """ Removes the candidate's answer to a question.
            
            @param answerValue The value or list of values of the
            belongs to.
        """
        qr = self.getQR("unsetCandidateAnswer", question)
        qr.unsetCandidateAnswer()
        self.storeQR(question, qr)

    ## Points caching: start

    # Points for an individual question
    security.declareProtected(PERMISSION_RESULT_READ,
                              'getCachedQuestionPoints')

    def getCachedQuestionPoints(self, question):
        """
        """
        qr = self.getQR("getCachedQuestionPoints", question)
        return qr.cachedPoints

    security.declareProtected(PERMISSION_RESULT_WRITE,
                              'setCachedQuestionPoints')

    def setCachedQuestionPoints(self, question, value):
        """
        """
        qr = self.getQR("setCachedQuestionPoints", question)
        qr.cachedPoints = value
        self.storeQR(question, qr)

    # Tutor-assigned points for an individual question
    security.declareProtected(PERMISSION_GRADE, 'setTutorPoints')

    def getTutorPoints(self, question):
        """
        """
        qr = self.getQR("getTutorPoints", question)
        return qr.tutorPoints

    security.declareProtected(PERMISSION_GRADE, 'setTutorPoints')

    def setTutorPoints(self, question, value):
        """
        """
        qr = self.getQR("setTutorPoints", question)
        qr.tutorPoints = value
        self.storeQR(question, qr)

        # clear related cache info
        test = getParent(question)
        if test.portal_type == ECQGroup.portal_type:
            questionGroup = test
            test = getParent(questionGroup)
        else:
            questionGroup = None

        self.setCachedCandidatePoints(test, None)
        #log("%s: CachedCandidatePoints: %s" % (str(self), str(test)))
        if questionGroup:
            self.setCachedCandidatePoints(questionGroup, None)
            #log("%s: CachedCandidatePoints: %s" % (str(self),
            #                                         str(questionGroup)))
        #log("")

    security.declareProtected(PERMISSION_GRADE, 'unsetTutorPoints')

    def unsetTutorPoints(self, question):
        """
        """
        self.setTutorPoints(question, None)  # this also clears any
        # related caches
        # Retract to "pending" because the result can't be "graded" if
        # some grades are missing
        userId = self.portal_membership.getAuthenticatedMember().getId()
        comment = "Retracted by %s: tutor grades were deleted" % userId
        self.tryWorkflowAction('retract_pending',
                               ignoreErrors=True,
                               comment=comment)

    # Possible points for a question group
    security.declareProtected(PERMISSION_RESULT_READ,
                              'getCachedPossiblePoints')

    def getCachedPossiblePoints(self, questionGroup):
        """
        """
        cache = self.getPossiblePointsCache()
        return cache.get(questionGroup.UID(), None)

    security.declareProtected(PERMISSION_RESULT_WRITE,
                              'setCachedPossiblePoints')

    def setCachedPossiblePoints(self, questionGroup, value):
        """
        """
        cache = self.getPossiblePointsCache()
        cache[questionGroup.UID()] = value
        self.setPossiblePointsCache(dict(cache))

    # Achieved points for a question group
    security.declareProtected(PERMISSION_RESULT_READ,
                              'getCachedCandidatePoints')

    def getCachedCandidatePoints(self, questionGroup):
        """
        """
        cache = self.getCandidatePointsCache()
        return cache.get(questionGroup.UID(), None)

    security.declareProtected(PERMISSION_RESULT_WRITE,
                              'setCachedCandidatePoints')

    def setCachedCandidatePoints(self, questionGroup, value):
        """
        """
        cache = self.getCandidatePointsCache()
        cache[questionGroup.UID()] = value
        self.setCandidatePointsCache(dict(cache))

    # Delete all cached points
    security.declarePrivate('unsetAllCachedPoints')

    def unsetAllCachedPoints(self):
        # Delete cached points for the questions
        qrs = self.getQuestionResults()
        for qr in qrs.values():
            qr.cachedPoints = None
        self.setQuestionResults(dict(qrs))

        # Delete the caches for possible and candidate points in a
        # question group
        self.setPossiblePointsCache({})
        self.setCandidatePointsCache({})
        #log("%s: deleted all cached points" % (str(self)))

    # Clear all cached points related to the question [question],
    # i. e. clear cache for possible and achieved (candidate) points
    # for the question and the question group and the test that
    # contain this question
    security.declarePrivate('unsetCachedQuestionPoints')

    def unsetCachedQuestionPoints(self, question):
        """
        """
        if self.getQR("", question, dontThrow=True) is not None:
            test = getParent(question)
            if test.portal_type == ECQGroup.portal_type:
                questionGroup = test
                test = getParent(questionGroup)
            else:
                questionGroup = None

            self.setCachedQuestionPoints(question, None)
            #log("%s: CachedQuestionPoints: %s" % (str(self), str(question)))

            self.setCachedPossiblePoints(test, None)
            #log("%s: CachedPossiblePoints: %s" % (str(self), str(test)))
            self.setCachedCandidatePoints(test, None)
            #log("%s: CachedCandidatePoints: %s" % (str(self), str(test)))
            if questionGroup:
                self.setCachedPossiblePoints(questionGroup, None)
                #log("%s: CachedPossiblePoints: %s" % (str(self),
                #                                        str(questionGroup)))
                self.setCachedCandidatePoints(questionGroup, None)
                #log("%s: CachedCandidatePoints: %s" % (str(self),
                #                                         str(questionGroup)))
            #log("")

    ## Points caching: end

    security.declareProtected(PERMISSION_RESULT_READ, 'haveCandidateAnswer')

    def haveCandidateAnswer(self, question):
        qr = self.getQR("haveCandidateAnswer", question)
        return qr.haveCandidateAnswer()

    security.declareProtected(PERMISSION_RESULT_WRITE, 'startWatch')

    def startWatch(self, question):
        qr = self.getQR("startWatch", question)
        if not qr.isWatchRunning():
            qr.addTimeStart(datetime.now())
            #log("startWatch: %s" % str(question))
            self.storeQR(question, qr)
            makeTransactionUnundoable()

    security.declareProtected(PERMISSION_RESULT_WRITE, 'stopWatch')

    def stopWatch(self, question):
        qr = self.getQR("stopWatch", question)
        if qr.isWatchRunning():
            #log("stopWatch: %s" % str(question))
            qr.addTimeFinish(datetime.now())
            self.storeQR(question, qr)

    security.declareProtected(PERMISSION_RESULT_READ, 'isWatchRunning')

    def isWatchRunning(self, question):
        qr = self.getQR("isWatchRunning", question)
        return qr.isWatchRunning()

    security.declareProtected(PERMISSION_RESULT_READ, 'getTimeSpent')

    def getTimeSpent(self, question):
        """@return  A Python timedelta object."""
        qr = self.getQR("getTimeSpent", question)
        return qr.getTimeSpent()

    security.declareProtected(PERMISSION_RESULT_READ, 'getSetCount')

    def getSetCount(self, question):
        """@return The number of times the candidate changed his
        answer."""
        qr = self.getQR("getTimeSpent", question)
        return qr.getSetCount()

    security.declarePublic('getWorkflowState')

    def getWorkflowState(self):
        """Determine the Plone workflow state."""
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        return wf.getInfoFor(self, 'review_state', '')

    security.declarePublic('hasState')

    def hasState(self, state):
        return self.getWorkflowState() == state

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        if wf.isActionSupported(self, action):
            if comment is None:
                userId = getSecurityManager().getUser().getId()
                comment = 'State changed by ' + userId
            wtool.doActionFor(self, action, comment=comment)
        elif not ignoreErrors:
            raise TypeError('Unsupported workflow action %s for object %s.' %
                            (repr(action), repr(self)))

    security.declarePublic('isGradable')

    def isGradable(self):
        mcTest = getParent(self)
        return mcTest.isTutorGraded(self) and \
               (self.getWorkflowState() in ("pending", "graded",))

    security.declareProtected(PERMISSION_RESULT_WRITE, 'submit')

    def submit(self):
        self.setTimeFinish(DateTime())
        mcTest = getParent(self)
        results = mcTest.contentValues(filter={
            'Creator': self.Creator(),
            'portal_type': self.portal_type,
        })
        for res in results:
            # determine workflow action: submit for self and supersede
            # for all the others
            if res == self:
                if mcTest.isTutorGraded(self):
                    action = 'submit_pending'
                else:
                    action = 'submit_graded'
                commentAction = 'Submitted'
            else:
                action = 'supersede'
                commentAction = 'Superseded'
            # execute the action
            comment = '%s by %s' % (commentAction, self.Creator())
            res.tryWorkflowAction(action, ignoreErrors=True, comment=comment)

    security.declarePublic('isNewer')

    def isNewer(self, other):
        return self.getTimeStart() > other.getTimeStart()

    security.declarePublic('isMoreFinal')

    def isMoreFinal(self, other):
        STATES = [
            'unsubmitted',
            'superseded',
            'pending',
            'graded',
            #'invalid',
        ]
        indexes = [STATES.index(o.getWorkflowState()) for o in self, other]
        return indexes[0] > indexes[1]

    security.declarePrivate('getViewerNames')

    def getViewerNames(self):
        """
        Get the names of the users and/or groups which have the local
        role ROLE_RESULT_VIEWER.  This allows reviewers to quickly
        check who may view an assignment.
        
        @return list of user and/or group names
        """
        principalIds = self.users_with_local_role(ROLE_RESULT_VIEWER)
        names = []

        for id in principalIds:
            if self.portal_groups.getGroupById(id):
                names.append(
                    self.portal_groups.getGroupById(id).getGroupName())
            else:
                names.append(self.ecq_tool.getFullNameById(id))

        return names

    security.declarePublic('getIndicators')

    def getIndicators(self):
        """
        Returns a list of dictionaries which contain information necessary
        to display the indicator icons.
        """
        retVal = []

        user = self.portal_membership.getAuthenticatedMember()
        isOwner = user.has_role(['Owner', 'Reviewer', 'Manager'], self)
        isGrader = self.userIsGrader(user)

        viewers = self.getViewerNames()

        if viewers:
            if isOwner:
                retVal.append({
                    'src': 'ec_shared.png',
                    'alt': 'Released',
                    'alt_msgid': 'label_released',
                    'title': '; '.join(viewers),
                })
            elif isGrader:
                retVal.append({
                    'src': 'ec_shared.png',
                    'alt': 'Released',
                    'alt_msgid': 'label_released',
                    'title':
                    'These quiz results have been released for viewing.',
                    'title_msgid': 'tooltip_released_icon',
                })


#         if self.feedback:
#             feedback = str(self.feedback)
#             title = re.sub('[\r\n]+', ' ', feedback)[0:76]

#             retVal.append({'icon':'comment.png',
#                            'alt':'Feedback',
#                            'alt_msgid':'label_feedback',
#                            'title':title,
#                            })

#         if isGrader and hasattr(self, 'remarks') and self.remarks:
#             remarks = str(self.remarks)
#             title = re.sub('[\r\n]+', ' ', remarks)[0:76]

#             retVal.append({'icon':'ecab_remarks.png',
#                            'alt':'Remarks',
#                            'alt_msgid':'label_remarks',
#                            'title':title,
#                            })
        return retVal

    security.declarePublic('translateIndicators')

    def translateIndicators(self, indicators):
        # Translate [alt] and [title]
        for d in indicators:
            for k_msgid, k_msg in ((
                    'alt_msgid',
                    'alt',
            ), (
                    'title_msgid',
                    'title',
            )):
                msgid = d.get(k_msgid, None)
                if msgid is not None:
                    msg = d[k_msg]
                    d[k_msg] = self.translate(msgid=k_msg,
                                              domain=I18N_DOMAIN,
                                              default=msg)
                    d.pop(k_msgid)

        return indicators
Exemple #32
0
from Products.ATContentTypes.content.image import ATImage
from my315ok.watermarkImage.watermarkfield import WatermarkImageField as  ImageField
from my315ok.watermarkImage import watermarkImageMessageFactory as  _
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.configuration import zconf

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))


WatermarkImageSchema = ATContentTypeSchema.copy() + atapi.Schema((
    ImageField('image',
               required=True,
               primary=True,
               languageIndependent=True,
               storage = atapi.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),                   
                      },
               validators = (('isNonEmptyFile', V_REQUIRED),
                             ('checkImageMaxSize', V_REQUIRED)),
Exemple #33
0
from Products.Archetypes.atapi import TextAreaWidget
from Products.Archetypes.atapi import TextField
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.lib.constraintypes \
    import ConstrainTypesMixinSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.PloneSurvey import PloneSurveyMessageFactory as _
from Products.PloneSurvey.config import NOTIFICATION_METHOD
from Products.PloneSurvey.config import TEXT_INPUT_TYPE
from Products.PloneSurvey.config import SELECT_INPUT_TYPE
from Products.PloneSurvey.config import TEXT_LOCATION
from Products.PloneSurvey.config import COMMENT_TYPE
from Products.PloneSurvey.config import LIKERT_OPTIONS

SurveySchema = ATContentTypeSchema.copy(
) + ConstrainTypesMixinSchema + Schema((
    TextField(
        'body',
        searchable=1,
        required=0,
        schemata="Introduction",
        default_content_type='text/html',
        default_output_type='text/html',
        allowable_content_types=(
            'text/plain',
            'text/structured',
            'text/html',
        ),
        widget=RichWidget(
            label=_('label_introduction', default=u"Introduction"),
            description=_('help_introduction',
    BooleanField(
        name='categoryIndependent',
        languageIndependent=True,
        widget=BooleanField._properties['widget'](
            visible=dict(edit='invisible', view='invisible'),
            label=_(u'ra_categoryIndependent_label', default=u'Category independent'),
            description=_(u'ra_categoryIndependent_description', 
                default=u'Tick here to limit your search to general and introductory Risk Assessment Links.'),
        ),
    ),
),
)


RiskAssessmentLink_schema = BaseSchema.copy() + \
    ATContentTypeSchema.copy() + \
    schema.copy()

finalizeATCTSchema(RiskAssessmentLink_schema)

unwantedFields = ('rights', 'subject', 'contributors', 'allowDiscussion', 'location',
    'creators', 'effectiveDate', 'expirationDate', 'creation_date', 'modification_date',
    'relatedItems', 'excludeFromNav', 'language')

for name in unwantedFields:
    RiskAssessmentLink_schema[name].widget.visible['edit'] = 'invisible'
    RiskAssessmentLink_schema.changeSchemataForField(name, 'Other')



class RiskAssessmentLink(BaseContent, ATCTContent, BrowserDefaultMixin):
        atapi.StringField('playbackUrl',
                          searchable=0,
                          accessor="getPlaybackUrl",
                          mode="r",
                          widget=atapi.ComputedWidget(label="Url",
                                                    description="Url set by Kaltura after upload (read only)",
                                                    visible = { 'edit' :'visible', 'view' : 'visible' },
                                                    i18n_domain="kaltura_video")
                          ),

        ),
        marshall=RFC822Marshaller()
   )

KalturaVideoSchema += KalturaBase.KalturaMetadataSchema.copy()
KalturaVideoSchema += ATContentTypeSchema.copy()

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

KalturaVideoSchema.get('title').storage = AnnotationStorage()

KalturaVideoSchema[
    'categories'].widget.description = "Select category(ies) this video will belong to"
KalturaVideoSchema[
    'categories'].widget.description_msgid = "desc_kvideo_categories"
KalturaVideoSchema[
    'tags'].widget.description = "keyword tags to place on this video (one per line)"
KalturaVideoSchema['tags'].widget.description_msgid = "desc_kvideo_tags"

finalizeATCTSchema(KalturaVideoSchema, moveDiscussion=False)
Exemple #36
0
                                    default=u"Options Vocabulary"),
            description=_(u'help_fgtvocabulary_text', default=u"""
                A TALES expression that will be evaluated when the form is displayed
                to get the field options.
                Leave empty if unneeded.
                Your TALES expression should evaluate as a list of (key, value) tuples.
                PLEASE NOTE: errors in the evaluation of this expression will cause
                an error on form display.
            """),
            size=70,
            ),
        )

# establish a bare baseline
# only label field uses this without change
BareFieldSchema = ATContentTypeSchema.copy()
BareFieldSchema['title'].searchable = False
BareFieldSchema['title'].widget.label = _(u'label_fieldlabel_text',
                                          default=u'Field Label')
BareFieldSchema['description'].searchable = False
BareFieldSchema['description'].widget.label = _(u'label_fieldhelp_text',
                                                default=u'Field Help')
BareFieldSchema['description'].widget.description = None

###
# BaseFieldSchema -- more common baseline
# Used as a base schema for several fields

BaseFieldSchema = BareFieldSchema.copy() + Schema((
    BooleanField(
        'required',
Exemple #37
0
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.configuration import zconf

from Products.PloneFormGen.config import PROJECTNAME
from Products.PloneFormGen.interfaces import IPloneFormGenThanksPage

from Products.PloneFormGen import PloneFormGenMessageFactory as _
from Products.PloneFormGen import dollarReplace
from Products.PloneFormGen import implementedOrProvidedBy

import zope.i18n


ThanksPageSchema = ATContentTypeSchema.copy() + Schema((
    BooleanField('showAll',
        required=0,
        searchable=0,
        default='1',
        widget=BooleanWidget(
            label=_(u'label_showallfields_text', default=u"Show All Fields"),
            description=_(u'help_showallfields_text', default=u"""
                Check this to display input for all fields
                (except label and file fields). If you check
                this, the choices in the pick box below
                will be ignored.
                """),
            ),
        ),
    LinesField('showFields',
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import translateMimetypeAlias
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interfaces import IATDocument
from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.permissions import View
from Products.CMFCore.utils import getToolByName
from Products.GenericSetup.interfaces import IDAVAware
from types import TupleType
from zope.interface import implementer
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,
        default = 'No',
        widget=SelectionWidget
        (
            label='Publish Harvested Metadata',            
        ),
        vocabulary=['Yes','No']
    ),

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Harvester_schema = BaseSchema.copy() + schema.copy()
Harvester_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class Harvester(BaseContent):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseContent,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'Harvester'

    meta_type = 'Harvester'
    portal_type = 'Harvester'
Exemple #40
0
from zope.interface import implements
from Products.Archetypes import atapi

from Products.ATContentTypes.content import base
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.CMFCore.permissions import View
from Products.CMFCore.permissions import ModifyPortalContent
from AccessControl import ClassSecurityInfo

from iservices.rssdocument import RSSDocumentMessageFactory as _
from iservices.rssdocument.interfaces import IRSSDocument
from iservices.rssdocument import config

RSSDocumentSchema = ATContentTypeSchema.copy() + atapi.Schema((
    atapi.StringField(
        'RSSLink',
        required=True,
        widget=atapi.StringWidget(label=_(u'RSS URL'),
                                  description=_(u'The URL of the RSS Feed')),
    ),
    atapi.IntegerField(
        'max_entries',
        required=True,
        widget=atapi.IntegerWidget(
            label=_(u'Max Entries'),
            description=_(u'Maximum Number of entries to show')),
    ),
))
finalizeATCTSchema(RSSDocumentSchema)
from Products.ATContentTypes import ATCTMessageFactory as _
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
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."""
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='',
                label=_(u'label_body_text', u'Body Text'),
                rows=25,
                allow_file_upload=zconf.ATDocument.allow_document_upload)),
Exemple #43
0
from Products.MimetypesRegistry.common import MimeTypeException
from ZODB.POSException import ConflictError
from zope.event import notify
from zope.interface import implementer
from zope.lifecycleevent import ObjectCreatedEvent
from zope.lifecycleevent import ObjectModifiedEvent


try:
    from Products.LinguaPlone.public import registerType
    registerType  # make pyflakes happy...
except ImportError:
    from Products.Archetypes.atapi import registerType


ATBlobSchema = ATContentTypeSchema.copy()
ATBlobSchema['title'].storage = AnnotationStorage()
# titles not required for blobs, because we'll use the filename if missing
ATBlobSchema['title'].required = False

finalizeATCTSchema(ATBlobSchema, folderish=False, moveDiscussion=False)
ATBlobSchema.registerLayer('marshall', BlobMarshaller())


try:
    from Products.CMFCore.CMFCatalogAware import WorkflowAware
    WorkflowAware  # make pyflakes happy...
    # CMF 2.2 takes care of raising object events for old-style factories
    hasCMF22 = True
except ImportError:
    hasCMF22 = False
from Products.Archetypes.public import *
from Products.Archetypes.utils import shasattr

from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.content.base import registerATCT

from Products.TALESField import TALESString

from Products.PloneFormGen import PloneFormGenMessageFactory as _
from Products.PloneFormGen.config import *
from Products.PloneFormGen.interfaces import IPloneFormGenActionAdapter

FormAdapterSchema = ATContentTypeSchema.copy() + Schema((
    TALESString('execCondition',
        schemata='overrides',
        searchable=0,
        required=0,
        validators=('talesvalidator',),
        default='',
        write_permission=EDIT_TALES_PERMISSION,
        read_permission=ModifyPortalContent,
        isMetadata=True, # just to hide from base view
        widget=StringWidget(label=_(u'label_execcondition_text', default=u"Execution Condition"),
            description=_(u'help_execcondition_text', default=u"""
                A TALES expression that will be evaluated to determine whether or not
                to execute this action.
                Leave empty if unneeded, and the action will be executed. 
                Your expression should evaluate as a boolean; return True if you wish
Exemple #45
0
from Products.ATContentTypes.interface import IATBTreeFolder
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import NextPreviousAwareSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.lib.constraintypes import \
    ConstrainTypesMixinSchema
from Products.ATContentTypes.content.base import ATCTFolderMixin
from Products.ATContentTypes.content.base import registerATCT

from plone.app.folder import packageName
from plone.app.folder.base import BaseBTreeFolder
from plone.app.folder.bbb import IArchivable, IPhotoAlbumAble
from plone.app.folder.bbb import folder_implements


ATFolderSchema = ATContentTypeSchema.copy() + \
    ConstrainTypesMixinSchema.copy() + NextPreviousAwareSchema.copy()
finalizeATCTSchema(ATFolderSchema, folderish=True, moveDiscussion=False)


class IATUnifiedFolder(IATFolder):
    """ marker interface for the new, unified folders """


class ATFolder(ATCTFolderMixin, BaseBTreeFolder):
    """ a folder suitable for holding a very large number of items """
    implements(IATUnifiedFolder, IATBTreeFolder, IArchivable, IPhotoAlbumAble)

    __implements__ = folder_implements

    schema = ATFolderSchema
Exemple #46
0
from zope.event import notify
from zope.interface import implements
from zope.lifecycleevent import ObjectModifiedEvent


def default_start():
    return DT(default_start_dt())

def default_end():
    return DT(default_end_dt())

def first_weekday_sun0():
    return wkday_to_mon1(first_weekday())


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

    atapi.DateTimeField('startDate',
        required=True,
        searchable=False,
        accessor='start',
        write_permission=ModifyPortalContent,
        default_method=default_start,
        languageIndependent=True,
        widget=DatetimeWidget(
            label=_(
                u'label_event_start',
                default=u'Event Starts'
            ),
            description=_(
                u'help_event_start',
     atapi.BooleanField('teaserblock',
                schemata='settings',
                default=0,
                widget=atapi.BooleanWidget(description = "teaser blocks shows their related items (ex. for frontpage)",
                                             description_msgid = "simplelayout_help_teaserblock",
                                             label = "Tick if this block is a teaser",
                                             label_msgid = "simplelayout_label_teaserblock",
                                             i18n_domain = "simplelayout",
                                             )),
),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

paragraph_schema = ATContentTypeSchema.copy() + \
    schema.copy() + textSchema.copy() + imageSchema.copy()

paragraph_schema['excludeFromNav'].default = True
paragraph_schema['title'].required = False
finalize_simplelayout_schema(paragraph_schema)
paragraph_schema['description'].widget.visible = {'edit': 0, 'view': 0}
paragraph_schema['title'].searchable = 0
paragraph_schema.moveField('teaserblock',before="relatedItems")
paragraph_schema['text'].widget.filter_buttons = ('image', )

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class Paragraph(ATDocumentBase):
    """
Exemple #48
0
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from ftw.book import _
from ftw.book.config import PROJECTNAME
from ftw.book.interfaces import IHTMLBlock
from ftw.contentpage.content import textblock
from ftw.contentpage.content.schema import finalize
from zope.interface import implements


if HAS_LINGUA_PLONE:
    from Products.LinguaPlone import public as atapi
else:
    from Products.Archetypes import atapi


htmlblock_schema = ATContentTypeSchema.copy() + \
    textblock.default_schema.copy()

htmlblock_schema['title'].required = False
htmlblock_schema['description'].widget.visible = {'view': 'invisible',
                                                  'edit': 'invisible'}

htmlblock_schema['text'].validators = ()
htmlblock_schema['text'].default_output_type = 'text/html'
htmlblock_schema['text'].widget = atapi.TextAreaWidget(
    label=_(u'label_html', default=u'HTML'),
    description='',
    rows=32,
    cols=70)

finalize(htmlblock_schema)
from Products.Archetypes import atapi
from Products.ATContentTypes.content import base
from Products.ATContentTypes.content import schemata

from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema

from collective.geo.geoserver import geoMessageFactory as _
from collective.geo.geoserver.config import PROJECTNAME
from collective.geo.geoserver.interfaces import IGeoQuery

from AccessControl import ClassSecurityInfo
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName

GeoQuerySchema = ATContentTypeSchema.copy() + atapi.Schema((
    atapi.StringField(
        'layer',
        required=True,
        searchable=False,
        vocabulary_factory='layers_vocabulary',
        widget=atapi.SelectionWidget(
            label=_(u'label_layer', default='Layer'),
            description=_(
                u'help_layer', default=u'Select a layer from the list.'
            ),
        ),
    ),

    atapi.StringField(
        'srid',
Exemple #50
0
from Products.Archetypes.Marshall import PrimaryFieldMarshaller
from Products.COREBlog2.config import PROJECTNAME

#Interfaces
#from Products.CMFPlone.interfaces.NonStructuralFolder import \
#                                                    INonStructuralFolder

from AccessControl import ClassSecurityInfo
from Products.CMFCore.permissions import View,ModifyPortalContent
from Products.CMFCore.utils import getToolByName

from zope.interface import implements
from actions_proxy import updateAliases, base_aliases

COREBlogCategorySchema = ATContentTypeSchema.copy() +  Schema((

    IntegerField('internal_id',
        searchable=False,
        isMetadata=True,
        mutator="setInternal_id",
        widget=IntegerWidget(label='Internal ID',
            description='',
            visible={'view':'invisible','edit':'hidden'},
            ),
        ),

    ImageField('category_image',
        widget=ImageWidget(label='Category image',
            description='',
            label_msgid='label_category_image',
from archetypes.referencebrowserwidget.widget import ReferenceBrowserWidget
from Products.CMFPlone import PloneMessageFactory as _

##/code-section module-header

from config import *

schema = Schema((

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

TCContentReference_schema = ATContentTypeSchema.copy() + \
    schema.copy()

TCContentReference_schema['title'].required=0
TCContentReference_schema['title'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['description'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['subject'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['location'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['rights'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['contributors'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['creators'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['allowDiscussion'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['creators'].widget.visible={'edit':'invisible', 'view':'invisible'}
TCContentReference_schema['creation_date'].widget.visible={'edit':'invisible', 'view':'invisible'}

TCContentReference_schema.changeSchemataForField('relatedItems', 'default')
Exemple #52
0
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.CMFCore import permissions

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

#Logs_schema = BaseFolderSchema.copy() + schema.copy()
Logs_schema = ATContentTypeSchema.copy() + schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class Logs(BaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(BaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'Logs'

    meta_type = 'Logs'
    portal_type = 'Logs'
Exemple #53
0
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.interface import IATFolder
from Products.ATContentTypes.lib.constraintypes import ConstrainTypesMixinSchema
from Products.ATContentTypes.permission import permissions
from Products.Archetypes.atapi import BaseFolder
from Products.CMFCore.utils import getToolByName
from plone.app.folder.base import BaseBTreeFolder
from plone.folder.interfaces import IOrderable
from zope.event import notify
from zope.interface import implementer
from zope.lifecycleevent import ObjectCreatedEvent
from zope.lifecycleevent import ObjectModifiedEvent

ATFolderSchema = ATContentTypeSchema.copy() + ConstrainTypesMixinSchema
finalizeATCTSchema(ATFolderSchema, folderish=True, moveDiscussion=False)


class UnorderedFolder(BaseFolder):
    """ sample unordered (old-style) folder for testing purposes """
    def SearchableText(self):
        return ''


@implementer(IOrderable)
class OrderableFolder(BaseBTreeFolder):
    """ sample ordered btree-based folder (needing the interface) """


@implementer(IATFolder, IOrderedContainer)
from AccessControl import ClassSecurityInfo

from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import StringWidget

from Products.ATContentTypes.config import PROJECTNAME
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 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)
Exemple #55
0
from Products.ATContentTypes.content.base import registerATCT
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.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.permissions import View
from Products.validation import V_REQUIRED
from Products.validation.config import validation
from Products.validation.validators.SupplValidators import MaxSizeValidator
from zope.interface import implementer

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),
            'thumb': (128, 128),
Exemple #56
0
from zope.lifecycleevent import ObjectModifiedEvent


def default_start():
    return DT(default_start_dt())


def default_end():
    return DT(default_end_dt())


def first_weekday_sun0():
    return wkday_to_mon1(first_weekday())


ATEventSchema = ATContentTypeSchema.copy() + atapi.Schema((
    atapi.DateTimeField(
        'startDate',
        required=True,
        searchable=False,
        accessor='start',
        write_permission=ModifyPortalContent,
        default_method=default_start,
        languageIndependent=True,
        widget=DatetimeWidget(
            label=_(u'label_event_start', default=u'Event Starts'),
            description=_(u'help_event_start',
                          default=u"Date and Time, when the event begins."),
            with_time=1,
            first_day=first_weekday_sun0,
        ),
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,)),
    ), marshall=PrimaryFieldMarshaller()
    )