Exemplo n.º 1
0
 def getConfXmlFile(self, file):
     if type(file) is dict:
         filename = file['filename']
         xmlfile = StringIO(file['data'])
     elif type(file) is str and file.startswith('http://'):
         filename = _fileutil.extractFilename(file)
         xmlfile = StringIO(self.http_import(file))
     else:
         filename = _fileutil.extractFilename(file)
         xmlfile = open(_fileutil.getOSPath(file), 'rb')
     return filename, xmlfile
Exemplo n.º 2
0
def uploadBlobField(self, objtype, file='', filename='', mediadbStorable=True):
    if objtype == _globals.DT_IMAGE:
        clazz = MyImage
        maxlength_prop = 'ZMS.input.image.maxlength'
    elif objtype == _globals.DT_FILE:
        clazz = MyFile
        maxlength_prop = 'ZMS.input.file.maxlength'
    blob = clazz(id='', title='', file=file)
    blob.aq_parent = self
    blob.mediadbfile = None
    blob.filename = _fileutil.extractFilename(filename,
                                              undoable=True).encode('utf-8')
    # Check size.
    if self is not None:
        maxlength = self.getConfProperty(maxlength_prop, '')
        if len(maxlength) > 0:
            size = blob.get_size()
            if size > int(maxlength):
                raise zExceptions.Forbidden(
                    'size=%i > %s=%i' % (size, maxlength_prop, int(maxlength)))
    # Store data in media-db.
    if self is not None and mediadbStorable:
        mediadb = self.getMediaDb()
        if mediadb is not None:
            blob.mediadbfile = mediadb.storeFile(blob)
            blob.data = ''
    return blob
Exemplo n.º 3
0
    def rotate(self, img, direction, qual=75):
        """
    Rotate image.
    """
        try:
            from PIL import Image
        except:
            import Image

        # Save image in temp-folder
        tempfolder = tempfile.mktemp()
        filepath = _fileutil.getOSPath('%s/%s' % (tempfolder, img.filename))
        _fileutil.exportObj(img, filepath)

        # Rotate image
        im = Image.open(filepath)
        im = im.rotate(direction)
        im.save(filepath, "JPEG", quality=qual)

        # Read resized image from file-system
        f = open(filepath, 'rb')
        result_data = f.read()
        result_filename = _fileutil.extractFilename(filepath)
        result = {'data': result_data, 'filename': result_filename}
        f.close()

        # Remove temp-folder and images
        _fileutil.remove(tempfolder, deep=1)

        # Returns resulting image
        image = self.context.ImageFromData(result['data'], result['filename'])
        return image


################################################################################
Exemplo n.º 4
0
def initTheme(self, theme, new_id, REQUEST):

    filename = _fileutil.extractFilename(theme)
    id = filename[:filename.rfind('.')]

    ### Store copy of ZEXP in INSTANCE_HOME/import-folder.
    filepath = INSTANCE_HOME + '/import/' + filename
    if theme.startswith('http://'):
        initutil = _globals.initutil()
        initutil.setConfProperty('HTTP.proxy', REQUEST.get('http_proxy', ''))
        zexp = _globals.http_import(initutil, theme)
        _fileutil.exportObj(zexp, filepath)
    else:
        packagepath = package_home(globals()) + '/import/' + filename
        try:
            os.stat(_fileutil.getOSPath(filepath))
        except OSError:
            shutil.copy(packagepath, filepath)

    ### Import theme from ZEXP.
    _fileutil.importZexp(self, filename)

    ### Assign folder-id.
    if id != new_id:
        self.manage_renameObject(id=id, new_id=new_id)

    ### Return new ZMS home instance.
    return getattr(self, new_id)
