"""ExtImage product module.""" ############################################################################### # # Copyright (c) 2001 Gregor Heine . All rights reserved. # ExtFile Home: http://www.zope.org/Members/MacGregor/ExtFile/index_html # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission # # Disclaimer # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # In accordance with the license provided for by the software upon # which some of the source code has been derived or used, the following # acknowledgement is hereby provided : # # "This product includes software developed by Digital Creations # for use in the Z Object Publishing Environment # (http://www.zope.org/)." # ############################################################################### __doc__ = """ExtImage product module. The ExtImage-Product works like the Zope Image-product, but stores the uploaded image externally in a repository-direcory. It creates a preview of the image (requires PIL).""" __version__='1.5.4' import Globals from Products.ExtFile.ExtFile import * from Globals import HTMLFile, MessageDialog, InitializeClass from AccessControl import ClassSecurityInfo from webdav.Lockable import ResourceLockedError import urllib, os, string, types from os.path import join, isfile from tempfile import TemporaryFile from webdav.WriteLockInterface import WriteLockInterface from IExtFile import IExtImage from zLOG import * _SUBSYS = 'ExtImage' _debug = 0 try: from zExceptions import Redirect except ImportError: Redirect = 'Redirect' from Config import REPOSITORY_UMASK NO_PREVIEW = 0 GENERATE = 1 UPLOAD_NORESIZE = 2 UPLOAD_RESIZE = 3 manage_addExtImageForm = HTMLFile('dtml/extImageAdd', globals()) def manage_addExtImage(self, id='', title='', descr='', file='', preview='', content_type='', create_prev=0, maxx='', maxy='', ratio=0, permission_check=0, redirect_default_view=0, REQUEST=None): """ Add an ExtImage to a folder. """ if not id and getattr(file, 'filename', None) is not None: # generate id from filename and make sure, it has no 'bad' chars id = file.filename id = id[max(string.rfind(id,'/'), string.rfind(id,'\\'), string.rfind(id,':'))+1:] title = title or id id = normalize_id(id) tempExtImage = ExtImage(id, title, descr, permission_check, redirect_default_view) self._setObject(id, tempExtImage) if file != '': self._getOb(id).manage_file_upload(file, content_type, 0, create_prev, maxx, maxy, ratio) if create_prev==UPLOAD_NORESIZE or create_prev==UPLOAD_RESIZE: self._getOb(id).manage_file_upload(preview, content_type, 1, create_prev, maxx, maxy, ratio) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=0) return id class ExtImage(ExtFile): """ The ExtImage-Product works like the Zope Image-product, but stores the uploaded image externally in a repository-direcory. It can create a preview of the image (requires PIL).""" __implements__ = (IExtImage, WriteLockInterface) security = ClassSecurityInfo() # what do people think they're adding? meta_type = 'ExtImage' # default,min,max-sizes for the preview image _image_size={'default':256,'min':1,'max':999} # store maxx and maxy prev_maxx = _image_size['default'] prev_maxy = _image_size['default'] ################################ # Init method # ################################ def __init__(self, id, title='', descr='', permission_check=0, redirect_default_view=0): """ Initialize a new instance of ExtImage """ ExtImage.inheritedAttribute("__init__")(self, id, title, descr, permission_check, redirect_default_view) self.prev_filename = [] self.prev_content_type = '' self.prev_ratio = 1 self.has_preview = 0 ################################ # Public methods # ################################ def __str__(self): return self.tag() security.declareProtected(ViewPermission, 'tag') def tag(self, preview=0, icon=0, height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, border='0', REQUEST=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values of the image tag. Adopted and adapted from OFS/Image.py """ if not self.is_webviewable(): preview = 1 if not self._access_permitted(): preview = 1 if preview and not self.has_preview: icon = 1 if icon: url = self._static_url(icon=1) img_width, img_height = (32, 32) elif preview: url = self._static_url(preview=1) img_width, img_height = self._getImageSize(self.prev_filename) else: url = self._static_url() img_width, img_height = self._getImageSize(self.filename) height = height or img_height width = width or img_width # Auto-scaling support xdelta = xscale or scale ydelta = yscale or scale if xdelta and width != None: width = str(int(width) * xdelta) if ydelta and height != None: height = str(int(height) * ydelta) if alt is None: alt = self.title or '' strg = '%sself._image_size['max']: maxx = self._image_size['max'] if maxyself._image_size['max']: maxy = self._image_size['max'] return maxx, maxy def _undo(self): """ Restore filename after delete or copy-paste """ if self.has_preview and self.filename != self.prev_filename: fn = self._fsname(self.prev_filename) if not isfile(fn) and isfile(fn+'.undo'): self._register() # Register with TM os.rename(fn+'.undo', self._temp_fsname(self.prev_filename)) return ExtImage.inheritedAttribute("_undo")(self) def _get_content_type(self, file, body, id, content_type=None): """ Determine the mime-type """ from OFS.Image import getImageInfo ct, w, h = getImageInfo(body) if ct: content_type = ct else: content_type = ExtImage.inheritedAttribute('_get_content_type')(self, file, body, id, content_type) return content_type ################################ # Special management methods # ################################ security.declarePrivate('manage_afterClone') def manage_afterClone(self, item): """ When a copy of the object is created (zope copy-paste-operation), this function is called by CopySupport.py. A copy of the external file is created and self.filename is changed. """ try: self.aq_parent # This raises AttributeError if no context except AttributeError: pass else: result = ExtImage.inheritedAttribute("manage_afterClone")(self, item) self._register() # Register with TM try: new_prev_fn = self._get_new_ufn(content_type=self.prev_content_type) if self.has_preview and self.filename != self.prev_filename: old_prev_fn = self._get_fsname(self.prev_filename) if old_prev_fn: self._update_data(old_prev_fn, self._temp_fsname(new_prev_fn)) self.prev_filename = new_prev_fn else: self.prev_filename = [] self.has_preview = 0 elif self.has_preview: # XXX: This seems to be an impossible state? old_fn = self._get_fsname(self.filename) if not old_fn: self.prev_filename = [] self.has_preview = 0 else: self.prev_filename = [] finally: self._dir__unlock() return result return ExtImage.inheritedAttribute("manage_afterClone")(self, item) security.declarePrivate('manage_afterAdd') def manage_afterAdd(self, item, container): """ When a copy of the object is created (zope copy-paste-operation), this function is called by CopySupport.py. A copy of the external file is created and self.filename is changed. """ return ExtImage.inheritedAttribute("manage_afterAdd")(self, item, container) security.declarePrivate('manage_beforeDelete') def manage_beforeDelete(self, item, container): """ This method is called, when the object is deleted. To support undo-functionality and because this happens too, when the object is moved (cut-paste) or renamed, the external file is not deleted. It is just renamed to filename.undo and remains in the repository, until it is deleted manually. """ if self.has_preview and self.filename != self.prev_filename: tmp_fn = self._temp_fsname(self.prev_filename) fn = self._fsname(self.prev_filename) if isfile(tmp_fn): try: os.rename(tmp_fn, fn+'.undo') except OSError: pass else: try: os.remove(fn) except OSError: pass elif isfile(fn): try: os.rename(fn, fn+'.undo') except OSError: pass return ExtImage.inheritedAttribute("manage_beforeDelete")(self, item, container) ################################ # Transaction manager methods # ################################ def _finish(self): """ Commits the temporary file """ if self.prev_filename and self.filename != self.prev_filename: tmp_fn = self._temp_fsname(self.prev_filename) if _debug: LOG(_SUBSYS, INFO, 'finishing %s' % tmp_fn) if isfile(tmp_fn): if _debug: LOG(_SUBSYS, INFO, 'isfile %s' % tmp_fn) fn = self._fsname(self.prev_filename) try: os.remove(fn) except OSError: pass os.rename(tmp_fn, fn) ExtImage.inheritedAttribute('_finish')(self) def _abort(self): """ Deletes the temporary file """ if self.prev_filename and self.filename != self.prev_filename: tmp_fn = self._temp_fsname(self.prev_filename) if _debug: LOG(_SUBSYS, INFO, 'aborting %s' % tmp_fn) if isfile(tmp_fn): if _debug: LOG(_SUBSYS, INFO, 'isfile %s' % tmp_fn) try: os.remove(tmp_fn) except OSError: pass ExtImage.inheritedAttribute('_abort')(self) InitializeClass(ExtImage)