Ejemplo n.º 1
0
    def _fields(self):
        """
        """
        context = self.context
        behavior_fields = []

        # Stap 1 metadata
        behavior_assignable = IBehaviorAssignable(context)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            for behavior in behaviors:
                behavior_fields += getFieldsInOrder(behavior.interface)

        # Stap 2 eigen velden
        fti = context.getTypeInfo()
        schema = fti.lookupSchema()
        content_fields = getFieldsInOrder(schema)
        fields = behavior_fields
        fields += content_fields
        
#        for field_info in fields:
#            try:
#                field_name = field_info[0]
#                field = field_info[1]
#                print field_info
#                print getattr(context, field_name)
#            except Exception, e:
#                pass
            
        return fields
Ejemplo n.º 2
0
    def __getattr__(self, name):
        # python basics:  __getattr__ is only invoked if the attribute wasn't
        # found by __getattribute__
        #
        # optimization: sometimes we're asked for special attributes
        # such as __conform__ that we can disregard (because we
        # wouldn't be in here if the class had such an attribute
        # defined).
        # also handle special dynamic providedBy cache here.
        if name.startswith('__') or name == '_v__providedBy__':
            raise AttributeError(name)

        # attribute was not found; try to look it up in the schema and return
        # a default
        value = _default_from_schema(self, SCHEMA_CACHE.get(self.portal_type),
                                     name)
        if value is not _marker:
            return value

        # do the same for each subtype
        assignable = IBehaviorAssignable(self, None)
        if assignable is not None:
            for behavior_registration in assignable.enumerateBehaviors():
                if behavior_registration.interface:
                    value = _default_from_schema(
                        self, behavior_registration.interface, name)
                    if value is not _marker:
                        return value

        raise AttributeError(name)
Ejemplo n.º 3
0
def researh_fields_dexterity(item):
    # Get fields from schema
    fields = {
        "created": {
            "type": "datetime"
        },
        "modified": {
            "type": "datetime"
        },
        "immediately_addable_types": {
            "type": "lines"
        },
        "locally_allowed_types": {
            "type": "lines"
        },
        "constrain_types_mode": {
            "type": "integer"
        },
    }
    for field_name, field_instance in getFieldsInOrder(
            item.getTypeInfo().lookupSchema()):
        fields[field_name] = parse_field_dexterity(field_name, field_instance)

    # Get fields from behaviors
    behavior_assignable = IBehaviorAssignable(item)
    if behavior_assignable:
        behaviors = behavior_assignable.enumerateBehaviors()
        for behavior in behaviors:
            for field_name, field_instance in getFieldsInOrder(
                    behavior.interface):
                fields[field_name] = parse_field_dexterity(
                    field_name, field_instance)

    return fields
Ejemplo n.º 4
0
    def copy_fields_dexterity(self, source, target):
        # Copy the content from the canonical fields
        try:
            fields = schema.getFieldsInOrder(
                source.getTypeInfo().lookupSchema())  # noqa
        except AttributeError as e:
            log.info("Error: %s" % "/".join(source.getPhysicalPath()))
            log.exception(e)
            return
        for key, value in fields:
            if key.lower() in SKIPPED_FIELDS_DX:
                # skip language
                log.info("Skipped %s" % key)
                continue
            self.change_content(source, target, key, value)

        # Copy the contents from behaviors
        behavior_assignable = IBehaviorAssignable(source)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            for behavior in behaviors:
                for key, value in getFieldsInOrder(behavior.interface):
                    if key.lower() in SKIPPED_FIELDS_DX:
                        # skip language
                        log.info("Skipped %s" % key)
                        continue
                    self.change_content_for_behavior(source, target, key,
                                                     behavior.interface)
Ejemplo n.º 5
0
    def __call__(self):
        context = aq_inner(self.context)
        fieldname = self.request.get('fieldname')
        portal_type = self.request.get('portal_type')
        
        fti = zope.component.getUtility(IDexterityFTI, name=portal_type)
        schema = fti.lookupSchema()

        field = schema.get(fieldname)
        if field is None:
            # The field might be defined in a behavior schema
            behavior_assignable = IBehaviorAssignable(context, None)
            for behavior_reg in behavior_assignable.enumerateBehaviors():
                behavior_schema = IFormFieldProvider(behavior_reg.interface, None)
                if behavior_schema is not None:
                    field = behavior_schema.get(fieldname)
                    if field is not None:
                        break

        vname = field.vocabularyName
        factory = zope.component.getUtility(IVocabularyFactory, vname)
        tree = factory(context)
        # XXX: "selected" is not set in input.pt, so does it make sense to check
        # for it here? Only if this json view is called elsewhere, which
        # doesn't seem to be the case...
        selected = self.request.get('selected', '').split('|')
        return JSONWriter().write(dict2dynatree(tree, selected, True, False))
Ejemplo n.º 6
0
    def grabDexterityData(self, obj):
        """
        Export Dexterity schema data as dictionary object.
        Snippets taken from
        https://www.andreas-jung.com/contents
        """
        data = {}
        for key in EXPORT_ATTRIBUTES:
            data[key] = getattr(obj, key, None)

        from plone.dexterity.interfaces import IDexterityFTI
        from plone.behavior.interfaces import IBehaviorAssignable
        from zope.component import getUtility
        schema = getUtility(IDexterityFTI, name=obj.portal_type).lookupSchema()
        fields = [(name, schema, schema[name]) for name in schema]

        assignable = IBehaviorAssignable(obj)
        for behavior in assignable.enumerateBehaviors():
            behavior_schema = behavior.interface
            for name in behavior_schema:
                fields.append((name, behavior_schema, behavior_schema[name]))

        for name, schema_adaptor, field in fields:
            source_adapted = schema_adaptor(obj)
            data[name] = getattr(source_adapted, field.getName())
        return data