Exemplo n.º 5
0
def importFile(self, file, REQUEST, handler):
  message = ''

  # Get filename.
  if isinstance(file,ZPublisher.HTTPRequest.FileUpload):
    filename = file.filename
  else: 
    filename = file.name
  _globals.writeBlock( self, '[importFile]: filename='+filename)

  # Create temporary folder.
  folder = tempfile.mktemp()
  os.mkdir(folder)
  
  # Save to temporary file.
  filename = _fileutil.getOSPath('%s/%s'%(folder,_fileutil.extractFilename(filename)))
  _fileutil.exportObj(file,filename)
  
  # Find XML-file.
  if _fileutil.extractFileExt(filename) == 'zip':
    _fileutil.extractZipArchive(filename)
    filename = None
    for deep in [0,1]:
      for ext in ['xml', 'htm', 'html' ]:
        if filename is None:
          filename = _fileutil.findExtension(ext, folder, deep)
	  break
    if filename is None:
      raise zExceptions.InternalError('XML-File not found!')
  
  # Import Filter.
  if REQUEST.get('filter','') in self.getFilterIds():
    filename = _filtermanager.importFilter(self, filename, REQUEST.get('filter',''), REQUEST)
  
  # Import XML-file.
  _globals.writeBlock( self, '[importFile]: filename='+filename)
  f = open(filename, 'r')
  message += handler(self, f)
  f.close()
  
  # Remove temporary files.
  _fileutil.remove(folder, deep=1)
  
  # Return with message.
  message += self.getZMILangStr('MSG_IMPORTED')%('<i>%s</i>'%_fileutil.extractFilename(filename))
  return message
Exemplo n.º 6
0
 def storeFile(self, file):
     filename = _fileutil.extractFilename(file.filename)
     if len(filename) > 0:
         fileext = _fileutil.extractFileExt(file.filename)
         filename = filename[:-(len(fileext) + 1)] + '_' + str(
             time.time()).replace('.', '') + '.' + fileext
         filepath = _fileutil.getOSPath('%s/%s' % (self.location, filename))
         _fileutil.exportObj(file, filepath)
     return filename
Exemplo n.º 7
0
 def manage_index_html(self, REQUEST, RESPONSE):
     """ZMSLog.manage_index_html"""
     path = self.getPath(REQUEST)
     RESPONSE.setHeader('Content-Type', 'Unknown')
     RESPONSE.setHeader(
         'Content-Disposition',
         'inline;filename="%s"' % _fileutil.extractFilename(path))
     file = open(path, 'rb')
     rtn = file.read()
     file.close()
     return rtn
Exemplo n.º 8
0
    def manage_import(self, file, lang, REQUEST, RESPONSE):
        """ ZMSCustom.manage_import """
        message = ''

        if self.meta_id == 'ZMSSysFolder':
            _ziputil.importZip2Zodb(self, file)
            # Message.
            message += self.getZMILangStr('MSG_IMPORTED') % (
                '<i>%s</i>' % _fileutil.extractFilename(file.filename))
        elif self.getType() == 'ZMSRecordSet':
            message += parseXmlString(self, file)
        # Import XML-file.
        else:
            message += _importable.importFile(self, file, REQUEST,
                                              _importable.importContent)

        # Return with message.
        message = urllib.quote(message)
        return REQUEST.RESPONSE.redirect(
            'manage_main?lang=%s&manage_tabs_message=%s' % (lang, message))
Exemplo n.º 9
0
 def toXml(self, sender=None, base_path='', data2hex=True):
     data = ''
     objtype = ''
     filename = _fileutil.getOSPath(
         _fileutil.extractFilename(getattr(self, 'filename', '')))
     if data2hex:
         if getattr(self, 'content_type', '').find('text/') == 0:
             data = '<![CDATA[%s]]>' % str(self.getData(sender))
         else:
             data = _globals.bin2hex(self.getData(sender))
         objtype = ' type="file"'
     else:
         filename = self.getFilename()
         filename = getLangFilename(sender, filename, self.lang)
         filename = '%s%s' % (base_path, filename)
     xml = '\n<%s' % self.xmlGetTagName()
     xml += ' content_type="%s"' % str(getattr(self, 'content_type', ''))
     xml += ' filename="%s"' % filename
     xml += objtype + '>' + data
     xml += '</%s>' % self.xmlGetTagName()
     return xml
