def _Vocabulary(self, content_instance):
        pairs = []
        pc = getToolByName(content_instance, 'portal_catalog')

        allowed_types = self.allowed_types
        allowed_types_method = getattr(self, 'allowed_types_method', None)
        if allowed_types_method:
            meth = getattr(content_instance, allowed_types_method)
            allowed_types = meth(self)

        skw = allowed_types and {'portal_type': allowed_types} or {}
        pc_brains = pc.searchResults(**skw)

        if self.vocabulary_custom_label is not None:
            label = lambda b: eval(self.vocabulary_custom_label, {'b': b})
        elif self.vocabulary_display_path_bound != -1 and len(
            pc_brains) > self.vocabulary_display_path_bound:
            at = _(u'label_at', default=u'at')
            label = lambda b: u'%s %s %s' % (
                self._brains_title_or_id(b, content_instance),
                                             at, b.getPath())
        else:
            label = lambda b: self._brains_title_or_id(b, content_instance)

        for b in pc_brains:
            pairs.append((str(b.intid), label(b)))

        if not self.required and not self.multiValued:
            no_reference = _(u'label_no_reference',
                             default=u'<no reference>')
            pairs.insert(0, ('', no_reference))

        __traceback_info__ = (content_instance, self.getName(), pairs)
        __traceback_info__  # pyflakes
        return DisplayList(pairs)
    def languages(self):
        """Vocabulary method for the language field
        """
        util = None

        use_combined = False
        # Respect the combined language code setting from PloneLanguageTool
        lt = getToolByName(self, 'portal_languages', None)
        if lt is not None:
            use_combined = lt.use_combined_language_codes

        # Try the utility first
        if HAS_PLONE_I18N:
            util = queryUtility(IMetadataLanguageAvailability)
        # Fall back to acquiring availableLanguages
        if util is None:
            languages = getattr(self, 'availableLanguages', None)
            if callable(languages):
                languages = languages()
            # Fall back to static definition
            if languages is None:
                return DisplayList(
                    (('en', 'English'), ('fr', 'French'), ('es', 'Spanish'),
                     ('pt', 'Portuguese'), ('ru', 'Russian')))
        else:
            languages = util.getLanguageListing(combined=use_combined)
            languages.sort(key=lambda x: x[1])
            # Put language neutral at the top.
            languages.insert(0, (u'', _(u'Language neutral')))
        return DisplayList(languages)