Ejemplo n.º 7
0
def get_soundfile_field(context):
    assignable = IBehaviorAssignable(context, None)
    if assignable is None:
        return
    for behavior_registration in assignable.enumerateBehaviors():
        schema = behavior_registration.interface
        for tgv in mergedTaggedValueList(schema, SOUNDFILE_KEY):
            if tgv.soundfile:
                return tgv.soundfile
Ejemplo n.º 8
0
def get_dx_schema(context):
    schema = dict(getFieldsInOrder(context.getTypeInfo().lookupSchema()))

    behavior_assignable = IBehaviorAssignable(context)
    if behavior_assignable:
        for behavior in behavior_assignable.enumerateBehaviors():
            for k, v in getFieldsInOrder(behavior.interface):
                schema[k] = v

    return schema
Ejemplo n.º 9
0
def get_obj_schema(obj):
    for iface in providedBy(obj).flattened():
        for name, field in getFields(iface).items():
            yield name, field

    assignable = IBehaviorAssignable(obj, None)
    if assignable:
        for behavior in assignable.enumerateBehaviors():
            for name, field in getFields(behavior.interface).items():
                yield name, field
Ejemplo n.º 10
0
def get_dx_schema(context):
    schema = dict(getFieldsInOrder(context.getTypeInfo().lookupSchema()))

    behavior_assignable = IBehaviorAssignable(context)
    if behavior_assignable:
        for behavior in behavior_assignable.enumerateBehaviors():
            for k, v in getFieldsInOrder(behavior.interface):
                schema[k] = v

    return schema
Ejemplo n.º 11
0
    def __get__(self, inst, cls=None):
        if inst is None:
            return getObjectSpecification(cls)

        request = getRequest()
        annotations = IAnnotations(request)

        try:
            digest = inst.schema_digest
        except AttributeError:
            spec = getattr(inst, '__provides__', None)
            if spec is None:
                return implementedBy(cls)
            else:
                return spec

        # Return cached spec from request
        if not getattr(self, '__recursion__', False):
            spec = annotations.get(self.__class__.__name__ + '.' + digest)
            if spec is not None:
                return spec

        spec = getattr(inst, '__provides__', None)
        if spec is None:
            spec = implementedBy(cls)

        model = load_model(inst.schema, cache_key=inst.schema_digest)
        schemata = [
            model.schemata[name] for name in model.schemata
            if name in [u'', u'++add++']
            or IS_TRANSLATION.match(name.split(u'++add++')[0])
        ]
        schemata.append(spec)

        if getattr(self, '__recursion__', False):
            return Implements(*schemata)

        self.__recursion__ = True
        dynamically_provided = []
        try:
            assignable = IBehaviorAssignable(inst, None)
            if assignable is not None:
                for behavior_registration in assignable.enumerateBehaviors():
                    if behavior_registration.marker:
                        dynamically_provided.append(
                            behavior_registration.marker, )
        finally:
            del self.__recursion__

        schemata.extend(dynamically_provided)
        spec = Implements(*schemata)

        # Cache spec into request
        annotations[self.__class__.__name__ + '.' + digest] = spec
        return spec