Exemplo n.º 10
0
    def manage_submit(self, REQUEST, RESPONSE):
        """ZMSLog.manage_submit"""

        path = self.getPath(REQUEST)
        message = ""

        if REQUEST.get("btn") == "Execute":
            command = REQUEST['command']
            _fileutil.executeCommand(path, command)
            message = "Command executed."

        elif REQUEST.get("btn") == "Upload":
            obj = REQUEST['file']
            type = 'b'
            filename = "%s%s%s" % (path, os.sep,
                                   _fileutil.extractFilename(obj.filename))
            _fileutil.exportObj(obj, filename, type)
            message = "Upload complete."

        return REQUEST.RESPONSE.redirect(
            self.url_append_params(REQUEST['HTTP_REFERER'],
                                   {'manage_tabs_message': message}))
Exemplo n.º 11
0
 def getFile(self, REQUEST, RESPONSE):
     filename = _fileutil.extractFilename(self.getPath(REQUEST))
     parent.set_response_headers(filename)
     return self.retrieveFileStreamIterator(filename, REQUEST)
Exemplo n.º 12
0
    def resize(self, img, size, mode='resize', sffx='_thumbnail', qual=75):
        """
    Resize image.
    """
        try:
            from PIL import Image
        except:
            import Image

        # Save image in temp-folder
        tempfolder = tempfile.mktemp()
        filepath = _fileutil.getOSPath('%s/%s' % (tempfolder, img.filename))
        _fileutil.exportObj(img, filepath)

        # Resize image
        im = Image.open(filepath)
        im = im.convert('RGB')
        maxdim = max(list(size))
        if mode == 'thumbnail':
            try:
                im.thumbnail((maxdim, maxdim), Image.ANTIALIAS)
            except:
                im.thumbnail((maxdim, maxdim))
                im.save(infile, "JPEG", quality=qual)
        elif mode == 'resize':
            try:
                im = im.resize(size, Image.ANTIALIAS)
            except:
                im = im.resize(size)
        elif mode == 'square':
            try:
                width, height = im.size
                dst_width, dst_height = maxdim, maxdim
                if width > height:
                    delta = width - height
                    left = int(delta / 2)
                    upper = 0
                    right = height + left
                    lower = height
                else:
                    delta = height - width
                    left = 0
                    upper = int(delta / 2)
                    right = width
                    lower = width + upper
                im = im.crop((left, upper, right, lower))
                im = im.resize((dst_width, dst_height), Image.ANTIALIAS)
            except:
                im.resize(size)
        im.save(filepath, "JPEG", quality=qual)

        # Read resized image from file-system
        f = open(filepath, 'rb')
        result_data = f.read()
        thumb_sffx = str(sffx)
        getfilename = _fileutil.extractFilename(filepath).split('.')
        filename = getfilename[0:-1]
        filename = ".".join(filename)
        filename = filename.replace('.', '_')
        extension = _fileutil.extractFileExt(filepath)
        result_filename = filename + thumb_sffx + '.' + extension
        result = {'data': result_data, 'filename': result_filename}
        f.close()

        # Remove temp-folder and images
        _fileutil.remove(tempfolder, deep=1)

        # Returns resulting image
        image = self.context.ImageFromData(result['data'], result['filename'])
        return image