Example #3
0
    def languages(self):
        """Vocabulary method for the language field
        """
        util = None

        use_combined = False
        # Respect the combined language code setting from PloneLanguageTool
        lt = getToolByName(self, "portal_languages", None)
        if lt is not None:
            use_combined = lt.use_combined_language_codes

        # Try the utility first
        if HAS_PLONE_I18N:
            util = queryUtility(IMetadataLanguageAvailability)
        # Fall back to acquiring availableLanguages
        if util is None:
            languages = getattr(self, "availableLanguages", None)
            if callable(languages):
                languages = languages()
            # Fall back to static definition
            if languages is None:
                return DisplayList(
                    (("en", "English"), ("fr", "French"), ("es", "Spanish"), ("pt", "Portuguese"), ("ru", "Russian"))
                )
        else:
            languages = util.getLanguageListing(combined=use_combined)
            languages.sort(key=lambda x: x[1])
            # Put language neutral at the top.
            languages.insert(0, (u"", _(u"Language neutral")))
        return DisplayList(languages)
    def validate_content_types(self, instance, value, errors):
        """make sure the value's content-type is allowed"""
        if value in ("DELETE_IMAGE", "DELETE_FILE", None, ''):
            return None
        # plone.app.blob.field.BlobWrapper cannot be imported
        # at startup due to circular imports
        from plone.app.blob.field import BlobWrapper
        body = ''
        if isinstance(value, FileType):
            tell = value.tell()
            value.seek(0)
            body = value.read()
            value.seek(tell)
        elif isinstance(value, StringType):
            body = value
        elif isinstance(value, BlobWrapper):
            body = value.data

        if isinstance(value, (FileType, BlobWrapper)) and body in (None, ''):
            return None

        mtr = getToolByName(instance, 'mimetypes_registry', None)
        if mtr is not None:
            orig_filename = getattr(value, 'filename',
                                    getattr(value, 'name', ''))
            kw = dict(mimetype=None,
                      filename=orig_filename)
            try:
                d, f, mimetype = mtr(body[:8096], **kw)
            except UnicodeDecodeError:
                d, f, mimetype = mtr(len(body) < 8096 and body or '', **kw)
        else:
            mimetype, enc = guess_content_type(
                value.filename, value.read(), None)

        mimetype = str(mimetype).split(';')[0].strip()
        if mimetype not in self.allowable_content_types:
            request = aq_get(instance, 'REQUEST')
            label = self.widget.Label(instance)
            name = self.getName()
            if isinstance(label, Message):
                label = translate(label, context=request)
            error = _(u'error_allowable_content_types',
                      default=u'Mimetype ${mimetype} is not allowed '
                      'on ${name}, please correct.',
                      mapping={
                          'mimetype': mimetype,
                          'name': label
                      })
            error = translate(error, context=request)
            errors[name] = error
            return error

        return
    def __call__(self):
        self.processed = False
        self.errors = {}
        start_time = self.context.ZopeTime().timeTime()
        if not self.request.form.get('form.submitted'):
            return self.template()

        # fetch value from request
        input_encoding = self.request.form.get('input_encoding', 'utf-8')
        span_of_search = self.request.form.get('span_of_search', None)
        format = self.request.form.get('format', 'bib')

        # process source
        filename = None
        source = self.request.form.get('up_text')
        if not source:
            upfile = self.request.form.get('file')
            filename = upfile and getattr(upfile, 'filename', None)
            if not filename:
                self.errors['file'] = _(u'You must import a file or enter a'
                                         ' text.')
                addStatusMessage(self.request,
                                 _(u"Please correct the indicated errors."))
                return self.template()
            source = upfile.read()
            if not source or not isinstance(source, basestring):
                msg = "Could not read the file '%s'." % filename
                self.errors['file'] = msg
                addStatusMessage(self.request, _(unicode(msg)))
                return self.template()

        # skip DOS line breaks
        source = source.replace('\r', '')

        # get parsed entries from the Bibliography Tool
        bibtool = getToolByName(self.context, 'portal_bibliography')
        try:
            entries = bibtool.getEntries(source, format, filename,
                                         input_encoding=input_encoding)
        except ImportParseError:
            msg = """%s Parser's 'checkFormat' and guessing the format""" \
                  """ from the file name '%s' failed.""" % (format,
                                                            filename)
            self.errors['format'] = msg
            addStatusMessage(self.request, _(unicode(msg)))
            return self.template()
        except UnicodeError:
            msg = """The choosen input encoding does not match the real  """ \
                  """encoding of your input data in order to convert it to """\
                  """unicode internally."""
            self.errors['input_encoding'] = msg
            addStatusMessage(self.request, _(unicode(msg)))
            return self.template()
        except RuntimeError, e:
            addStatusMessage(self.request, _(unicode(e)))
            return self.template()
from Products.Archetypes.tests.utils import mkDummyInContext

from Products.Archetypes import PloneMessageFactory as _
from Products.Archetypes import atapi


class DummyDiscussionTool:
    def isDiscussionAllowedFor(self, content):
        return False

    def overrideDiscussionFor(self, content, allowDiscussion):
        pass

MULTIPLEFIELD_LIST = atapi.DisplayList(
    (
    ('1', _(u'Option 1 : printemps')),
    ('2', unicode('Option 2 : \xc3\xa9t\xc3\xa9', 'utf-8')),  # e-acute t e-acute
    ('3', u'Option 3 : automne'),
    ('4', _(u'option3', default=u'Option 3 : hiver')),
    ))

