def installUi(self): '''Installs the user interface.''' # Some useful imports from OFS.Folder import manage_addFolder from OFS.Image import manage_addImage, manage_addFile from Products.PythonScripts.PythonScript import PythonScript from Products.PageTemplates.ZopePageTemplate import \ manage_addPageTemplate # Delete the existing folder if it existed. zopeContent = self.app.objectIds() if 'ui' in zopeContent: self.app.manage_delObjects(['ui']) manage_addFolder(self.app, 'ui') # Browse the physical ui folders (the Appy one and an app-specific, if # the app defines one) and create the corresponding objects in the Zope # folder. In the case of files having the same name in both folders, # the one from the app-specific folder is chosen. j = os.path.join uiFolders = [j(j(appy.getPath(), 'gen'), 'ui')] appUi = j(self.config.diskFolder, 'ui') if os.path.exists(appUi): uiFolders.insert(0, appUi) for ui in uiFolders: for root, dirs, files in os.walk(ui): folderName = root[len(ui):] # Get the Zope folder that corresponds to this name zopeFolder = self.app.ui if folderName: for name in folderName.strip(os.sep).split(os.sep): zopeFolder = zopeFolder._getOb(name) # Create sub-folders at this level for name in dirs: if not hasattr(zopeFolder.aq_base, name): manage_addFolder(zopeFolder, name) # Create files at this level for name in files: zopeName, ext = os.path.splitext(name) if ext not in ('.pt', '.py'): # In the ZODB, pages and scripts have their name without # their extension. zopeName = name if hasattr(zopeFolder.aq_base, zopeName): continue f = file(j(root, name)) if ext in gen.File.imageExts: manage_addImage(zopeFolder, zopeName, f) elif ext == '.pt': manage_addPageTemplate(zopeFolder,zopeName,'',f.read()) elif ext == '.py': obj = PythonScript(zopeName) zopeFolder._setObject(zopeName, obj) zopeFolder._getOb(zopeName).write(f.read()) else: manage_addFile(zopeFolder, zopeName, f) f.close() # Update the home page if 'index_html' in zopeContent: self.app.manage_delObjects(['index_html']) manage_addPageTemplate(self.app, 'index_html', '', homePage) # Update the error page if 'standard_error_message' in zopeContent: self.app.manage_delObjects(['standard_error_message']) manage_addPageTemplate(self.app, 'standard_error_message', '',errorPage)
def test_image_extension(self): # Verify that a new image is stored with the correct extension. path = os.path.join(os.path.dirname(__file__), 'correct.png') f = open(path, 'rb') try: data = f.read() finally: f.close() conn = self.db.open() try: app = conn.root()['Application'] manage_addImage(app, 'image', StringIO(data)) transaction.commit() self.assertEqual(app.image.data, data) conn2 = self.db.open() try: app = conn2.root()['Application'] self.assertEqual(app.image.data, data) finally: conn2.close() dir = self.conn.basepath names = os.listdir(dir) self.assert_(('image.png') in names, names) self.assert_(('image') not in names, names) finally: conn.close()
def installUi(self): '''Installs the user interface''' # Some useful imports from OFS.Folder import manage_addFolder from OFS.Image import manage_addImage, manage_addFile # Delete the existing folder if it existed zopeContent = self.app.objectIds() for name in ('ui', self.favIcon): if name in zopeContent: self.app.manage_delObjects([name]) manage_addFolder(self.app, 'ui') # Browse the physical ui folders (the Appy one and an app-specific, if # the app defines one) and create the corresponding objects in the Zope # folder. In the case of files having the same name in both folders, # the one from the app-specific folder is chosen. j = os.path.join uiFolders = [j(j(appy.getPath(), 'gen'), 'ui')] for uiFolder in self.config.appConfig.uiFolders: if uiFolder.startswith('..'): folder = j(os.path.dirname(self.config.diskFolder),uiFolder[3:]) else: folder = j(self.config.diskFolder, uiFolder) if os.path.exists(folder): uiFolders.insert(0, folder) for ui in uiFolders: for root, dirs, files in os.walk(ui): folderName = root[len(ui):] # Get the Zope folder that corresponds to this name zopeFolder = self.app.ui if folderName: for name in folderName.strip(os.sep).split(os.sep): zopeFolder = zopeFolder._getOb(name) # Create sub-folders at this level for name in dirs: if not hasattr(zopeFolder.aq_base, name): manage_addFolder(zopeFolder, name) # Create files at this level for name in files: ext = os.path.splitext(name)[1] if hasattr(zopeFolder.aq_base, name): continue f = file(j(root, name)) if name == self.favIcon: if not hasattr(self.app, name): # Copy it at the root. Else, IE won't notice it. manage_addImage(self.app, name, f) elif ext in gen.File.imageExts: manage_addImage(zopeFolder, name, f) else: manage_addFile(zopeFolder, name, f) f.close() # Update home and error pages from Products.PageTemplates.ZopePageTemplate import \ manage_addPageTemplate if 'index_html' in zopeContent: self.app.manage_delObjects(['index_html']) manage_addPageTemplate(self.app, 'index_html', '', homePage) if 'standard_error_message' in zopeContent: self.app.manage_delObjects(['standard_error_message']) manage_addPageTemplate(self.app, 'standard_error_message', '', errorPage)
def installUi(self): '''Installs the user interface.''' # Some useful imports. from OFS.Folder import manage_addFolder from OFS.Image import manage_addImage, manage_addFile # Delete the existing folder if it existed. zopeContent = self.app.objectIds() if 'ui' in zopeContent: self.app.manage_delObjects(['ui']) manage_addFolder(self.app, 'ui') # Browse the physical ui folders (the Appy one and an app-specific, if # the app defines one) and create the corresponding objects in the Zope # folder. In the case of files having the same name in both folders, # the one from the app-specific folder is chosen. j = os.path.join uiFolders = [j(j(appy.getPath(), 'gen'), 'ui')] for uiFolder in self.config.appConfig.uiFolders: if uiFolder.startswith('..'): folder = j(os.path.dirname(self.config.diskFolder), uiFolder[3:]) else: folder = j(self.config.diskFolder, uiFolder) if os.path.exists(folder): uiFolders.insert(0, folder) for ui in uiFolders: for root, dirs, files in os.walk(ui): folderName = root[len(ui):] # Get the Zope folder that corresponds to this name zopeFolder = self.app.ui if folderName: for name in folderName.strip(os.sep).split(os.sep): zopeFolder = zopeFolder._getOb(name) # Create sub-folders at this level for name in dirs: if not hasattr(zopeFolder.aq_base, name): manage_addFolder(zopeFolder, name) # Create files at this level for name in files: ext = os.path.splitext(name)[1] if hasattr(zopeFolder.aq_base, name): continue f = file(j(root, name)) if name == 'favicon.ico': if not hasattr(self.app, name): # Copy it at the root. Else, IE won't notice it. manage_addImage(self.app, name, f) elif ext in gen.File.imageExts: manage_addImage(zopeFolder, name, f) else: manage_addFile(zopeFolder, name, f) f.close() # Update the home page if 'index_html' in zopeContent: self.app.manage_delObjects(['index_html']) from Products.PageTemplates.ZopePageTemplate import \ manage_addPageTemplate manage_addPageTemplate(self.app, 'index_html', '', homePage) # Remove the error page. if 'standard_error_message' in zopeContent: self.app.manage_delObjects(['standard_error_message'])
def uploadImage(self, file, REQUEST=None): """Upload image to the collection and then return to the referring URL.""" id, title = cookId(None, None, file) i = 0 storage = self._get_storage() while storage._getOb(id, None): i += 1 id = '%s-%u' % (id, i) manage_addImage(storage, id, file, title) self._redirectBack(REQUEST)
def upload_file(self, REQUEST): """ """ temp_folder = self.getSite().temp_folder file = REQUEST.form.get('upload_file', None) if file is None: return None try: image = Image.open(file) except: # Python Imaging Library doesn't recognize it as an image return None x, y = image.size filename = file.filename image_format = image.format if not image_format: _, ext = os.path.splitext(filename) image_format = ext # can't leave empty because image.save will crash if not image_format: image_format = 'JPEG' MAX_SIZE = 400 if x >= MAX_SIZE and x >= y: x, y = MAX_SIZE, y * MAX_SIZE / x resize = True elif y >= MAX_SIZE and y >= x: x, y = x * MAX_SIZE / y, MAX_SIZE resize = True else: resize = False if resize: try: image = image.resize((x, y), Image.ANTIALIAS) except AttributeError: image = image.resize((x, y)) image_io = StringIO() image.save(image_io, image_format, quality=85) id = make_id(temp_folder, id=filename) manage_addImage(temp_folder, id, file=image_io.getvalue()) ob = getattr(temp_folder, id) ob.filename = filename ob.p_changed = 1 if x > y: return (ob.absolute_url(), (x-y)/2, 0, y + (x-y)/2, y, resize) else: return (ob.absolute_url(), 0, (y-x)/2, x, x + (y-x)/2, resize)
def _admin_save_image(self, picture_id, upload_picture_url, x1, y1, x2, y2, width, height, def_width, def_height, container_folder, REQUEST=None, title='', subtitle=''): """ """ if width and height: F_WIDTH = width F_HEIGHT = height else: F_WIDTH = def_width F_HEIGHT = def_height temp_folder = self.getSite().temp_folder upload_picture_url = urllib.unquote(upload_picture_url) # fetch image from temp folder or from container_folder folder if upload_picture_url.startswith(temp_folder.absolute_url()): folder = temp_folder elif upload_picture_url.startswith(container_folder.absolute_url()): folder = container_folder else: raise ValueError() # get image new_picture = upload_picture_url.split('/')[-1] picture = folder[new_picture] if not picture_id: picture_id = new_picture # crop image crop_coordinates = (x1, y1, x2, y2) croped_picture = process_picture(picture, crop_coordinates, F_WIDTH, F_HEIGHT) # remove old image if exists if container_folder.hasObject(picture_id): container_folder.manage_delObjects([picture_id]) # add image to folder if title or subtitle: picture_title = '%s|%s' % (title, subtitle) else: picture_title = '' manage_addImage(container_folder, picture_id, croped_picture, title=picture_title) self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate()) if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER'])
def migrate_to_1_12(db): """ Convert resources script lib File into PythonScript and Image """ libs = db.resources.objectValues('File') for lib in libs: lib_id = lib.id() lib_data = lib.data content_type = lib.getContentType() if 'image' in content_type: db.resources.manage_delObjects(lib_id) lib_id = manage_addImage(db.resources, lib_id, lib_data) else: error_re = re.compile('^## Errors:$', re.MULTILINE) ps = PythonScript('testing') try: lib_data = asUnicode(lib_data) except UnicodeDecodeError, e: logger.info("Unknown encoding, skipping: %s" % lib_id) continue ps.write(lib_data) if not error_re.search(ps.read()): db.resources.manage_delObjects(lib_id) blank = manage_addPythonScript(db.resources, lib_id) sc = db.resources._getOb(lib_id) sc.write(lib_data) logger.info("Converted to Script: %s" % lib_id) continue
def uploadImage(self, file, REQUEST=None): """ Upload image to the collection and then return to the referring URL. """ sha1_hash = sha_hexdigest(file) for image in self.storage.objectValues('Image'): if not hasattr(image, 'sha1_hash'): image.sha1_hash = sha_hexdigest(image) if sha1_hash == image.sha1_hash: return image id, title = cookId(None, None, file) # first, determine if this is a utf-8 text and not ascii try: id.decode('ascii') except UnicodeError: id = id.decode('utf-8') orig_id = id id = make_id(self.storage, title=title) id = manage_addImage(self.storage, id, file, title) if REQUEST: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER']) ob = self.storage._getOb(id) return ob
def importResourceFromJSON(self, container, id, element): """ """ id = id.encode('utf-8') resource_type = element['type'] if id in container.objectIds(): container.manage_delObjects([id]) if resource_type == "Page Template": obj = manage_addPageTemplate(container, id) obj.title = element['title'] obj.write(element['data']) elif resource_type == "Script (Python)": manage_addPythonScript(container, id) obj = container._getOb(id) obj.ZPythonScript_setTitle(element['title']) obj.write(element['data']) elif resource_type == "Image": id = manage_addImage(container, id, element['data'].decode('base64'), content_type=element['contenttype']) else: container.manage_addFile(id) obj = getattr(container, id) obj.meta_type = resource_type obj.title = element['title'] data = element['data'].decode('base64') obj.update_data(data, content_type=element['contenttype'])
def migrate_to_1_12(db): """ Convert resources script lib File into PythonScript and Image """ libs = db.resources.objectValues('File') for lib in libs: lib_id = lib.id() lib_data = lib.data content_type = lib.getContentType() if 'image' in content_type: db.resources.manage_delObjects(lib_id) lib_id = manage_addImage(db.resources, lib_id, lib_data) else: error_re = re.compile('^## Errors:$', re.MULTILINE) ps = PythonScript('testing') try: lib_data = asUnicode(lib_data) except UnicodeDecodeError, e: logger.info("Unknown encoding, skipping: %s" % lib_id) continue ps.write(lib_data) if not error_re.search(ps.read()): db.resources.manage_delObjects(lib_id) ignored = manage_addPythonScript(db.resources, lib_id) sc = db.resources._getOb(lib_id) sc.write(lib_data) logger.info("Converted to Script: %s" % lib_id) continue
def zope_txt2img(self, id, label, imgformat="PNG", **kw): """ Copy this module to your Zope Instance Extensions directory, and after restarting Zope do create an External Method in ZMI following the example: Id - txt2img Title - Convert text into image Module Name - txt2img.py Function Name - zope_txt2img """ from OFS.Image import manage_addImage imgfile = StringIO() img = txt2img(label, **kw) img.save(imgfile, imgformat) manage_addImage(self, id, imgfile)
def upload_maintopic_temp_image(self, REQUEST): """ """ temp_folder = self.getSite().temp_folder file = REQUEST.form.get("upload_file", None) if file is None: return json_response({'error': "no file"}, REQUEST.RESPONSE) id = make_id(temp_folder) manage_addImage(temp_folder, id, file=file) ob = getattr(temp_folder, id) skin = self.getLayoutTool().getCurrentSkin() image_size = map(int, skin.main_section_image_size.split("x")) try: data = crop_image(ob, image_size) except AssertionError, e: data = {"error": str(e)}
def upload_maintopic_temp_image(self, REQUEST): """ """ temp_folder = self.getSite().temp_folder file = REQUEST.form.get("upload_file", None) if file is None: return json_response({'error': "no file"}, REQUEST.RESPONSE) filename = file.filename id = make_id(temp_folder, id=filename) manage_addImage(temp_folder, id, file=file) ob = getattr(temp_folder, id) skin = self.getLayoutTool().getCurrentSkin() image_size = map(int, skin.main_section_image_size.split("x")) try: data = crop_image(ob, image_size) except AssertionError, e: data = {"error": str(e)}
def process_image_upload(self, file='', REQUEST=None): """ Handles the upload of a new image. @param file: uploaded image @param REQUEST: I{optional} parameter to do the redirect """ if file != '': if hasattr(file, 'filename'): if file.filename != '': pos = max(file.filename.rfind('/'), file.filename.rfind('\\'), file.filename.rfind(':'))+1 id = file.filename[pos:] ph = file.filename[:pos] while True: try: manage_addImage(self, '', file) break except: rand_id = utils().utGenRandomId(6) file.filename = '%s%s_%s' % (ph, rand_id , id) if REQUEST: REQUEST.RESPONSE.redirect('%s/toolbox_html' % self.absolute_url())
def uploadImage(self, file, REQUEST=None): """Upload image to the collection and then return to the referring URL.""" id, title = cookId(None, None, file) i = 0 while self.storage._getOb(id, None): i += 1 id = '%s-%u' % (id, i) id = manage_addImage(self.storage, id, file, title) if REQUEST: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER']) ob = self.storage._getOb(id) return ob
def uploadImage(self, file, REQUEST=None): """ Upload image to the collection and then return to the referring URL. """ sha1_hash = sha_hexdigest(file) for image in self.storage.objectValues('Image'): if not hasattr(image, 'sha1_hash'): image.sha1_hash = sha_hexdigest(image) if sha1_hash == image.sha1_hash: return image id, title = cookId(None, None, file) orig_id = id i = 0 while self.storage._getOb(id, None): i += 1 id = '%s-%u' % (orig_id, i) id = manage_addImage(self.storage, id, file, title) if REQUEST: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER']) ob = self.storage._getOb(id) return ob
def admin_savemaintopic_image(self, mainsection, upload_picture_url, x1, y1, x2, y2, width, height, REQUEST=None): """ """ if width and height: F_WIDTH = width F_HEIGHT = height else: F_WIDTH = 962 F_HEIGHT = 143 def process_picture(picture, crop_coordinates): image_string = picture2stringIO(picture) img = Image.open(image_string) fmt = img.format crop_size = F_WIDTH if crop_coordinates[2] - crop_coordinates[0] == 0: x = img.size[0] y = img.size[1] if F_HEIGHT * x > F_WIDTH * y: crop_coordinates = ((x - F_WIDTH * y / F_HEIGHT) / 2, 0, (x + F_WIDTH * y / F_HEIGHT) / 2, y) else: crop_coordinates = (0, (y - (F_HEIGHT * x / F_WIDTH)) / 2, x, (y + (F_HEIGHT * x / F_WIDTH)) / 2) img = img.crop(crop_coordinates) try: img = img.resize((F_WIDTH, F_HEIGHT), Image.ANTIALIAS) except AttributeError: img = img.resize((F_WIDTH, F_HEIGHT)) newimg = StringIO() img.save(newimg, fmt, quality=85) return newimg.getvalue() main_section_images = self._get_mainsection_images_folder() temp_folder = self.getSite().temp_folder upload_picture_url = urllib.unquote(upload_picture_url) # fetch image from temp folder or from main_section_images folder if upload_picture_url.startswith(temp_folder.absolute_url()): folder = temp_folder elif upload_picture_url.startswith(main_section_images.absolute_url()): folder = main_section_images else: raise ValueError() # get image picture_id = upload_picture_url.split('/')[-1] picture = folder[picture_id] # crop image crop_coordinates = (x1, y1, x2, y2) croped_picture = process_picture(picture, crop_coordinates) # remove old image if exists if main_section_images.hasObject(mainsection): main_section_images.manage_delObjects([mainsection]) # add image to folder manage_addImage(main_section_images, mainsection, croped_picture) if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER'])