def __call__(self, name, content_type, data, obj_id): ctr = cmfutils.getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), '', '') or 'File' # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() try: transaction.begin() obj = ploneutils._createObjectByType(type_, self.context, obj_id) ttool = getToolByName(self.context, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [field for safe_name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field)] if len(file_fields) == 0: logger.info("An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(file_field): value = NamedBlobImage(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif INamedImageField.providedBy(file_field): value = NamedImage(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif INamedFileField.providedBy(file_field): value = NamedFile(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) file_field.set(obj, value) obj.title = name obj.reindexObject() notify(ObjectInitializedEvent(obj)) notify(ObjectModifiedEvent(obj)) transaction.commit() finally: upload_lock.release() return obj
def set(self, data, filename, content_type): error = '' obj = self.context ttool = getToolByName(obj, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [ field for name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] if len(file_fields) == 0: error = u'serverError' logger.info( "An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(field): value = NamedBlobImage( data=data, contentType=content_type, filename=unicode(filename)) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile( data=data, contentType=content_type, filename=unicode(filename)) elif INamedImageField.providedBy(file_field): value = NamedImage( data=data, contentType=content_type, filename=unicode(file_field)) elif INamedFileField.providedBy(file_field): value = NamedFile( data=data, contentType=content_type, filename=unicode(filename)) file_field.set(obj, value) obj.reindexObject() notify(ObjectInitializedEvent(obj)) return error
def __call__(self, context): context = getattr(context, 'context', context) portal = getToolByName(context, 'portal_url').getPortalObject() items = [SimpleTerm('auto', 'auto', context.translate(_('label_default_portaltype_configuration', default=u'Default configuration (Content Type Registry).')))] archetype_tool = getToolByName(context, 'archetype_tool', None) if archetype_tool: flt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IFileContent)] ilt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IImageContent)] items.extend([SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in flt]) file_types = [t['portal_type'] for t in flt] items.extend([SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in ilt if t['portal_type'] not in file_types]) for fti in portal.portal_types.objectValues(): if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): try: schema = fti.lookupSchema() except ImportError: # this dexterity type was changed/removed in an improper way # no need to punish, just fail gracefully continue fields = getFieldsInOrder(schema) for fieldname, field in fields: if INamedFileField.providedBy(field) or INamedImageField.providedBy(field): items.append(SimpleTerm(fti.getId(), fti.getId(), fti.Title())) break return SimpleVocabulary(items)
def __call__(self, context): context = getattr(context, 'context', context) portal = getToolByName(context, 'portal_url').getPortalObject() flt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IFileContent)] ilt = [_infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IImageContent)] items = [SimpleTerm('auto', 'auto', context.translate('label_default_portaltype_configuration', default=u'Default configuration (Content Type Registry).', domain='collective.quickupload')),] all_portal_types = [] for t in flt+ilt: portal_type = t['portal_type'] if portal_type not in all_portal_types: items.append(SimpleTerm(portal_type, portal_type, t['type_ui_info'])) all_portal_types.append(portal_type) for fti in portal.portal_types.objectValues(): if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): fields = getFieldsInOrder(fti.lookupSchema()) for fieldname, field in fields: if INamedFileField.providedBy(field) or INamedImageField.providedBy(field): items.append(SimpleTerm(fti.getId(), fti.getId(), fti.Title())) break return SimpleVocabulary(items)
def set(self, data, filename, content_type): error = '' obj = self.context ttool = getToolByName(obj, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [ field for name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] if len(file_fields) == 0: error = u'serverError' logger.info( "An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(file_field): value = NamedBlobImage(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif INamedImageField.providedBy(file_field): value = NamedImage(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) elif INamedFileField.providedBy(file_field): value = NamedFile(data=data, contentType=content_type, filename=unicode(filename, 'utf-8')) file_field.set(obj, value) return error
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 INamedFileField.providedBy(primary_adapter.field): named_file = primary_adapter.value if primary_adapter.value: yield self.get_file_tuple(named_file, path_prefix)
def reset_fileupload_widgets(form): for widget in form.widgets: if not IWidget.providedBy(widget): widget = form.widgets[widget] if INamedFileField.providedBy(widget.field): widget.value = None elif IMultiWidget.providedBy(widget): reset_fileupload_widgets(widget) elif IObjectWidget.providedBy(widget): reset_fileupload_widgets(widget.subform) try: for group in form.groups: reset_fileupload_widgets(group) except AttributeError: pass
def setDexterityObject(self, obj, file_id): """ Set the file- or image-field of dexterity-based types This works with the types 'Image' and 'File' of plone.app.contenttypes and has fallbacks for other implementations of image- and file-types with dexterity. """ request = self.context.REQUEST field_name = '' info = '' try: # Use the primary 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 INamedImageField.providedBy(field) or \ INamedFileField.providedBy(field): field_name = info.fieldname if not field_name: # Use the first field in the schema obj_schema = queryContentType(obj) obj_fields = getFieldsInOrder(obj_schema) for field_info in obj_fields: field = field_info[1] field_schema = getattr(field, 'schema', None) if field_schema and field_schema.getName() in [ 'INamedBlobImage', 'INamedImage', 'INamedBlobFile', 'INamedFile' ]: field_name = field_info[0] break if not field_name: return False else: # Create file/image setattr(obj, field_name, field._type(request['uploadfile'].read(), filename=unicode(file_id))) return True
def setDexterityObject(self, obj, file_id): """ Set the file- or image-field of dexterity-based types This works with the types 'Image' and 'File' of plone.app.contenttypes and has fallbacks for other implementations of image- and file-types with dexterity. """ request = self.context.REQUEST field_name = '' info = '' try: # Use the primary 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 INamedImageField.providedBy(field) or \ INamedFileField.providedBy(field): field_name = info.fieldname if not field_name: # Use the first field in the schema obj_schema = queryContentType(obj) obj_fields = getFieldsInOrder(obj_schema) for field_info in obj_fields: field = field_info[1] field_schema = getattr(field, 'schema', None) if field_schema and field_schema.getName() in [ 'INamedBlobImage', 'INamedImage', 'INamedBlobFile', 'INamedFile' ]: field_name = field_info[0] break if not field_name: return False else: # Create file/image setattr( obj, field_name, field._type(request['uploadfile'].read(), filename=unicode(file_id))) return True
def __call__(self, context): context = getattr(context, 'context', context) portal = getToolByName(context, 'portal_url').getPortalObject() flt = [ _infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IFileContent) ] ilt = [ _infoDictForType(portal, tipe) for tipe in _listTypesForInterface(portal, IImageContent) ] items = [ SimpleTerm( 'auto', 'auto', context.translate( _('label_default_portaltype_configuration', default=u'Default configuration (Content Type Registry).' ))) ] items.extend([ SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in flt ]) file_types = [t['portal_type'] for t in flt] items.extend([ SimpleTerm(t['portal_type'], t['portal_type'], t['type_ui_info']) for t in ilt if t['portal_type'] not in file_types ]) for fti in portal.portal_types.objectValues(): if HAS_DEXTERITY and IDexterityFTI.providedBy(fti): fields = getFieldsInOrder(fti.lookupSchema()) for fieldname, field in fields: if INamedFileField.providedBy( field) or INamedImageField.providedBy(field): items.append( SimpleTerm(fti.getId(), fti.getId(), fti.Title())) break return SimpleVocabulary(items)
def write_data(self): usegrid = getattr(self.group, 'group_usage', None) == 'grid' sheet = self.worksheet.worksheet idx = 0 odd = lambda v: bool(v % 2) if usegrid: data = getattr(self.data, 'data', []) or [] else: data = [self.data] rowidx = 0 for record in data: rowidx += 1 for fieldname, field in getFieldsInOrder(self.field_schema): # get title, value title = field.title if usegrid: value = record.get(fieldname, '') else: value = getattr(record, fieldname, '') # get row color (zebra): idx += 1 # repeat / zebra stripe index oddrow = odd(idx) # computed row height based on length of the title: lines = int(math.ceil(len(title) / 67.0)) set_height(sheet.row(self.cursor), 18 * lines) if usegrid: # include row number in fieldname col, grouped zebra stripe fieldname = 'ROW-%s: %s' % (rowidx, fieldname) oddrow = odd(rowidx) # field name: _style = 'fieldname_odd' if oddrow else 'fieldname_even' style = STYLES.get(_style) sheet.write(self.cursor, 0, fieldname, style) # field title: _style = 'fieldtitle_odd' if oddrow else 'fieldtitle_even' style = STYLES.get(_style) sheet.write_merge(self.cursor, self.cursor, 1, 2, title, style) # write field value(s): _style = 'fieldvalue_odd' if oddrow else 'fieldvalue_even' if self.use_dateformat(field, value): _style = '_'.join((_style, 'date')) style = STYLES.get(_style) # collection field with more than one answer: if not self.is_multiple(field, value): value = [value] if INamedFileField.providedBy(field): value = [v.filename.encode('utf-8') for v in value] vidx = 0 for element in value: if isinstance(element, basestring) and len(element) > 30: # word-wrap likely necessary, compute row height: lines = max(lines, int(math.ceil(len(element) / 30.0))) set_height(sheet.row(self.cursor), 18 * lines) if vidx: for i in range(0, 3): sheet.write(self.cursor, i, '', style) sheet.write(self.cursor, 3, element, style) self.cursor += 1 vidx += 1 if not value: self.cursor += 1 # empty field, proceed to next row
def export_blobs(self, portal_type, blob_type, blacklist, whitelist): """Return a zip-file with file and/or images for the required export. """ all_fields = get_schema_info(portal_type, blacklist, whitelist) if blob_type == 'images': fields = [ i for i in all_fields if INamedImageField.providedBy(i[1]) or INamedBlobImageField.providedBy(i[1]) ] elif blob_type == 'files': fields = [ i for i in all_fields if INamedFileField.providedBy(i[1]) or INamedBlobFileField.providedBy(i[1]) ] elif blob_type == 'related': fields = [ i for i in all_fields if IRelationChoice.providedBy(i[1]) or IRelationList.providedBy(i[1]) ] tmp_file = NamedTemporaryFile() zip_file = zipfile.ZipFile(tmp_file, 'w') catalog = api.portal.get_tool('portal_catalog') query = {'portal_type': portal_type} query['path'] = {} query['path']['query'] = '/'.join(self.context.getPhysicalPath()) blobs_found = False if HAS_MULTILINGUAL and 'Language' in catalog.indexes(): query['Language'] = 'all' for brain in catalog(query): obj = brain.getObject() for fieldname, field in fields: # manually filter for fields # if fieldname not in ['primary_picture']: # continue blobs = [] value = field.get(field.interface(obj)) if not value: continue if blob_type != 'related': blobs = [value] elif IRelationChoice.providedBy(field) or \ IRelationList.providedBy(field): blobs = get_blobs_from_relations(value, field) for blob in blobs: if not blob: continue filename = str((blob.filename).encode('utf8')) zip_file.writestr( '{0}_{1}/{2}'.format( brain.UID, # or: brain.id.upper(), fieldname, filename), str(blob.data)) blobs_found = True zip_file.close() if not blobs_found: return 'No {0} found'.format(blob_type) data = file(tmp_file.name).read() response = self.request.response response.setHeader('content-type', 'application/zip') response.setHeader('content-length', len(data)) response.setHeader('content-disposition', 'attachment; filename="{0}.zip"'.format(blob_type)) return response.write(data)
invoiceSender=invoice.senderId, invoiceSenderName=invoice.senderName, invoiceRecipient=invoice.invoiceRecipient, invoiceRecipientName=invoice.invoiceRecipientName, invoiceDate=invoice.invoiceDate, invoicePayCondition=invoice.invoicePayCondition, invoiceExpireDate=invoice.invoiceExpireDate, invoiceCurrency=invoice.invoiceCurrency, invoiceTotalVat=invoice.invoiceTotalVat, invoiceTotalAmount=invoice.invoiceTotalCost ) # Get the field containing data fields = getFieldsInOrder(IInvoice) file_fields = [field for name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] #import pdb #pdb.set_trace() value = NamedBlobFile(data=invoicefile, contentType=contenttype,
def _file_field_name(self): schema = IFormDefinition(self.context).schema for (name, field) in getFieldsInOrder(schema): if INamedFileField.providedBy(field): return name
def export_blobs(self, portal_type, blob_type, blacklist, whitelist): """Return a zip-file with file and/or images for the required export. """ all_fields = get_schema_info(portal_type, blacklist, whitelist) if blob_type == 'images': fields = [ i for i in all_fields if INamedImageField.providedBy(i[1]) or INamedBlobImageField.providedBy(i[1])] elif blob_type == 'files': fields = [ i for i in all_fields if INamedFileField.providedBy(i[1]) or INamedBlobFileField.providedBy(i[1])] elif blob_type == 'related': fields = [ i for i in all_fields if IRelationChoice.providedBy(i[1]) or IRelationList.providedBy(i[1])] tmp_file = NamedTemporaryFile() zip_file = zipfile.ZipFile(tmp_file, 'w') catalog = api.portal.get_tool('portal_catalog') query = {'portal_type': portal_type} blobs_found = False if HAS_MULTILINGUAL and 'Language' in catalog.indexes(): query['Language'] = 'all' for brain in catalog(query): obj = brain.getObject() for fieldname, field in fields: # manually filter for fields # if fieldname not in ['primary_picture']: # continue blobs = [] value = field.get(field.interface(obj)) if not value: continue if blob_type != 'related': blobs = [value] elif IRelationChoice.providedBy(field) or \ IRelationList.providedBy(field): blobs = get_blobs_from_relations(value, field) for blob in blobs: if not blob: continue filename = str((blob.filename).encode('utf8')) zip_file.writestr( '{0}_{1}/{2}'.format( brain.UID, # or: brain.id.upper(), fieldname, filename), str(blob.data) ) blobs_found = True zip_file.close() if not blobs_found: return 'No {0} found'.format(blob_type) data = file(tmp_file.name).read() response = self.request.response response.setHeader('content-type', 'application/zip') response.setHeader('content-length', len(data)) response.setHeader( 'content-disposition', 'attachment; filename="{0}.zip"'.format(blob_type)) return response.write(data)
def __call__(self, name, content_type, data, obj_id): ctr = cmfutils.getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), '', '') or 'File' # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() try: transaction.begin() obj = ploneutils._createObjectByType(type_, self.context, obj_id) ttool = getToolByName(self.context, 'portal_types') ctype = ttool[obj.portal_type] schema = ctype.lookupSchema() fields = getFieldsInOrder(schema) file_fields = [ field for safe_name, field in fields if INamedFileField.providedBy(field) or INamedImageField.providedBy(field) ] if len(file_fields) == 0: logger.info( "An error happens : the dexterity content type %s " "has no file field, rawdata can't be created", obj.absolute_url()) for file_field in file_fields: if IPrimaryField.providedBy(file_field): break else: # Primary field can't be set ttw, # then, we take the first one file_field = file_fields[0] # TODO: use adapters if HAVE_BLOBS and INamedBlobImageField.providedBy(file_field): value = NamedBlobImage(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif HAVE_BLOBS and INamedBlobFileField.providedBy(file_field): value = NamedBlobFile(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif INamedImageField.providedBy(file_field): value = NamedImage(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) elif INamedFileField.providedBy(file_field): value = NamedFile(data=data.read(), contentType=content_type, filename=unicode(obj_id, 'utf-8')) file_field.set(obj, value) obj.title = name obj.reindexObject() notify(ObjectInitializedEvent(obj)) notify(ObjectModifiedEvent(obj)) transaction.commit() finally: upload_lock.release() return obj
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)