Пример #1
0
 def test_add_two_files(self):
     ntypes = len(mimetypes.types_map)
     content_types.add_files([MIME_TYPES_1, MIME_TYPES_2])
     ctype, encoding = content_types.guess_content_type("foo.ztmt-1")
     self.assert_(encoding is None)
     self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-1")
     ctype, encoding = content_types.guess_content_type("foo.ztmt-2")
     self.assert_(encoding is None)
     self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-2")
     self.check_types_count(2)
Пример #2
0
    def _get_content_type(self, file, body, id, content_type=None):
        # Consult self.content_type first, this is either
        # the default (unknown/unknown) or it got a value from a
        # .metadata file
        default_type = 'unknown/unknown'
        if getattr(self, 'content_type', default_type) != default_type:
            return self.content_type

        # Next, look at file headers
        headers=getattr(file, 'headers', None)
        if headers and headers.has_key('content-type'):
            content_type=headers['content-type']
        else:
            # Last resort: Use the (imperfect) content type guessing
            # mechanism from OFS.Image, which ultimately uses the
            # Python mimetypes module.
            if not isinstance(body, basestring):
                body = body.data
            content_type, enc=guess_content_type(
                getattr(file, 'filename',id), body, content_type)
            if (enc is None
                and (content_type.startswith('text/') or
                     content_type.startswith('application/'))
                and body.startswith(codecs.BOM_UTF8)):
                content_type += '; charset=utf-8'

        return content_type
Пример #3
0
    def _get_content_type(self, file, body, id, content_type=None):
        # Consult self.content_type first, this is either
        # the default (unknown/unknown) or it got a value from a
        # .metadata file
        default_type = 'unknown/unknown'
        if getattr(self, 'content_type', default_type) != default_type:
            return self.content_type

        # Next, look at file headers
        headers = getattr(file, 'headers', None)
        if headers and headers.has_key('content-type'):
            content_type = headers['content-type']
        else:
            # Last resort: Use the (imperfect) content type guessing
            # mechanism from OFS.Image, which ultimately uses the
            # Python mimetypes module.
            if not isinstance(body, basestring):
                body = body.data
            content_type, enc = guess_content_type(
                getattr(file, 'filename', id), body, content_type)
            if (enc is None and (content_type.startswith('text/')
                                 or content_type.startswith('application/'))
                    and body.startswith(codecs.BOM_UTF8)):
                content_type += '; charset=utf-8'

        return content_type
Пример #4
0
 def _get_content_type(self, file, body, id, content_type=None):
     headers=getattr(file, 'headers', None)
     if headers and headers.has_key('content-type'):
         content_type=headers['content-type']
     else:
         if type(body) is not type(''): body=body.data
         content_type, enc=guess_content_type(
             getattr(file, 'filename',id), body, content_type)
     return content_type
Пример #5
0
    def __init__(self, path, name):
        self.path = path

        f = open(path, 'rb')
        data = f.read()
        f.close()
        self.content_type, enc = guess_content_type(path, data)
        self.__name__ = name
        self.lmt = float(os.path.getmtime(path)) or time()
        self.lmh = rfc1123_date(self.lmt)
Пример #6
0
    def __call__(self, name, content_type, data):
        if not content_type and data:
            content_type, width, height = getImageInfo(data)
        if not content_type:
            content_type, encoding = guess_content_type(name, data, '')

        if content_type.startswith('image/'):
            return Image(data)

        return File(data, content_type)
Пример #7
0
 def PUT_factory( self, name, typ, body ):
     """
         Hook PUT creation to make objects of the right type when
         new item uploaded via FTP/WebDAV.
     """
     if typ is None:
         typ, enc = guess_content_type()
     if typ == 'text/x-python':
         return PythonScript( name )
     if typ[ :4 ] == 'text':
         return DTMLMethod( '', __name__=name )
     return None # take the default, then
