Exemplo n.º 1
0
    def toFieldValue(self, value):
        """Converts the value to a storable form."""
        context = self.widget.context
        if not IAddForm.providedBy(self.widget.form):
            dm = queryMultiAdapter((context, self.field), IDataManager)
        else:
            dm = None

        current_field_value = (dm.query() if
                               ((dm is not None)
                                and self.field.interface.providedBy(context))
                               else None)
        if not current_field_value or current_field_value == NO_VALUE:
            current_field_value = []
        if not isinstance(current_field_value, list):
            current_field_value = [current_field_value]
        current_field_set = set(current_field_value)
        retvalue = []
        if (INamedField.providedBy(self.field)):
            value_type = self.field._type
        else:
            value_type = self.field.value_type._type
        if not value:
            return value
        elif not isinstance(value, list):
            value = [value]
        for item in value:
            if item['new']:
                retvalue.append(
                    value_type(data=item['file'].read(),
                               filename=item['name']))
            else:
                for existing_file in current_field_set:
                    if existing_file.filename == item['name']:
                        retvalue.append(existing_file)
        if (INamedField.providedBy(self.field)):
            return retvalue[0]
        else:
            return retvalue
Exemplo n.º 2
0
    def get_files(self, path_prefix=u"", recursive=True, toplevel=True):
        try:
            primary_adapter = getAdapter(self.context,
                                         interface=IPrimaryFieldInfo)
        except TypeError:
            # if no primary field is available PrimaryFieldInfo
            # Adapter throws TypeError
            return

        if INamedField.providedBy(primary_adapter.field):
            named_file = primary_adapter.value
            if primary_adapter.value:
                notify(ItemZippedEvent(self.context))
                yield self.get_file_tuple(named_file, path_prefix)
Exemplo n.º 3
0
    def setDexterityItem(self, obj, uploadfile):
        """ Set the blob-field of dexterity-based types

        This works with blob-types of plone.app.contenttypes and has
        fallbacks for other implementations of blob-types with dexterity.

        """
        field_name = ''
        info = ''
        try:
            # Use the primary field if it's an blob-field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first blob-field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                if INamedField.providedBy(field):
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create either a NamedBlobImage or a NamedImage
            setattr(obj, field_name, field._type(uploadfile.read(),
                                                 filename=unicode(id)))
        return True
Exemplo n.º 4
0
    def setDexterityItem(self, obj, uploadfile, filename):
        """ Set the blob-field of dexterity-based types

        This works with blob-types of plone.app.contenttypes and has
        fallbacks for other implementations of blob-types with dexterity.

        """
        field_name = ''
        info = ''
        try:
            # Use the primary field if it's an blob-field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first blob-field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                if INamedField.providedBy(field):
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create either a NamedBlobImage or a NamedImage
            setattr(obj, field_name, field._type(uploadfile.read(),
                                                 filename=unicode(filename)))
        return True
Exemplo n.º 5
0
    def _init(self):
        """
        moved here just so we can wrap it in exception block more nicely
        """
        try:
            primary = IPrimaryFieldInfo(self.context, None)
            if (INamedField.providedBy(primary.field) and
                    hasattr(primary.field, 'getSize') and
                    primary.field.getSize() > 0):
                self.file = primary.field
                self.field_name = primary.fieldname
        except TypeError:
            pass

        if has_image(self.context):
            self.image = self.file = self.context.image
            self.field_name = 'image'
Exemplo n.º 6
0
def DexterityItem__init__(self, context, feed):
    try:
        self._old___init__(context, feed)
    except (POSKeyError, AttributeError, TypeError):
        pass

    try:
        primary = IPrimaryFieldInfo(self.context, None)
    except TypeError:
        primary = None
    try:
        if primary and INamedField.providedBy(primary.field):
            file = primary.field.get(self.context)
            if file.getSize() > 0:
                self.file = file
                self.field_name = primary.fieldname
    except (POSKeyError, AttributeError):
        pass
Exemplo n.º 7
0
 def __init__(self, context, feed):
     super().__init__(context, feed)
     self.dexterity = IDexterityContent.providedBy(context)
     lead = ILeadImage(self.context, None)
     if lead:
         if (lead.image and hasattr(lead.image, 'getSize')
                 and lead.image.getSize() > 0):
             self.file = lead.image
             self.field_name = 'image'
     if self.file is None:
         try:
             primary = IPrimaryFieldInfo(self.context, None)
             if (INamedField.providedBy(primary.field)
                     and hasattr(primary.value, 'getSize')
                     and primary.value.getSize() > 0):
                 self.file = primary.value
                 self.field_name = primary.fieldname
         except TypeError:
             pass