Ejemplo n.º 12
0
    def get_field_data(self):
        from plone.dexterity.interfaces import IDexterityFTI
        from plone.behavior.interfaces import IBehaviorAssignable

        data = {}

        schema = getUtility(IDexterityFTI,
                            name=self.obj.portal_type).lookupSchema()
        for name, field in getFieldsInOrder(schema):
            data[name] = getattr(self.obj, name, None)

        behavior_assignable = IBehaviorAssignable(self.obj)
        for behavior in behavior_assignable.enumerateBehaviors():
            binst = behavior.interface(self.obj)
            bdata = {}
            for name, field in getFieldsInOrder(behavior.interface):
                bdata[name] = getattr(binst, name, None)
            data[behavior.interface.__identifier__] = bdata

        if ILayoutAware.providedBy(self.obj):
            from plone.tiles.data import ANNOTATIONS_KEY_PREFIX
            from plone.app.blocks.utils import getLayout
            from repoze.xmliter.utils import getHTMLSerializer
            from plone.app.blocks import tiles
            from plone.app.blocks import gridsystem
            from lxml.html import tostring
            tdata = {}
            annotations = IAnnotations(self.obj, {})
            for key in annotations.keys():
                if key.startswith(ANNOTATIONS_KEY_PREFIX):
                    adata = annotations[key]
                    tdata[key] = adata
            data['tile_data'] = tdata

            req = site.REQUEST
            layout = getLayout(self.obj)
            dom = getHTMLSerializer(layout)

            try:
                tiles.renderTiles(req,
                                  dom.tree,
                                  site=site,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            except TypeError:
                tiles.renderTiles(req,
                                  dom.tree,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            gridsystem.merge(req, dom.tree)

            data['rendered_layout'] = tostring(dom.tree)

        return data
Ejemplo n.º 13
0
def get_soundcloud_accessors(context):
    accessors = []
    assignable = IBehaviorAssignable(context, None)
    if assignable is None:
        return accessors
    for behavior_registration in assignable.enumerateBehaviors():
        schema = behavior_registration.interface
        for tgv in mergedTaggedValueList(schema, SOUNDCLOUD_KEY):
            for accessor in tgv.accessors:
                accessors.append((schema, accessor,))
    return accessors
Ejemplo n.º 14
0
 def _all_fields(self):
     type_info = self.context.getTypeInfo()
     if type_info is None:
         return
     schema = type_info.lookupSchema()
     for field in getFieldsInOrder(schema):
         yield field
     behavior_assignable = IBehaviorAssignable(self.context)
     if behavior_assignable:
         for behavior in behavior_assignable.enumerateBehaviors():
             for field in getFieldsInOrder(behavior.interface):
                 yield field
Ejemplo n.º 15
0
def applyMarkers(obj, event):
    """Event handler to apply markers for all behaviors enabled
    for the given type.
    """

    assignable = IBehaviorAssignable(obj, None)
    if assignable is None:
        return

    for behavior in assignable.enumerateBehaviors():
        if behavior.marker is not None:
            alsoProvides(obj, behavior.marker)
Ejemplo n.º 16
0
def applyMarkers(obj, event):
    """Event handler to apply markers for all behaviors enabled
    for the given type.
    """
    
    assignable = IBehaviorAssignable(obj, None)
    if assignable is None:
        return
        
    for behavior in assignable.enumerateBehaviors():
        if behavior.marker is not None:
            alsoProvides(obj, behavior.marker)
Ejemplo n.º 17
0
 def get_behaviors(self):
     """ Iterate over all behaviors that are assigned to the object
     Used code from @tisto:
     https://github.com/plone/plone.restapi/blob/master/src/plone/restapi/utils.py
     """
     out = {}
     assignable = IBehaviorAssignable(self.context, None)
     if not assignable:
         return out
     for behavior in assignable.enumerateBehaviors():
         for name, field in getFields(behavior.interface).items():
             out[name] = field
     return out
Ejemplo n.º 18
0
 def get_behaviors(self):
     """ Iterate over all behaviors that are assigned to the object
     Used code from @tisto:
     https://github.com/plone/plone.restapi/blob/master/src/plone/restapi/utils.py
     """
     out = {}
     assignable = IBehaviorAssignable(self.context, None)
     if not assignable:
         return out
     for behavior in assignable.enumerateBehaviors():
         for name, field in getFields(behavior.interface).items():
             out[name] = field
     return out
Ejemplo n.º 19
0
        def _image_field_info(self):
            type_info = self.context.getTypeInfo()
            schema = type_info.lookupSchema()
            fields = getFieldsInOrder(schema)

            behavior_assignable = IBehaviorAssignable(self.context)
            if behavior_assignable:
                behaviors = behavior_assignable.enumerateBehaviors()
                for behavior in behaviors:
                    fields += getFieldsInOrder(behavior.interface)

            for fieldname, field in fields:
                img_field = getattr(self.context, fieldname, None)
                if img_field and IImage.providedBy(img_field):
                    yield (fieldname, img_field)
Ejemplo n.º 20
0
        def _image_field_info(self):
            type_info = self.context.getTypeInfo()
            schema = type_info.lookupSchema()
            fields = getFieldsInOrder(schema)

            behavior_assignable = IBehaviorAssignable(self.context)
            if behavior_assignable:
                behaviors = behavior_assignable.enumerateBehaviors()
                for behavior in behaviors:
                    fields += getFieldsInOrder(behavior.interface)

            for fieldname, field in fields:
                img_field = getattr(self.context, fieldname, None)
                if img_field and IImage.providedBy(img_field):
                    yield (fieldname, img_field)
Ejemplo n.º 21
0
    def can_be_division(self):
        ''' Check if this object can be a division,
        i.e. has a division field in the schema or in a behavior
        '''
        schema = self.context.getTypeInfo().lookupSchema()
        if 'is_division' in getFieldNames(schema):
            return True

        behavior_assignable = IBehaviorAssignable(self.context)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            for behavior in behaviors:
                if 'is_division' in getFieldNames(schema):
                    return True
        return False
Ejemplo n.º 22
0
def getAdditionalSchemata(context=None, portal_type=None):
    """Get additional schemata for this context or this portal_type.

    Additional schemata can be defined in behaviors.

    Usually either context or portal_type should be set, not both.
    The idea is that for edit forms or views you pass in a context
    (and we get the portal_type from there) and for add forms you pass
    in a portal_type (and the context is irrelevant then).  If both
    are set, the portal_type might get ignored, depending on which
    code path is taken.
    """
    log.debug("getAdditionalSchemata with context %r and portal_type %s",
              context, portal_type)
    if context is None and portal_type is None:
        return
    if context:
        behavior_assignable = IBehaviorAssignable(context, None)
    else:
        behavior_assignable = None
    if behavior_assignable is None:
        log.debug("No behavior assignable found, only checking fti.")
        # Usually an add-form.
        if portal_type is None:
            portal_type = context.portal_type
        fti = getUtility(IDexterityFTI, name=portal_type)
        for behavior_name in fti.behaviors:
            behavior_interface = None
            behavior_instance = queryUtility(IBehavior, name=behavior_name)
            if not behavior_instance:
                try:
                    behavior_interface = resolveDottedName(behavior_name)
                except (ValueError, ImportError):
                    log.warning("Error resolving behaviour %s", behavior_name)
                    continue
            else:
                behavior_interface = behavior_instance.interface

            if behavior_interface is not None:
                behavior_schema = IFormFieldProvider(behavior_interface, None)
                if behavior_schema is not None:
                    yield behavior_schema
    else:
        log.debug("Behavior assignable found for context.")
        for behavior_reg in behavior_assignable.enumerateBehaviors():
            behavior_schema = IFormFieldProvider(behavior_reg.interface, None)
            if behavior_schema is not None:
                yield behavior_schema
Ejemplo n.º 23
0
def getAdditionalSchemata(context=None, portal_type=None):
    """Get additional schemata for this context or this portal_type.

    Additional schemata can be defined in behaviors.

    Usually either context or portal_type should be set, not both.
    The idea is that for edit forms or views you pass in a context
    (and we get the portal_type from there) and for add forms you pass
    in a portal_type (and the context is irrelevant then).  If both
    are set, the portal_type might get ignored, depending on which
    code path is taken.
    """
    log.debug("getAdditionalSchemata with context %r and portal_type %s",
              context, portal_type)
    if context is None and portal_type is None:
        return
    if context:
        behavior_assignable = IBehaviorAssignable(context, None)
    else:
        behavior_assignable = None
    if behavior_assignable is None:
        log.debug("No behavior assignable found, only checking fti.")
        # Usually an add-form.
        if portal_type is None:
            portal_type = context.portal_type
        fti = getUtility(IDexterityFTI, name=portal_type)
        for behavior_name in fti.behaviors:
            behavior_interface = None
            behavior_instance = queryUtility(IBehavior, name=behavior_name)
            if not behavior_instance:
                try:
                    behavior_interface = resolveDottedName(behavior_name)
                except (ValueError, ImportError):
                    log.warning("Error resolving behaviour %s", behavior_name)
                    continue
            else:
                behavior_interface = behavior_instance.interface

            if behavior_interface is not None:
                behavior_schema = IFormFieldProvider(behavior_interface, None)
                if behavior_schema is not None:
                    yield behavior_schema
    else:
        log.debug("Behavior assignable found for context.")
        for behavior_reg in behavior_assignable.enumerateBehaviors():
            behavior_schema = IFormFieldProvider(behavior_reg.interface, None)
            if behavior_schema is not None:
                yield behavior_schema
Ejemplo n.º 24
0
def get_all_fields(context):
    """ Return all fields (including behavior fields) of a context object
        as dict fieldname -> field.
    """

    schema = zope.component.getUtility(
        IDexterityFTI, name=context.portal_type).lookupSchema()
    fields = dict((fieldname, schema[fieldname]) for fieldname in schema)

    assignable = IBehaviorAssignable(context)
    for behavior in assignable.enumerateBehaviors():
        behavior_schema = behavior.interface
        fields.update((name, behavior_schema[name])
                      for name in behavior_schema)

    return fields
def get_all_fields(context):
    """ Return all fields (including behavior fields) of a context object
        as dict fieldname -> field.
    """

    schema = zope.component.getUtility(
        IDexterityFTI, name=context.portal_type).lookupSchema()
    fields = dict((fieldname, schema[fieldname]) for fieldname in schema)

    assignable = IBehaviorAssignable(context)
    for behavior in assignable.enumerateBehaviors():
        behavior_schema = behavior.interface
        fields.update(
            (name, behavior_schema[name]) for name in behavior_schema)

    return fields
Ejemplo n.º 26
0
def get_object_schema(obj):
    object_schema = set()
    for iface in providedBy(obj).flattened():
        for name, field in getFields(iface).items():
            no_underscore_method = not name.startswith('_')
            no_manage_method = not name.startswith('manage')
            if no_underscore_method and no_manage_method:
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field

    assignable = IBehaviorAssignable(obj, None)
    if assignable:
        for behavior in assignable.enumerateBehaviors():
            for name, field in getFields(behavior.interface).items():
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field
Ejemplo n.º 27
0
def get_object_schema(obj):
    object_schema = set()
    for iface in providedBy(obj).flattened():
        for name, field in getFields(iface).items():
            no_underscore_method = not name.startswith('_')
            no_manage_method = not name.startswith('manage')
            if no_underscore_method and no_manage_method:
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field

    assignable = IBehaviorAssignable(obj, None)
    if assignable:
        for behavior in assignable.enumerateBehaviors():
            for name, field in getFields(behavior.interface).items():
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field
Ejemplo n.º 28
0
def get_behaviors(brain_or_object):
    """Iterate over all behaviors that are assigned to the object

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: Behaviors
    :rtype: list
    """
    obj = get_object(brain_or_object)
    if not is_dexterity_content(obj):
        fail(400, "Only Dexterity contents can have assigned behaviors")
    assignable = IBehaviorAssignable(obj, None)
    if not assignable:
        return {}
    out = {}
    for behavior in assignable.enumerateBehaviors():
        for name, field in getFields(behavior.interface).items():
            out[name] = field
    return out
Ejemplo n.º 29
0
        def fieldFilter():
            portal_type = self.context.getPortalTypeName()
            fti = getUtility(IDexterityFTI, name=portal_type)
            schema = fti.lookupSchema()
            fields = getFieldsInOrder(schema)
            assignable = IBehaviorAssignable(self.context, None)
            for behavior in assignable.enumerateBehaviors():
                if behavior.marker:
                    new_fields = getFieldsInOrder(behavior.marker)
                    if len(new_fields) > 0:
                        fields = fields + new_fields

            obj_fields = []
            for key, value in fields:
                is_image = INamedImageField.providedBy(value)
                is_file = INamedBlobFileField.providedBy(value)
                if is_image or is_file:
                    obj_fields.append(value)
            return obj_fields
Ejemplo n.º 30
0
def get_behaviors(brain_or_object):
    """Iterate over all behaviors that are assigned to the object

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: Behaviors
    :rtype: list
    """
    obj = get_object(brain_or_object)
    if not is_dexterity_content(obj):
        fail(400, "Only Dexterity contents can have assigned behaviors")
    assignable = IBehaviorAssignable(obj, None)
    if not assignable:
        return {}
    out = {}
    for behavior in assignable.enumerateBehaviors():
        for name, field in getFields(behavior.interface).items():
            out[name] = field
    return out
Ejemplo n.º 31
0
        def fieldFilter():
            portal_type = self.context.getPortalTypeName()
            fti = getUtility(IDexterityFTI, name=portal_type)
            schema = fti.lookupSchema()
            fields = getFieldsInOrder(schema)
            assignable = IBehaviorAssignable(self.context, None)
            for behavior in assignable.enumerateBehaviors():
                if behavior.marker:
                    new_fields = getFieldsInOrder(behavior.marker)
                    if len(new_fields) > 0:
                        fields = fields + new_fields

            obj_fields = []
            for key, value in fields:
                is_image = INamedImageField.providedBy(value)
                is_file = INamedBlobFileField.providedBy(value)
                if is_image or is_file:
                    obj_fields.append(value)
            return obj_fields
Ejemplo n.º 32
0
def all_dexterity_fieldnames(obj):
    "the schema from FTI plus query IBehaviorAssignable"

    try:
        typename = obj.getPortalTypeName()
        fti = getUtility(IDexterityFTI, name=typename)
    except ComponentLookupError as exc:
        # has no fti, what is this, an ancient Archetype?
        return []

    schema = fti.lookupSchema()
    fields = [getFieldsInOrder(schema)]

    behavior_assignable = IBehaviorAssignable(obj)
    if behavior_assignable:
        behaviors = behavior_assignable.enumerateBehaviors()
        for behavior in behaviors:
            fields.append(getFieldsInOrder(behavior.interface))

    return [fn for fn, f in chain(*fields)]
Ejemplo n.º 33
0
def extract_relations(obj):
    assignable = IBehaviorAssignable(obj, None)
    if assignable is None:
        return
    for behavior in assignable.enumerateBehaviors():
        if behavior.marker != behavior.interface:
            for name, field in getFields(behavior.interface).items():
                if IRelation.providedBy(field):
                    try:
                        relation = getattr(behavior.interface(obj), name)
                    except AttributeError:
                        continue
                    yield behavior.interface, name, relation
                if IRelationList.providedBy(field):
                    try:
                        l = getattr(behavior.interface(obj), name)
                    except AttributeError:
                        continue
                    if l is not None:
                        for relation in l:
                            yield behavior.interface, name, relation
Ejemplo n.º 34
0
def getBehaviorsFor(context=None, portal_type=None):
    if context is None and portal_type is None:
        return
    if context is None:
        fti = getUtility(IDexterityFTI, name=portal_type)
        for behavior_name in fti.behaviors:
            behavior_interface = None
            behavior_instance = queryUtility(IBehavior, name=behavior_name)
            if not behavior_instance:
                try:
                    behavior_interface = resolveDottedName(behavior_name)
                except (ValueError, ImportError):
                    continue
            else:
                behavior_interface = behavior_instance.interface
            if behavior_interface is not None:
                yield behavior_interface
    else:
        behavior_assignable = IBehaviorAssignable(context, None)
        for behavior_reg in behavior_assignable.enumerateBehaviors():
            yield behavior_reg.interface
Ejemplo n.º 35
0
def get_fields(brain_or_object):
    """Get a name to field mapping of the object

    :param brain_or_object: A single catalog brain or content object
    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
    :returns: Mapping of name -> field
    :rtype: OrderedDict
    """
    obj = get_object(brain_or_object)
    schema = get_schema(obj)
    if is_dexterity_content(obj):
        # get the fields directly provided by the interface
        fields = getFieldsInOrder(schema)
        # append the fields coming from behaviors
        behavior_assignable = IBehaviorAssignable(obj)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            for behavior in behaviors:
                fields.extend(getFieldsInOrder(behavior.interface))
        return OrderedDict(fields)
    return OrderedDict(schema)
Ejemplo n.º 36
0
def extract_relations(obj):
    assignable = IBehaviorAssignable(obj, None)
    if assignable is None:
        return
    for behavior in assignable.enumerateBehaviors():
        if behavior.marker == behavior.interface:
            continue
        for name, field in getFields(behavior.interface).items():
            if IRelation.providedBy(field):
                try:
                    relation = getattr(behavior.interface(obj), name)
                except AttributeError:
                    continue
                yield behavior.interface, name, relation
            if IRelationList.providedBy(field):
                try:
                    rel_list = getattr(behavior.interface(obj), name)
                except AttributeError:
                    continue
                if rel_list is not None:
                    for relation in rel_list:
                        yield behavior.interface, name, relation
Ejemplo n.º 37
0
def get_object_schema(obj):
    object_schema = set()

    # Iterate over all interfaces that are provided by the object and filter
    # out all attributes that start with '_' or 'manage'.
    for iface in providedBy(obj).flattened():
        for name, field in getFields(iface).items():
            no_underscore_method = not name.startswith('_')
            no_manage_method = not name.startswith('manage')
            if no_underscore_method and no_manage_method:
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field

    # Iterate over all behaviors that are assigned to the object.
    assignable = IBehaviorAssignable(obj, None)
    if assignable:
        for behavior in assignable.enumerateBehaviors():
            for name, field in getFields(behavior.interface).items():
                if name not in object_schema:
                    object_schema.add(name)
                    yield name, field
Ejemplo n.º 38
0
    def __getattr__(self, name):
        # python basics:  __getattr__ is only invoked if the attribute wasn't
        # found by __getattribute__
        #
        # optimization: sometimes we're asked for special attributes
        # such as __conform__ that we can disregard (because we
        # wouldn't be in here if the class had such an attribute
        # defined).
        # also handle special dynamic providedBy cache here.
        # Ignore also some other well known names like
        # Acquisition and AccessControl related ones.
        if name.startswith('__') or name in ATTRIBUTE_NAMES_TO_IGNORE:
            raise AttributeError(name)

        # attribute was not found; try to look it up in the schema and return
        # a default
        value = _default_from_schema(
            self,
            SCHEMA_CACHE.get(self.portal_type),
            name
        )
        if value is not _marker:
            return value

        # do the same for each subtype
        assignable = IBehaviorAssignable(self, None)
        if assignable is not None:
            for behavior_registration in assignable.enumerateBehaviors():
                if behavior_registration.interface:
                    value = _default_from_schema(
                        self,
                        behavior_registration.interface,
                        name
                    )
                    if value is not _marker:
                        return value

        raise AttributeError(name)
Ejemplo n.º 39
0
def getAdditionalSchemata(context=None, portal_type=None):
    """Get additional schemata for this context or this portal_type.

    Additional form field schemata can be defined in behaviors.

    Usually either context or portal_type should be set, not both.
    The idea is that for edit forms or views you pass in a context
    (and we get the portal_type from there) and for add forms you pass
    in a portal_type (and the context is irrelevant then).  If both
    are set, the portal_type might get ignored, depending on which
    code path is taken.
    """
    log.debug("getAdditionalSchemata with context %r and portal_type %s",
              context, portal_type)
    if context is None and portal_type is None:
        return
    if context:
        behavior_assignable = IBehaviorAssignable(context, None)
    else:
        behavior_assignable = None
    if behavior_assignable is None:
        log.debug("No behavior assignable found, only checking fti.")
        # Usually an add-form.
        if portal_type is None:
            portal_type = context.portal_type
        for schema_interface in SCHEMA_CACHE.behavior_schema_interfaces(
            portal_type
        ):
            form_schema = IFormFieldProvider(schema_interface, None)
            if form_schema is not None:
                yield form_schema
    else:
        log.debug("Behavior assignable found for context.")
        for behavior_reg in behavior_assignable.enumerateBehaviors():
            form_schema = IFormFieldProvider(behavior_reg.interface, None)
            if form_schema is not None:
                yield form_schema
Ejemplo n.º 40
0
def getAdditionalSchemata(context=None, portal_type=None):
    """Get additional schemata for this context or this portal_type.

    Additional form field schemata can be defined in behaviors.

    Usually either context or portal_type should be set, not both.
    The idea is that for edit forms or views you pass in a context
    (and we get the portal_type from there) and for add forms you pass
    in a portal_type (and the context is irrelevant then).  If both
    are set, the portal_type might get ignored, depending on which
    code path is taken.
    """
    log.debug("getAdditionalSchemata with context %r and portal_type %s",
              context, portal_type)
    if context is None and portal_type is None:
        return
    if context:
        behavior_assignable = IBehaviorAssignable(context, None)
    else:
        behavior_assignable = None
    if behavior_assignable is None:
        log.debug("No behavior assignable found, only checking fti.")
        # Usually an add-form.
        if portal_type is None:
            portal_type = context.portal_type
        for schema_interface in SCHEMA_CACHE.behavior_schema_interfaces(
            portal_type
        ):
            form_schema = IFormFieldProvider(schema_interface, None)
            if form_schema is not None:
                yield form_schema
    else:
        log.debug("Behavior assignable found for context.")
        for behavior_reg in behavior_assignable.enumerateBehaviors():
            form_schema = IFormFieldProvider(behavior_reg.interface, None)
            if form_schema is not None:
                yield form_schema
Ejemplo n.º 41
0
    def _deploy_content(self, obj, is_page=True):
        """
        Deploy object as page.
        """
        try:
            new_req, orig_req = fakeRequest(obj)
        except AttributeError:
            # not a valid obj to override request with
            new_req = None
        content = self._render_obj(obj)
        if content is None:
            return

        filename = obj.absolute_url_path().lstrip('/')
        # deploy additional views for content type
        if PLONE_APP_BLOB_INSTALLED and isinstance(obj, ATBlob):
            self._deploy_views([os.path.join(filename, 'view'), ],
                    is_page=True)

        if is_page:
            filename = filename.rstrip('/')
            if self.add_index or IFolder.providedBy(obj):
                filename = os.path.join(filename, 'index.html')
            elif not filename.endswith('.htm') and not filename.endswith('.html'):
                filename = filename + '.html'
        elif isinstance(obj, ATImage) or \
                hasattr(obj, 'getBlobWrapper') and \
                'image' in obj.getBlobWrapper().getContentType():
            # create path to dump ATImage in original size
            if filename.rsplit('.', 1)[-1] in ('png', 'jpg', 'gif', 'jpeg'):
                filename = os.path.join(filename, 'image.%s' % (
                    filename.rsplit('.', 1)[-1]))
            else:
                filename = os.path.join(filename, 'image.jpg')
            filename, content = self._apply_image_transforms(filename, content)
        elif (hasattr(obj, 'getBlobWrapper') and 'image' not in
                obj.getBlobWrapper().getContentType()):
            # create path like for ATImage
            if len(filename.rsplit('.', 1)) > 1:
                filename = os.path.join(filename, 'file.%s' % (
                    filename.rsplit('.', 1)[-1]))
            else:
                filename = os.path.join(filename, 'file')

        self._write(filename, content)

        # deploy all sizes of images uploaded for the object
        if not getattr(obj, 'schema', None):
            return

        # For Dexterity objects
        if IDexterityContent.providedBy(obj):
            from plone.dexterity.interfaces import IDexterityFTI
            from zope.component import getUtility
            from zope.schema import getFieldsInOrder
            from plone.behavior.interfaces import IBehaviorAssignable

            fti = getUtility(IDexterityFTI, name=obj.portal_type)
            schema = fti.lookupSchema()
            fields = getFieldsInOrder(schema)
            for _, field in fields:
                if INamedImageField.providedBy(field):
                    self._deploy_blob_dexterity_image_field(obj, field)
                elif INamedFileField.providedBy(field):
                    self._deploy_blob_dexterity_file_field(obj, field)

            behavior_assignable = IBehaviorAssignable(obj)
            if behavior_assignable:
                behaviors = behavior_assignable.enumerateBehaviors()
                for behavior in behaviors:
                    for k, v in getFieldsInOrder(behavior.interface):
                        pass

        else:
            for field in obj.Schema().fields():
                if (PLONE_APP_BLOB_INSTALLED and IBlobImageField.providedBy(field)) or \
                        field.type == 'image':
                    self._deploy_blob_image_field(obj, field)
                elif PLONE_APP_BLOB_INSTALLED and IBlobField.providedBy(field):
                    self._deploy_blob_file_field(obj, field)
                elif field.type == 'file' and obj.portal_type not in self.file_types:
                    self._deploy_file_field(obj, field)
                else:
                    continue
        if new_req is not None:
            restoreRequest(orig_req, new_req)
Ejemplo n.º 42
0
    def __get__(self, inst, cls=None):  # noqa
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        direct_spec = getattr(inst, '__provides__', None)

        # avoid recursion - fall back on default
        if getattr(self, '__recursion__', False):
            return direct_spec

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # Find the data we need to know if our cache needs to be invalidated
        portal_type = getattr(inst, 'portal_type', None)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)

        # See if we have a current cache. Reasons to do this include:
        #
        #  - The FTI was modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        updated = (
            inst._p_mtime,
            SCHEMA_CACHE.modified(portal_type),
            SCHEMA_CACHE.invalidations,
            hash(direct_spec)
        )
        if cache is not None and cache[:-1] == updated:
            if cache[-1] is not None:
                return cache[-1]
            return spec

        main_schema = SCHEMA_CACHE.get(portal_type)
        if main_schema:
            dynamically_provided = [main_schema]
        else:
            dynamically_provided = []

        # block recursion
        self.__recursion__ = True
        try:
            assignable = IBehaviorAssignable(inst, None)
            if assignable is not None:
                for behavior_registration in assignable.enumerateBehaviors():
                    if behavior_registration.marker:
                        dynamically_provided.append(
                            behavior_registration.marker
                        )
        finally:
            del self.__recursion__

        if not dynamically_provided:
            # rare case if no schema nor behaviors with markers are set
            inst._v__providedBy__ = updated + (None, )
            return spec

        dynamically_provided.append(spec)
        all_spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (all_spec, )

        return all_spec
    def set_properties(self, params):
        for par in params:
            if isinstance(params[par], xmlrpclib.DateTime):
                params[par] = DT2dt(DateTime(params[par].value)).replace(tzinfo=None)
            elif isinstance(params[par], xmlrpclib.Binary):
                # import pdb; pdb.set_trace()
                params[par] = params[par].data
            elif par == "creators":
                params[par] = tuple(params[par])
            elif isinstance(params[par], str):
                params[par] = unicode(params[par])
            # elif isinstance(self.context[attr], BaseUnit):
            #     self.context[par].update(params[par], self.context[par])
            #     del params[par]

        context = self.context
        changed = []

        behavior_fields = []
        content_fields = []

        # Stap 1 metadata
        behavior_assignable = IBehaviorAssignable(context)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            for behavior in behaviors:
                behavior_fields += getFieldsInOrder(behavior.interface)

        # Stap 2 eigen velden
        fti = context.getTypeInfo()
        schema = fti.lookupSchema()
        content_fields = getFieldsInOrder(schema)

        fields = behavior_fields
        fields += content_fields

        for k, v in params.items():
            found = False

            for field_info in fields:
                try:
                    field_name = field_info[0]
                    field = field_info[1]
                    field_schema = getattr(field, "schema", None)
                    if field_name == k:
                        if field_schema and field_schema.getName() in ["INamedBlobImage", "INamedImage"]:
                            found = True
                            setattr(context, field_name, field._type(v))
                            changed.append(k)

                        elif type(field) == RelationChoice:
                            if type(v) in [list, tuple]:
                                v = v[0]
                            context.set_relation(field_name, path=v)

                        elif type(field) == RelationList:
                            value = v
                            if type(value) in [str, unicode]:
                                value = [value]
                            context.set_relation(field_name, paths=value)

                        else:
                            found = True
                            field.set(context, v)
                            changed.append(k)
                        # context.plone_log(u'Setting field "{0}"'.format(k))
                except Exception, e:
                    logger.exception("Error with field '{0}'  : {1}".format(field_name, e))
                    pass