Exemplo n.º 13
0
    def manage_customizeDesign(self, btn, lang, REQUEST, RESPONSE):
        """ ConfManager.manage_customizeDesign """
        message = ''
        cssId = REQUEST.get('cssId', '')

        # Ex-/Import.
        # -----------
        if btn in [
                self.getZMILangStr('BTN_EXPORT'),
                self.getZMILangStr('BTN_IMPORT')
        ]:
            #-- Theme.
            home = self.getHome()
            home_id = home.id
            temp_folder = self.temp_folder
            # Init exclude-ids.
            excl_ids = []
            # Add clients-folders to exclude-ids.
            for folder in home.objectValues(['Folder']):
                if len(folder.objectValues(['ZMS'])) > 0:
                    excl_ids.append(absattr(folder.id))
            # Add content-object artefacts to exclude-ids.
            for metaObjId in self.getMetaobjIds():
                for metaObjAttrId in self.getMetaobjAttrIds(metaObjId):
                    metaObjAttr = self.getMetaobjAttr(metaObjId, metaObjAttrId)
                    if metaObjAttr[
                            'type'] in self.metaobj_manager.valid_zopetypes:
                        excl_ids.append(metaObjAttrId)
            # Filter ids.
            ids = filter(lambda x: x not in excl_ids,
                         home.objectIds(self.metaobj_manager.valid_zopetypes))
            if btn == self.getZMILangStr('BTN_EXPORT'):
                if home_id in temp_folder.objectIds():
                    temp_folder.manage_delObjects(ids=[home_id])
                temp_folder.manage_addFolder(id=home_id,
                                             title=home.title_or_id())
                folder = getattr(temp_folder, home_id)
                home.manage_copyObjects(ids, REQUEST)
                folder.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST)
                return RESPONSE.redirect(
                    self.url_append_params(
                        '%s/manage_exportObject' % temp_folder.absolute_url(),
                        {
                            'id': home_id,
                            'download:int': 1
                        }))
            if btn == self.getZMILangStr('BTN_IMPORT'):
                v = REQUEST['theme']
                temp_filename = _fileutil.extractFilename(v.filename)
                temp_id = temp_filename[:temp_filename.rfind('.')]
                filepath = INSTANCE_HOME + '/import/' + temp_filename
                _fileutil.exportObj(v, filepath)
                if temp_id in temp_folder.objectIds():
                    temp_folder.manage_delObjects(ids=[temp_id])
                temp_folder.manage_importObject(temp_filename)
                folder = getattr(temp_folder, temp_id)
                home.manage_delObjects(ids=ids)
                folder.manage_copyObjects(folder.objectIds(), REQUEST)
                home.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST)
                _fileutil.remove(filepath)
                temp_folder.manage_delObjects(ids=[temp_id])

        # Save.
        # -----
        if btn == self.getZMILangStr('BTN_SAVE'):
            #-- Stylesheet.
            if REQUEST.has_key('cssId'):
                if REQUEST.get('default'):
                    self.setConfProperty('ZMS.stylesheet',
                                         REQUEST.get('cssId'))
                css = self.getStylesheet(REQUEST.get('cssId'))
                data = REQUEST.get('stylesheet')
                title = css.title
                css.manage_edit(data, title)
                message = self.getZMILangStr('MSG_CHANGED')
            #-- Sitemap.
            if REQUEST.has_key('attr_layoutsitemap'):
                if len(REQUEST['attr_layoutsitemap']) > 0:
                    self.attr_layoutsitemap = int(
                        REQUEST['attr_layoutsitemap'])
                elif hasattr(self, 'attr_layoutsitemap'):
                    delattr(self, 'attr_layoutsitemap')
                message = self.getZMILangStr('MSG_CHANGED')

        # Upload.
        # -------
        elif btn == self.getZMILangStr('BTN_UPLOAD'):
            #-- ZMI Logo.
            self.zmi_logo = Image(id='logo', title='', file='')
            self.zmi_logo.manage_upload(REQUEST['file'], REQUEST)
            message = self.getZMILangStr('MSG_CHANGED')

        # Return with message.
        message = urllib.quote(message)
        return RESPONSE.redirect(
            'manage_customizeDesignForm?lang=%s&manage_tabs_message=%s&cssId=%s'
            % (lang, message, cssId))