Exemplo n.º 8
0
 def __init__(self, context, feed):
     super(DexterityItem, self).__init__(context, feed)
     self.dexterity = IDexterityContent.providedBy(context)
     lead = ILeadImage(self.context, None)
     if lead:
         if (lead.image
                 and hasattr(lead.image, 'getSize')
                 and lead.image.getSize() > 0):
             self.file = lead.image
             self.field_name = 'image'
     if self.file is None:
         try:
             primary = IPrimaryFieldInfo(self.context, None)
             if (INamedField.providedBy(primary.field)
                     and hasattr(primary.field, 'getSize')
                     and primary.field.getSize() > 0):
                 self.file = primary.field
                 self.field_name = primary.fieldname
         except TypeError:
             pass
    def __call__(self, recursive=True):
        # look for a content with name file field into content
        fti = getUtility(IDexterityFTI, name=self.context.portal_type)
        schema = fti.lookupSchema()
        for name, field in getFieldsInOrder(schema):
            if INamedField.providedBy(field):
                return getattr(self.context, name)

        # else, look for a source file field into related items
        if recursive and IRelatedItems.providedBy(self.context):
            related_items = [r.to_object for r in self.context.relatedItems]
            for related_item in related_items:

                source_file = getMultiAdapter((related_item, self.request),
                                              IModelFileSource)()
                if source_file:
                    return source_file
                else:
                    continue

        return None
    def __call__(self, recursive=True):
        # look for a content with name file field into content
        fti = getUtility(IDexterityFTI, name=self.context.portal_type)
        schema = fti.lookupSchema()
        for name, field in getFieldsInOrder(schema):
            if INamedField.providedBy(field):
                return getattr(self.context, name)

        # else, look for a source file field into related items
        if recursive and IRelatedItems.providedBy(self.context):
            related_items = [r.to_object for r in self.context.relatedItems]
            for related_item in related_items:

                source_file = getMultiAdapter((related_item, self.request),
                                              IModelFileSource
                                              )()
                if source_file:
                    return source_file
                else:
                    continue

        return None
Exemplo n.º 11
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(FileUploadWidget, self)._base_args()
        url = '%s/++widget++%s/@@upload/' % (
                    self.request.getURL(),
                    self.name)
        args.setdefault('pattern_options', {})
        args['pattern_options'] = {'url': url}
        args['pattern_options']['paramName'] = self.name
        if (INamedField.providedBy(self.field)):
            self.maxFiles = 1
        args['pattern_options']['maxFiles'] = self.maxFiles
        args['pattern_options']['isWidget'] = True
        args['pattern_options']['showTitle'] = False
        args['pattern_options']['autoCleanResults'] = False
        self.cleanup()
        loaded = []
        extractName = self.name + "uploaded"
        if getattr(self.request, extractName, None) is not None:
            files = self.request[extractName]
            if files:
                extracted = json.loads(str(files))
                for extracted_file in extracted:
                    if extracted_file['name'] != extracted_file['tmpname']:
                        tmpdir = gettempdir()
                        path = join(tmpdir, extracted_file['tmpname'])
                        file_ = open(path, 'r+b')
                        file_.seek(0, 2)  # end of file
                        tmpsize = file_.tell()
                        file_.seek(0)
                        file_.close()
                        dl_url = '%s/++widget++%s/@@download/' % (
                                  self.request.getURL(),
                                  self.name) + (extracted_file['tmpname'] +
                                                '?name=' +
                                                extracted_file['name'])
                        newfile = {'tmpname': extracted_file['tmpname'],
                                   'size': tmpsize,
                                   'url': dl_url,
                                   'name': extracted_file['name']}
                        loaded.append(newfile)

        if not IAddForm.providedBy(self.form):
            dm = queryMultiAdapter((self.context, self.field,), IDataManager)
        else:
            dm = None

        current_field_value = (
            dm.query()
            if ((dm is not None) and
                self.field.interface.providedBy(self.context))
            else None
        )
        if current_field_value and current_field_value != NO_VALUE:
            if not isinstance(current_field_value, list):
                current_field_value = [current_field_value]
            current_field_set = set(current_field_value)
            for item in current_field_set:
                dl_url = '%s/++widget++%s/@@downloadexisting/' % (
                             self.request.getURL(),
                             self.name) + item.filename
                info = {'name': item.filename,
                        'tmpname': item.filename,
                        'size': item.getSize(),
                        'url': dl_url,
                        }
                loaded.append(info)
        args['pattern_options']['existing'] = loaded
        return args
Exemplo n.º 12
0
 def has_enclosure(self):
     if self.primary:
         return INamedField.providedBy(self.primary.field)
     else:
         return False