Ejemplo n.º 44
0
def behaviors_of(obj):
    behavior_assignable = IBehaviorAssignable(obj)
    if behavior_assignable:
        behaviors = behavior_assignable.enumerateBehaviors()
        for behavior in behaviors:
            yield behavior
    def all_values(self):
        """
        Return a dict containing all values of all schema fields
        """
        assert isinstance(self, FolderishAnimationView)
        context = aq_inner(self.context)
        assert isinstance(context, FolderishAnimation)
        res = {}
        # https://stackoverflow.com/a/12178741/1051649:
        for name, desc in IFolderishAnimation.namesAndDescriptions():
            value = getattr(context, name, None)
            logger.info('.all_values %(name)r: %(desc)s', locals())
            if IMethod.providedBy(desc):
                logger.info('%(name)s: a method', locals())
                # It's a method --> call it:
                value = value()
            res[name] = value
        try:
            name = 'FolderishAnimation'
            schema = getUtility(IDexterityFTI, name=name).lookupSchema()
            logger.info('schema is %(schema)r', locals())
        except Exception as e:
            logger.exception(e)
            logger.error('Could not get schema for name %(name)r', locals())

        behavior_assignable = IBehaviorAssignable(context)
        if behavior_assignable:
            first = 1
            for behavior in behavior_assignable.enumerateBehaviors():
                logger.info('behavior: %(behavior)r', locals())
                for name, field in getFieldsInOrder(behavior.interface):
                    if name == 'subjects':
                        continue
                    try:
                        value = field.get(context)
                        if callable(value):
                            value = value()
                        res[name] = value
                        logger.info('  %(name)r --> %(value)r', locals())
                    except Exception as e:
                        # XXX Access to the fields from my behaviors doesn't work!
                        logger.exception(e)
                        logger.error('name=%(name)r, field=%(field)r', locals())
                        set_trace()
                        value = field.get(context)
                        if callable(value):
                            value = value()
                        res[name] = value
        if 'height' in res and 'width' in res:
            res['_calculated'] = {
                'style': ';'.join(['%s:%spx' % (k, res[k])
                                   for k in ('height', 'width')
                                   ]),
                }
            logger.info('style=%(style)s', res['_calculated'])
        pp(res)
        res['file_elements'] = self._file_elements()
        res['preload_img'] = self._preload_img

        scales = getMultiAdapter((context, context.REQUEST), name='images')
        scale = scales.scale('image', scale='preview')
        if scale:
            res['preview_image_tag'] = scale.tag(title=None,
                            alt=_('Open a new window to start the animation'))
        else:
            res['preview_image_tag'] = self._clickable_text()
            logger.warn('No preview image found for %(context)r', locals())
        return res