Пример #8
0
 def errors(self):
     form = self.request.form
     if "UPDATE_SUBMIT" in form:
         filename = getattr(form["field.data"], "filename", None)
         contenttype = form.get("field.contentType")
         if filename:
             if not contenttype:
                 contenttype = content_types.guess_content_type(filename)[0]
             if not form.get("add_input_name"):
                 form["add_input_name"] = filename
         return self.update_object(form["field.data"], contenttype)
     return ''
Пример #9
0
def my_guess_content_type(path, data):
    content_type, enc = guess_content_type(path, data)
    if content_type in ('text/plain', 'text/html','text/x-unknown-content-type'):
        if os.path.basename(path).endswith('.js-slimmed.js'):
            content_type = 'application/x-javascript'
        elif os.path.basename(path).find('.css-slimmed.css') > -1:
            # the find() covers both 'foo.css-slimmed' and
            # 'foo.css-slimmed-data64expanded'
            content_type = 'text/css'
        elif os.path.basename(path).find('.css-aliased.css') > -1:
            content_type = 'text/css'
    return content_type, enc
Пример #10
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the document given a client object, REQUEST mapping,
        Response, and key word arguments."""

        if not self._cache_namespace_keys:
            data = self.ZCacheable_get(default=_marker)
            if data is not _marker:
                # Return cached results.
                return data

        __traceback_supplement__ = (PathTracebackSupplement, self)
        kw['document_id']   =self.getId()
        kw['document_title']=self.title
        if hasattr(self, 'aq_explicit'):
            bself=self.aq_explicit
        else: bself=self

        security=getSecurityManager()
        security.addContext(self)

        try:
            if client is None:
                # Called as subtemplate, so don't need error propigation!
                r=apply(HTML.__call__, (self, bself, REQUEST), kw)
                if RESPONSE is None: result = r
                else: result = decapitate(r, RESPONSE)
                if not self._cache_namespace_keys:
                    self.ZCacheable_set(result)
                return result

            r=apply(HTML.__call__, (self, (client, bself), REQUEST), kw)
            if type(r) is not type('') or RESPONSE is None:
                if not self._cache_namespace_keys:
                    self.ZCacheable_set(r)
                return r

        finally: security.removeContext(self)

        have_key=RESPONSE.headers.has_key
        if not (have_key('content-type') or have_key('Content-Type')):
            if self.__dict__.has_key('content_type'):
                c=self.content_type
            else:
                c, e=guess_content_type(self.__name__, r)
            RESPONSE.setHeader('Content-Type', c)
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result
Пример #11
0
    def __init__(self, path='', contentType=''):
        self.path = path
        _data = open(os.path.normpath(self.path), 'rb').read()
        self._size = len(_data)
        self._fileMode = 'rb'
        self._encoding = DEFAULT_ENCODING

        if contentType=='':
            content_type, encoding = guess_content_type(self.path, _data, '')
        if content_type.startswith('image/'):
            self.contentType, width, height = getImageInfo(_data)
        else:
            self.contentType = content_type

        if self.contentType.startswith('text/'):
            self._fileMode = 'r'
            if encoding:
                self._encoding = encoding
Пример #12
0
    def get_attachments(self, fields, request):
        """Return all attachments uploaded in form.
        """

        from ZPublisher.HTTPRequest import FileUpload
        try:
            from zope.app.content_types import guess_content_type
        except ImportError:
            from OFS.content_types import guess_content_type

        attachments = []

        for field in fields:
            if field.isFileField():
                file = request.form.get('%s_file' % field.__name__, None)
                if file and isinstance(file, FileUpload) and file.filename != '':
                    file.seek(0) # rewind
                    data = file.read()
                    filename = file.filename
                    mimetype, enc = guess_content_type(filename, data, None)
                    attachments.append((filename, mimetype, enc, data))
        return attachments
Пример #13
0
    def __init__(self, path, _prefix=None):
        if _prefix is None:
            _prefix = getConfiguration().softwarehome
        elif type(_prefix) is not type(""):
            _prefix = package_home(_prefix)
        path = os.path.join(_prefix, path)
        self.path = path
        if Globals.DevelopmentMode:
            # In development mode, a shorter time is handy
            max_age = 60  # One minute
        else:
            # A longer time reduces latency in production mode
            max_age = 3600  # One hour
        self.cch = "public,max-age=%d" % max_age

        data = open(path, "rb").read()
        content_type, enc = guess_content_type(path, data)
        if content_type:
            self.content_type = content_type
        else:
            self.content_type = "image/%s" % path[path.rfind(".") + 1 :]
        self.__name__ = path[path.rfind("/") + 1 :]
        self.lmt = float(os.stat(path)[8]) or time.time()
        self.lmh = rfc1123_date(self.lmt)
Пример #14
0
    def PUT(self, REQUEST, RESPONSE):
        """Create a new non-collection resource.
        """
        from ZServer import LARGE_FILE_THRESHOLD

        self.dav__init(REQUEST, RESPONSE)

        name = self.__name__
        parent = self.__parent__

        ifhdr = REQUEST.get_header('If', '')
        if (IWriteLock.providedBy(parent) or
                WriteLockInterface.isImplementedBy(parent)) and \
                parent.wl_isLocked():
            if ifhdr:
                parent.dav__simpleifhandler(REQUEST, RESPONSE, col=1)
            else:
                # There was no If header at all, and our parent is locked,
                # so we fail here
                raise Locked
        elif ifhdr:
            # There was an If header, but the parent is not locked
            raise PreconditionFailed

        # SDS: Only use BODY if the file size is smaller than
        # LARGE_FILE_THRESHOLD, otherwise read LARGE_FILE_THRESHOLD
        # bytes from the file which should be enough to trigger
        # content_type detection, and possibly enough for CMF's
        # content_type_registry too.
        #
        # Note that body here is really just used for detecting the
        # content type and figuring out the correct factory. The correct
        # file content will be uploaded on ob.PUT(REQUEST, RESPONSE) after
        # the object has been created.
        #
        # A problem I could see is content_type_registry predicates
        # that do depend on the whole file being passed here as an
        # argument. There's none by default that does this though. If
        # they really do want to look at the file, they should use
        # REQUEST['BODYFILE'] directly and try as much as possible not
        # to read the whole file into memory.

        if int(REQUEST.get('CONTENT_LENGTH') or 0) > LARGE_FILE_THRESHOLD:
            file = REQUEST['BODYFILE']
            body = file.read(LARGE_FILE_THRESHOLD)
            file.seek(0)
        else:
            body = REQUEST.get('BODY', '')

        typ=REQUEST.get_header('content-type', None)
        if typ is None:
            typ, enc = guess_content_type(name, body)

        factory = getattr(parent, 'PUT_factory', self._default_PUT_factory )
        ob = factory(name, typ, body)
        if ob is None:
            ob = self._default_PUT_factory(name, typ, body)

        # We call _verifyObjectPaste with verify_src=0, to see if the
        # user can create this type of object (and we don't need to
        # check the clipboard.
        try:
            parent._verifyObjectPaste(ob.__of__(parent), 0)
        except CopyError:
            raise Unauthorized, sys.exc_info()[1]

        # Delegate actual PUT handling to the new object,
        # SDS: But just *after* it has been stored.
        self.__parent__._setObject(name, ob)
        ob = self.__parent__._getOb(name)
        ob.PUT(REQUEST, RESPONSE)

        RESPONSE.setStatus(201)
        RESPONSE.setBody('')
        return RESPONSE
Пример #15
0
    def PUT(self, REQUEST, RESPONSE):
        """ Create a new non-collection resource, deleting the LockNull
        object from the container before putting the new object in. """

        self.dav__init(REQUEST, RESPONSE)
        name = self.__name__
        parent = self.aq_parent
        parenturl = parent.absolute_url()
        ifhdr = REQUEST.get_header('If', '')

        # Since a Lock null resource is always locked by definition, all
        # operations done by an owner of the lock that affect the resource
        # MUST have the If header in the request
        if not ifhdr:
            raise PreconditionFailed, 'No If-header'

        # First we need to see if the parent of the locknull is locked, and
        # if the user owns that lock (checked by handling the information in
        # the If header).
        if (IWriteLock.providedBy(parent) or
                WriteLockInterface.isImplementedBy(parent)) and \
                parent.wl_isLocked():
            itrue = parent.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT',
                                                col=1, url=parenturl,
                                                refresh=1)
            if not itrue:
                raise PreconditionFailed, (
                'Condition failed against resources parent')

        # Now we need to check the If header against our own lock state
        itrue = self.dav__simpleifhandler(REQUEST, RESPONSE, 'PUT', refresh=1)
        if not itrue:
            raise PreconditionFailed, (
            'Condition failed against locknull resource')

        # All of the If header tests succeeded, now we need to remove ourselves
        # from our parent.  We need to transfer lock state to the new object.
        locks = self.wl_lockItems()
        parent._delObject(name)

        # Now we need to go through the regular operations of PUT
        body = REQUEST.get('BODY', '')
        typ = REQUEST.get_header('content-type', None)
        if typ is None:
            typ, enc = guess_content_type(name, body)

        factory = getattr(parent, 'PUT_factory', self._default_PUT_factory)
        ob = (factory(name, typ, body) or
              self._default_PUT_factory(name, typ, body))

        # Verify that the user can create this type of object
        try:
            parent._verifyObjectPaste(ob.__of__(parent), 0)
        except Unauthorized:
            raise
        except:
            raise Forbidden, sys.exc_info()[1]

        # Put the locks on the new object
        if not (IWriteLock.providedBy(ob) or
                WriteLockInterface.isImplementedBy(ob)):
            raise MethodNotAllowed, (
                'The target object type cannot be locked')
        for token, lock in locks:
            ob.wl_setLock(token, lock)

        # Delegate actual PUT handling to the new object.
        ob.PUT(REQUEST, RESPONSE)
        parent._setObject(name, ob)

        RESPONSE.setStatus(201)
        RESPONSE.setBody('')
        return RESPONSE
Пример #16
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the document given a client object, REQUEST mapping,
        Response, and key word arguments."""

        if not self._cache_namespace_keys:
            data = self.ZCacheable_get(default=_marker)
            if data is not _marker:
                if ( IStreamIterator.isImplementedBy(data) and
                     RESPONSE is not None ):
                    # This is a stream iterator and we need to set some
                    # headers now before giving it to medusa
                    if RESPONSE.headers.get('content-length', None) is None:
                        RESPONSE.setHeader('content-length', len(data))

                    if ( RESPONSE.headers.get('content-type', None) is None and
                         RESPONSE.headers.get('Content-type', None) is None ):
                        ct = ( self.__dict__.get('content_type') or
                               self.default_content_type )
                        RESPONSE.setHeader('content-type', ct)

                # Return cached results.
                return data

        __traceback_supplement__ = (PathTracebackSupplement, self)
        kw['document_id']   =self.getId()
        kw['document_title']=self.title

        security=getSecurityManager()
        security.addContext(self)
        if self.__dict__.has_key('validate'):
            first_time_through = 0
        else:
            self.__dict__['validate'] = security.DTMLValidate
            first_time_through = 1
        try:

            if client is None:
                # Called as subtemplate, so don't need error propagation!
                r=apply(HTML.__call__, (self, client, REQUEST), kw)
                if RESPONSE is None: result = r
                else: result = decapitate(r, RESPONSE)
                if not self._cache_namespace_keys:
                    self.ZCacheable_set(result)
                return result

            r=apply(HTML.__call__, (self, client, REQUEST), kw)
            if type(r) is not type('') or RESPONSE is None:
                if not self._cache_namespace_keys:
                    self.ZCacheable_set(r)
                return r

        finally:
            security.removeContext(self)
            if first_time_through:
                del self.__dict__['validate']

        have_key=RESPONSE.headers.has_key
        if not (have_key('content-type') or have_key('Content-Type')):
            if self.__dict__.has_key('content_type'):
                c=self.content_type
            else:
                c, e=guess_content_type(self.getId(), r)
            RESPONSE.setHeader('Content-Type', c)
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result