Exemplo n.º 13
0
    def __iter__(self):
        for item in self.previous:
            if '_path' not in item:
                yield item
                continue

            obj = self.context.unrestrictedTraverse(item['_path'].lstrip('/'),
                                                    None)

            if obj is None:
                yield item
                continue

            # do nothing if we got a wrong object through acquisition
            path = item['_path']
            if path.startswith('/'):
                path = path[1:]
            if '/'.join(obj.getPhysicalPath()[self.root_path_length:]) != path:
                yield item
                continue
            #import pdb; pdb.set_trace()
            for schemata in iterSchemata(obj):
                for name, field in getFieldsInOrder(schemata):
                    if field.readonly:
                        continue
                    # if name=='deity_main':
                    #     name = 'deity_host'
                    if INamedField.providedBy(field):
                       value = item.get('%s%s' % (self.datafield_prefix, name),
                                        _marker)
                       if value is not _marker:
                          deserializer = IDeserializer(field)

                          # prepare value data and content type
                          value['data'] = base64.b64decode(value['data'])
                          value['contenttype'] = value['content_type']
                          value = deserializer(value, None, item)
                          field.set(field.interface(obj), value)

                    # Get the widget's current value, if it has one then leave
                    # it alone
                    value = getMultiAdapter(
                        (obj, field), IDataManager).query()
                    if not(value is field.missing_value
                           or value is NO_VALUE):
                        continue

                    # Finally, set a default value if nothing is set so far
                    default = queryMultiAdapter((
                        obj,
                        obj.REQUEST,  # request
                        None,  # form
                        field,
                        None,  # Widget
                    ), IValue, name='default')
                    if default is not None:
                        default = default.get()
                    if default is None:
                        default = getattr(field, 'default', None)
                    if default is None:
                        try:
                            default = field.missing_value
                        except AttributeError:
                            pass
                    field.set(field.interface(obj), default)

            notify(ObjectModifiedEvent(obj))
            yield item
Exemplo n.º 14
0
 def has_enclosure(self):
     if self.primary:
         return INamedField.providedBy(self.primary.field)
     else:
         return False
Exemplo n.º 15
0
    def prepare_field_value(self, new_object, field, value):
        recurse = partial(self.prepare_field_value, new_object, field)

        if isinstance(value, str):
            return recurse(value.decode('utf-8'))

        if isinstance(value, list):
            return map(recurse, value)

        if isinstance(value, tuple):
            return tuple(map(recurse, value))

        relation_fields = filter(IRelation.providedBy,
                                 (field, getattr(field, 'value_type', None)))
        if relation_fields and isinstance(value, unicode):
            target = uuidToObject(value)
            return create_relation('/'.join(target.getPhysicalPath()))

        if IRichText.providedBy(field) \
           and not IRichTextValue.providedBy(value):
            return recurse(field.fromUnicode(value))

        if INamedField.providedBy(field) and value is not None \
           and not isinstance(value, field._type):

            if value == '':
                return None

            if hasattr(value, 'get_size') and value.get_size() == 0:
                return None

            source_is_blobby = IBlobWrapper.providedBy(value)
            target_is_blobby = INamedBlobFileField.providedBy(field) or \
                               INamedBlobImageField.providedBy(field)

            if source_is_blobby and target_is_blobby:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                new_value = field._type(
                    data='',  # empty blob, will be replaced
                    contentType=value.content_type,
                    filename=filename)
                if not hasattr(new_value, '_blob'):
                    raise ValueError(
                        ('Unsupported file value type {!r}'
                         ', missing _blob.').format(
                             new_value.__class__))

                # Simply copy the persistent blob object (with the file system
                # pointer) to the new value so that the file is not copied.
                # We assume that the old object is trashed and can therefore
                # adopt the blob file.
                new_value._blob = value.getBlob()
                return recurse(new_value)

            else:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                data = value.data
                data = getattr(data, 'data', data)  # extract Pdata
                return recurse(field._type(
                    data=data,
                    contentType=value.content_type,
                    filename=filename))

        return value
Exemplo n.º 16
0
    def prepare_field_value(self, new_object, field, value):
        recurse = partial(self.prepare_field_value, new_object, field)

        if isinstance(value, str):
            return recurse(value.decode('utf-8'))

        if isinstance(value, list):
            return map(recurse, value)

        if isinstance(value, tuple):
            return tuple(map(recurse, value))

        relation_fields = filter(IRelationChoice.providedBy,
                                 (field, getattr(field, 'value_type', None)))
        if relation_fields and isinstance(value, unicode):
            target = uuidToObject(value)
            return create_relation('/'.join(target.getPhysicalPath()))

        if IRichText.providedBy(field) \
           and not IRichTextValue.providedBy(value):
            return recurse(field.fromUnicode(value))

        if INamedField.providedBy(field) and value \
           and not isinstance(value, field._type):

            source_is_blobby = IBlobWrapper.providedBy(value)
            target_is_blobby = INamedBlobFileField.providedBy(field) or \
                               INamedBlobImageField.providedBy(field)

            if source_is_blobby and target_is_blobby:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                new_value = field._type(
                    data='',  # empty blob, will be replaced
                    contentType=value.content_type,
                    filename=filename)
                if not hasattr(new_value, '_blob'):
                    raise ValueError(
                        ('Unsupported file value type {!r}'
                         ', missing _blob.').format(
                             new_value.__class__))

                # Simply copy the persistent blob object (with the file system
                # pointer) to the new value so that the file is not copied.
                # We assume that the old object is trashed and can therefore
                # adopt the blob file.
                new_value._blob = value.getBlob()
                return recurse(new_value)

            else:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                data = value.data
                data = getattr(data, 'data', data)  # extract Pdata
                return recurse(field._type(
                    data=data,
                    contentType=value.content_type,
                    filename=filename))

        return value