Ejemplo n.º 46
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        direct_spec = getattr(inst, '__provides__', None)

        # avoid recursion - fall back on default
        if getattr(self, '__recursion__', False):
            return direct_spec

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # Find the data we need to know if our cache needs to be invalidated
        portal_type = getattr(inst, 'portal_type', None)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)

        # See if we have a current cache. Reasons to do this include:
        #
        #  - The FTI was modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        updated = (inst._p_mtime, SCHEMA_CACHE.modified(portal_type),
                   SCHEMA_CACHE.invalidations, hash(direct_spec))
        if cache is not None and cache[:-1] == updated:
            if cache[-1] is not None:
                return cache[-1]
            return spec

        main_schema = SCHEMA_CACHE.get(portal_type)
        if main_schema:
            dynamically_provided = [main_schema]
        else:
            dynamically_provided = []

        # block recursion
        self.__recursion__ = True
        try:
            assignable = IBehaviorAssignable(inst, None)
            if assignable is not None:
                for behavior_registration in assignable.enumerateBehaviors():
                    if behavior_registration.marker:
                        dynamically_provided.append(
                            behavior_registration.marker)
        finally:
            del self.__recursion__

        if not dynamically_provided:
            # rare case if no schema nor behaviors with markers are set
            inst._v__providedBy__ = updated + (None, )
            return spec

        dynamically_provided.append(spec)
        all_spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (all_spec, )

        return all_spec