schema = atapi.BaseSchema + atapi.Schema((
    atapi.LinesField(
        'MULTIPLEFIELD',
        searchable=1,
        vocabulary=MULTIPLEFIELD_LIST,
        widget=atapi.MultiSelectionWidget(
            i18n_domain='plone',
            ),
        ),
    atapi.TextField(
## Script (Python) "rejectAnonymous"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##

from Products.Archetypes import PloneMessageFactory as _
from Products.Archetypes.utils import addStatusMessage

if context.portal_membership.isAnonymousUser():

    url = '%s/login_form' % context.portal_url()
    addStatusMessage(REQUEST, _(u'You must sign in first.'), type='info')

    RESPONSE=context.REQUEST.RESPONSE
    return RESPONSE.redirect(url)
return True
Example #8
0
 def getTranslatedSchemaLabel(self, schema):
     label = u"label_schema_%s" % schema
     default = unicode(schema).capitalize()
     return _(label, default=default)
Example #9
0
    def _Vocabulary(self, content_instance):
        """overload 
            Archetypes Products.Archetypes.Field.ReferenceField._Vocabulary to make a restriction on the _path_ for performance gain
            """
        pairs = []
        pc = getToolByName(content_instance, 'portal_catalog')
        uc = getToolByName(content_instance, config.UID_CATALOG)
        purl = getToolByName(content_instance, 'portal_url')

        allowed_types = self.allowed_types
        allowed_types_method = getattr(self, 'allowed_types_method', None)
        if allowed_types_method:
            meth = getattr(content_instance,allowed_types_method)
            allowed_types = meth(self)

        skw = allowed_types and {'portal_type':allowed_types} or {}
        brains = uc.searchResults(skw)

        if self.vocabulary_custom_label is not None:
            label = lambda b:eval(self.vocabulary_custom_label, {'b': b})
        elif self.vocabulary_display_path_bound != -1 and len(brains) > self.vocabulary_display_path_bound:
            at = _(u'label_at', default=u'at')
            label = lambda b:u'%s %s %s' % (self._brains_title_or_id(b, content_instance),
                                             at, b.getPath())
        else:
            label = lambda b:self._brains_title_or_id(b, content_instance)

        # The UID catalog is the correct catalog to pull this
        # information from, however the workflow and perms are not accounted
        # for there. We thus check each object in the portal catalog
        # to ensure it validity for this user.
        portal_base = purl.getPortalPath()
        path_offset = len(portal_base) + 1

        abs_paths = {}
        abs_path = lambda b, p=portal_base: '%s/%s' % (p, b.getPath())

        # modifications
        sd =  (portal_base + 
               "/" + 
               self.widget.getStartupDirectory(
                   content_instance, self)).replace('//', '/')

        for b in brains:
            apath = abs_path(b)
            if apath.startswith(sd):
                abs_paths.update({apath:b}) 
        # end modifications

        pc_brains = pc(path=abs_paths.keys(), **skw)

        for b in pc_brains:
            b_path = b.getPath()
            # translate abs path to rel path since uid_cat stores
            # paths relative now
            path = b_path[path_offset:]
            # The reference field will not expose Refrerences by
            # default, this is a complex use-case and makes things too hard to
            # understand for normal users. Because of reference class
            # we don't know portal type but we can look for the annotation key in
            # the path
            if self.referenceReferences is False and \
               path.find(config.REFERENCE_ANNOTATION) != -1:
                continue

            # now check if the results from the pc is the same as in uc.
            # so we verify that b is a result that was also returned by uc,
            # hence the check in abs_paths.
            if abs_paths.has_key(b_path):
                uid = abs_paths[b_path].UID
                if uid is None:
                    # the brain doesn't have an uid because the catalog has a
                    # staled object. THAT IS BAD!
                    raise ReferenceException("Brain for the object at %s "\
                        "doesn't have an UID assigned with. Please update your"\
                        " reference catalog!" % b_path)
                pairs.append((uid, label(b)))

        if not self.required and not self.multiValued:
            no_reference = _(u'label_no_reference',
                             default=u'<no reference>')
            pairs.insert(0, ('', no_reference))

        __traceback_info__ = (content_instance, self.getName(), pairs)

        return DisplayList(pairs) 
    def getWidgets(self, instance=None,
                   package=None, type=None,
                   context=None, mode='edit',
                   fields=None, schemata=None, nosort=None):
        """Empty widgets for standalone rendering.
        """
        widgets = []
        w_keys = {}
        context = context is not None and context or self
        instances = instance is not None and [instance] or []
        f_names = fields
        if not instances:
            for t in self.listTypes(package, type):
                instance = t('fake_instance')
                instance._at_is_fake_instance = True
                wrapped = instance.__of__(context)
                wrapped.initializeArchetype()
                instances.append(wrapped)
        for instance in instances:
            if schemata is not None:
                schema = instance.Schemata()[schemata].copy()
            else:
                schema = instance.Schema().copy()
            fields = schema.fields()
            if mode == 'search':
                # Include only fields which have an index
                # XXX duplicate fieldnames may break this,
                # as different widgets with the same name
                # on different schemas means only the first
                # one found will be used
                indexes = self.portal_catalog.indexes()
                fields = [f for f in fields
                          if (f.accessor and
                              not f.accessor in w_keys
                              and f.accessor in indexes)]
            if f_names is not None:
                fields = filter(lambda f: f.getName() in f_names, fields)
            for field in fields:
                widget = field.widget
                field_name = field.getName()
                accessor = field.getAccessor(instance)
                if mode == 'search':
                    field.required = False
                    field.addable = False  # for ReferenceField
                    if not isinstance(field.vocabulary, DisplayList):
                        field.vocabulary = field.Vocabulary(instance)
                    if '' not in field.vocabulary.keys():
                        field.vocabulary = DisplayList([('', _(u'at_search_any', default=u'<any>'))]) + \
                            field.vocabulary
                    widget.populate = False
                    field_name = field.accessor
                    # accessor must be a method which doesn't take an argument
                    # this lambda is facking an accessor
                    accessor = lambda: field.getDefault(instance)

                w_keys[field_name] = None
                widgets.append((field_name, WidgetWrapper(
                    field_name=field_name,
                    mode=mode,
                    widget=widget,
                    instance=instance,
                    field=field,
                    accessor=accessor)))
        if mode == 'search' and nosort == None:
            widgets.sort()
        return [widget for name, widget in widgets]
Example #11
0
REQUEST = context.REQUEST
old_id = context.getId()

try:
    new_context = context.portal_factory.doCreate(context, id)
except AttributeError:
    # Fallback for AT + plain CMF where we don't have a portal_factory
    new_context = context
new_context.processForm()

# Get the current language and put it in request/LANGUAGE
form = REQUEST.form
if 'current_lang' in form:
    form['language'] = form.get('current_lang')

portal_status_message = _(u'Changes saved.')

# handle navigation for multi-page edit forms
next = not REQUEST.get('form.button.next', None) is None
previous = not REQUEST.get('form.button.previous', None) is None
fieldset = REQUEST.get('fieldset', None)
schemata = new_context.Schemata()

if next or previous:
    s_names = [s for s in schemata.keys() if s != 'metadata']

    if previous:
        s_names.reverse()

    next_schemata = None
    try:
Example #12
0
from Products.Archetypes import PloneMessageFactory as _
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.utils import DisplayList
from Products.ATContentTypes.content import schemata
from Products.ATContentTypes.content.schemata import marshall_register
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.base import ATCTMixin
from Products.ATContentTypes.content.document import ATDocument
from Products.ATContentTypes.content.folder import ATFolder, ATBTreeFolder
from Products.ATContentTypes.content.image import ATImage
from Products.ATContentTypes.content.event import ATEvent
from Products.ATContentTypes.content.file import ATFile
from Products.ATContentTypes.content.newsitem import ATNewsItem

new_subject_widget = AutocompleteWidget(
    label=_(u'label_categories', default = u'Categories'),
    description=_(u'help_categories',
                  default = u'Also known as keywords, tags or labels, '
                           'these help you categorize your content.'),
    actb_filter_bogus = 0,
    actb_expand_onfocus = 0,
    maxlength='1024'
 	)

def getKeywords(self):
    portal_catalog = getToolByName(self, 'portal_catalog')
    res = portal_catalog.uniqueValuesFor('Subject')
    return DisplayList(zip(res,res))

ATCTMixin.getKeywords = getKeywords 	
Example #13
0
_marker = []

content_type = Schema(
    (
        StringField(
            name="id",
            required=0,  # Still actually required, but the widget will
            # supply the missing value on non-submits
            mode="rw",
            permission=permission_copy_or_move,
            accessor="getId",
            mutator="setId",
            default=None,
            widget=IdWidget(
                label=_(u"label_short_name", default=u"Short Name"),
                description=_(
                    u"help_shortname",
                    default=u"Should not contain spaces, underscores or mixed case. "
                    "Short Name is part of the item's web address.",
                ),
                visible={"view": "invisible"},
            ),
        ),
        StringField(
            name="title",
            required=1,
            searchable=1,
            default="",
            accessor="Title",
            widget=StringWidget(label_msgid="label_title", visible={"view": "invisible"}, i18n_domain="plone"),
Example #14
0
from App.class_init import InitializeClass
from Acquisition import aq_base
from Acquisition import aq_inner
from ExtensionClass import Base
from zope.interface import implements

TemplateMixinSchema = Schema(
    (
        # TemplateMixin
        StringField(
            "layout",
            write_permission=permissions.ModifyPortalContent,
            default_method="getDefaultLayout",
            vocabulary="_voc_templates",
            widget=SelectionWidget(
                label=_(u"label_template_mixin", default=u"View template"),
                description=_(
                    u"help_template_mixin", default=u"Choose a template that will be used for viewing this item."
                ),
                visible={"view": "hidden", "edit": "visible"},
            ),
        ),
    )
)


class TemplateMixin(Base):
    implements(ITemplateMixin)

    schema = TemplateMixinSchema
Example #15
0
    def get_translated_validation_messages(self):
        context = aq_inner(self.context)
        request = context.REQUEST
        fieldnames = {
            'organisation': translate(_('Company/Organisation')),
            'address': translate(_('Address')),
            'postal_code': translate(_('Postal Code')),
            'city': translate(_('City')),
            'country': translate(_('Country')),
            'firstname': translate(_('Firstname')),
            'lastname': translate(_('Lastname')),
            'sector': translate(_('Sector')),
            'email': translate(_('Email')),
            'telephone': translate(_('Telephone')),
            }
        lang = context.portal_languages.getPreferredLanguage()
        messages = {}

        for field_id in fieldnames:
            fieldname = fieldnames[field_id]
            err_msgs = {
                'required': translate(
                            _(u'error_required',
                            default=u'${name} is required, please correct.',
                            mapping={'name': fieldname}),
                            context=request,
                            ),

                'email': translate(
                            _(u"You entered an invalid email address."),
                            context=request,
                            ),
                }

            messages[field_id] = err_msgs

        return {'messages': messages}
from Products.CMFCore import permissions, utils
from AccessControl import ClassSecurityInfo
from App.class_init import InitializeClass
from Acquisition import aq_base
from Acquisition import aq_inner
from ExtensionClass import Base
from zope.interface import implements


TemplateMixinSchema = Schema((
    # TemplateMixin
    StringField('layout',
                write_permission=permissions.ModifyPortalContent,
                default_method="getDefaultLayout",
                vocabulary="_voc_templates",
                widget=SelectionWidget(label=_(u'label_template_mixin',
                                               default=u'View template'),
                                       description=_(u'help_template_mixin',
                                                     default=u'Choose a template that will be used for viewing this item.'),
                                       visible={'view': 'hidden',
                                                'edit': 'visible'},)
                ),
))


class TemplateMixin(Base):
    implements(ITemplateMixin)

    schema = TemplateMixinSchema

    actions = (
        {'id': 'view',
from Products.Archetypes import PloneMessageFactory as _
from Products.Archetypes.atapi import *


class DummyDiscussionTool:
    def isDiscussionAllowedFor(self, content):
        return False

    def overrideDiscussionFor(self, content, allowDiscussion):
        pass


MULTIPLEFIELD_LIST = DisplayList(
    (
        ("1", _(u"Option 1 : printemps")),
        ("2", unicode("Option 2 : \xc3\xa9t\xc3\xa9", "utf-8")),  # e-acute t e-acute
        ("3", u"Option 3 : automne"),
        ("4", _(u"option3", default=u"Option 3 : hiver")),
    )
)

schema = BaseSchema + Schema(
    (
        LinesField(
            "MULTIPLEFIELD",
            searchable=1,
            vocabulary=MULTIPLEFIELD_LIST,
            widget=MultiSelectionWidget(i18n_domain="plone"),
        ),
        TextField("TEXTFIELD", primary=True),
     subfields = ('label', 'value'),
     subfield_labels ={'label':'Identifier'},
     subfield_vocabularies = {'label':'publicationIdentifiers',},      
     widget=RecordsWidget(
             i18n_domain = "cmfbibliographyat",
             label = u"Identifiers",
             ),
     ),
 LinesField('keywords',
     searchable=1,
     required=0,
     languageIndependent=1,
     is_duplicates_criterion=False,
     multiValued=1,
     widget=KeywordWidget(
             label=_(u'label_keywords', default=u'Keywords'),
             description=_(u'help_keywords',
                           default=u'Categorization of the publications content.'),
             i18n_domain = "cmfbibliographyat",
             ),
     ),
 StringField('publication_month',
     searchable=1,
     required=0,
     languageIndependent=1,
     is_duplicates_criterion=True,
     widget=StringWidget(
         label="Publication Month",
         label_msgid="label_publication_month",
         description_msgid="help_publication_month",
         description="Month of publication (or writing, if not published).",
REQUEST = context.REQUEST
old_id = context.getId()

try:
    new_context = context.portal_factory.doCreate(context, id)
except AttributeError:
    # Fallback for AT + plain CMF where we don't have a portal_factory
    new_context = context
new_context.processForm()

# Get the current language and put it in request/LANGUAGE
form = REQUEST.form
if form.has_key('current_lang'):
    form['language'] = form.get('current_lang')

portal_status_message = _(u'Changes saved.')

# handle navigation for multi-page edit forms
next = not REQUEST.get('form.button.next', None) is None
previous = not REQUEST.get('form.button.previous', None) is None
fieldset = REQUEST.get('fieldset', None)
schemata = new_context.Schemata()

if next or previous:
    s_names = [s for s in schemata.keys() if s != 'metadata']

    if previous:
        s_names.reverse()

    next_schemata = None
    try:
Example #20
0
_marker = []

content_type = Schema((

    StringField(
        name='id',
        required=0, # Still actually required, but the widget will
                    # supply the missing value on non-submits
        mode='rw',
        permission=permission_copy_or_move,
        accessor='getId',
        mutator='setId',
        default=None,
        widget=IdWidget(
            label=_(u'label_short_name', default=u'Short Name'),
            description=_(u'help_shortname',
                          default=u'Should not contain spaces, underscores or mixed case. '
                                   'Short Name is part of the item\'s web address.'),
            visible={'view' : 'invisible'}
        ),
    ),

    StringField(
        name='title',
        required=1,
        searchable=1,
        default='',
        accessor='Title',
        widget=StringWidget(
            label_msgid='label_title',
Example #21
0
# make the description field of NewsItems render HTML
description = TextField('description',
              required=False,
              searchable=True,
              accessor="Description",
              mutator='setDescription',
              edit_accessor="getRawDescription",
              isMetadata=True,
              storage=MetadataStorage(),
              generateMode="mVc",
              validators=('isTidyHtmlWithCleanup', ),
              default_output_type='text/x-html-safe',
              allowable_content_type=('text/html', 'text/x-html-safe'),
              schemata='default',
              widget=RichWidget(
                    label=_(u'label_description', default=u'Description'),
                    description=_(u'help_description',
                        default=u'A short summary of the content.'),
                    rows=25,
                    allow_file_upload=zconf.ATDocument.allow_document_upload)
              )


del ATNewsItemSchema['description']
ATNewsItemSchema.addField(description)
ATNewsItemSchema.moveField('description', after='title')

finalizeATCTSchema(ATNewsItemSchema)