Ejemplo n.º 47
0
    def set_properties(self, params):
        for par in params:
            if isinstance(params[par], xmlrpclib.DateTime):
                params[par] = DT2dt(DateTime(params[par].value)).replace(tzinfo=None)
            elif isinstance(params[par], xmlrpclib.Binary):
                # import pdb; pdb.set_trace()
                params[par] = params[par].data
            elif par == 'creators':
                params[par] = tuple(params[par])
            elif isinstance(params[par], str) and par != 'id':
                #print "set_properties", par
                params[par] = unicode(params[par])
            # elif isinstance(self.context[attr], BaseUnit):
            #     self.context[par].update(params[par], self.context[par])
            #     del params[par]
        context = self.context
        changed = []

        behavior_fields = []
        content_fields = []

        # Step 1 metadata

        # Fake a form submit, so that local behaviors are not evaluated
        request = self.context.REQUEST
        request.set("form.buttons.save", True)

        behavior_assignable = IBehaviorAssignable(context)
        if behavior_assignable:
            behaviors = behavior_assignable.enumerateBehaviors()
            #print behaviors
            for behavior in behaviors:
                #print getFieldsInOrder(behavior.interface)
                behavior_fields += getFieldsInOrder(behavior.interface)

        # Stap 2 eigen velden
        fti = context.getTypeInfo()
        schema = fti.lookupSchema()
        content_fields = getFieldsInOrder(schema)

        fields = behavior_fields
        fields += content_fields

        for k, v in params.items():
            found = False
            #print k, v
            for field_info in fields:
                try:
                    field_name = field_info[0]
                    field = field_info[1]
                    field_schema = getattr(field, 'schema', None)
                    #print field_name, field_schema, field_schema and field_schema.getName()
                    if field_name == k:
                        if field_schema and field_schema.getName() in ['INamedBlobImage', 'INamedBlobFile']:
                            found = True
                            filename = ''
                            #print type(v)
                            if type(v) == type(()):
                                #print "mod"
                                filename = safe_unicode(v[1])
                                v = v[0].data
                            #print len(v), filename    
                            if field_schema.getName() == 'INamedBlobImage':
                                v = NamedBlobImage(data=v, filename=filename)
                            elif field_schema.getName() == 'INamedBlobFile':
                                v = NamedBlobFile(data=v, filename=filename)
                            setattr(context, field_name, v)
                            changed.append(k)

                        elif type(field) == RelationChoice:
                                if type(v) in [list, tuple]:
                                    v = v[0]
                                context.set_relation(field_name, path=v)

                        elif type(field) == RelationList:
                            value = v
                            if type(value) in [str, unicode]:
                                value = [value, ]
                            context.set_relation(field_name, paths=value)
                        elif type(field) == RichText:
                            setattr(context, field_name, field.fromUnicode(v))
                        elif field_name == 'subjects':
                            setattr(context, 'subject', v)
                        else:
                            found = True
                            field.set(context, v)
                            changed.append(k)
                        logger.info(u'Setting field "{0}"'.format(k))
                except Exception, e:
                    logger.exception("Error with field '{0}'  : {1}".format(field_name, e))
                    pass

            if not found:
                logger.warn(u'Cannot find field "{0}"'.format(k))