Example #1
0
    def index_html(self, REQUEST, RESPONSE):
        """
        Display the image, with or without standard_html_[header|footer],
        as appropriate.
        """
        view = _ViewEmulator().__of__(self)

        # If we have a conditional get, set status 304 and return
        # no content
        if _checkConditionalGET(view, extra_context={}):
            return ''

        # old-style If-Modified-Since header handling.
        if self._setOldCacheHeaders():
            # Make sure the CachingPolicyManager gets a go as well
            _setCacheHeaders(view, extra_context={})
            return ''

        try:
            return OFS.Image.Image.index_html(self, REQUEST, RESPONSE)
        finally:
            if self.ZCacheable_getManager() is None:
                # not none cache manager already taken care of
                _setCacheHeaders(view, extra_context={})
            else:
                self.ZCacheable_set(None)
Example #2
0
    def index_html(self, REQUEST, RESPONSE):
        """
        The default view of the contents of a File or Image.

        Returns the contents of the file or image.  Also, sets the
        Content-Type HTTP header to the objects content type.
        """
        self._updateFromFS()
        view = _ViewEmulator().__of__(self)

        # If we have a conditional get, set status 304 and return
        # no content
        if _checkConditionalGET(view, extra_context={}):
            return ''

        RESPONSE.setHeader('Content-Type', self.content_type)

        # old-style If-Modified-Since header handling.
        if self._setOldCacheHeaders():
            # Make sure the CachingPolicyManager gets a go as well
            _setCacheHeaders(view, extra_context={})
            return ''

        data = self._readFile(0)
        data_len = len(data)
        RESPONSE.setHeader('Content-Length', data_len)

        #There are 2 Cache Managers which can be in play....
        #need to decide which to use to determine where the cache headers
        #are decided on.
        if self.ZCacheable_getManager() is not None:
            self.ZCacheable_set(None)
        else:
            _setCacheHeaders(view, extra_context={})
        return data
Example #3
0
    def index_html(self, REQUEST, RESPONSE):
        """
        Display the image, with or without standard_html_[header|footer],
        as appropriate.
        """
        view = _ViewEmulator().__of__(self)

        # If we have a conditional get, set status 304 and return
        # no content
        if _checkConditionalGET(view, extra_context={}):
            return ''

        # old-style If-Modified-Since header handling.
        if self._setOldCacheHeaders():
            # Make sure the CachingPolicyManager gets a go as well
            _setCacheHeaders(view, extra_context={})
            return ''

        rendered = OFS.Image.Image.index_html(self, REQUEST, RESPONSE)

        if self.ZCacheable_getManager() is None:
            # not none cache manager already taken care of
            _setCacheHeaders(view, extra_context={})
        else:
            self.ZCacheable_set(None)

        return rendered
Example #4
0
 def getExtensibleContent(self, request, name):
     # Be sure that html conversion is done,
     # as it is required to extract extensible content
     old_manager, user = self._forceIdentification(request)
     web_cache_kw = {'name': name, 'format': EMBEDDED_FORMAT}
     try:
         self._convert(format='html')
         view = _ViewEmulator().__of__(self)
         # If we have a conditional get, set status 304 and return
         # no content
         if _checkConditionalGET(view, web_cache_kw):
             return ''
         # call caching policy manager.
         _setCacheHeaders(view, web_cache_kw)
         mime, data = self.getConversion(format=EMBEDDED_FORMAT,
                                         filename=name)
         document = OFSFile(name, name, data,
                            content_type=mime).__of__(self.aq_parent)
     except (NotConvertedError, ConversionError, KeyError):
         document = DocumentExtensibleTraversableMixin.getExtensibleContent(
             self, request, name)
     # restore original security context if there's a logged in user
     if user is not None:
         setSecurityManager(old_manager)
     return document
Example #5
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the document given a client object, REQUEST mapping,
        Response, and key word arguments."""

        self._updateFromFS()

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

        if client is not None:
            if _checkConditionalGET(self, kw):
                return ''

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

        __traceback_info__ = self._filepath
        security = getSecurityManager()
        security.addContext(self)
        try:
            r = HTML.__call__(self, client, REQUEST, **kw)

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

            if not isinstance(r, basestring) or RESPONSE is None:
                if not self._cache_namespace_keys:
                    self.ZCacheable_set(r)
                return r

        finally:
            security.removeContext(self)

        headers = RESPONSE.headers
        if not ('content-type' in headers or 'Content-Type' in headers):
            if 'content_type' in self.__dict__:
                c = self.content_type
            else:
                c, _e = guess_content_type(self.getId(), r)
            RESPONSE.setHeader('Content-Type', c)
        if RESPONSE is not None:
            # caching policy manager hook
            _setCacheHeaders(self, {})
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result
Example #6
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the document given a client object, REQUEST mapping,
        Response, and key word arguments."""

        self._updateFromFS()

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

        if client is not None:
            if _checkConditionalGET(self, kw):
                return ''

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

        __traceback_info__ = self._filepath
        security=getSecurityManager()
        security.addContext(self)
        try:
            r = HTML.__call__(self, client, REQUEST, **kw)

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

            if not isinstance(r, basestring) 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.getId(), r)
            RESPONSE.setHeader('Content-Type', c)
        if RESPONSE is not None:
            # caching policy manager hook
            _setCacheHeaders(self, {})
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result
Example #7
0
    def pt_render(self, source=0, extra_context={}):
        self._updateFromFS()  # Make sure the template has been loaded.

        if not source:
            # If we have a conditional get, set status 304 and return
            # no content
            if _checkConditionalGET(self, extra_context):
                return ''

        result = FSPageTemplate.inheritedAttribute('pt_render')(self, source,
                                                                extra_context)
        if not source:
            _setCacheHeaders(self, extra_context)
        return result
Example #8
0
    def __call__(self, REQUEST={}, RESPONSE=None, **kw):
        """ Return our rendered StructuredText.
        """
        self._updateFromFS()

        if RESPONSE is not None:
            RESPONSE.setHeader('Content-Type', 'text/html')

        view = _ViewEmulator(self.getId()).__of__(self)
        if _checkConditionalGET(view, extra_context={}):
            return ''

        _setCacheHeaders(view, extra_context={})

        return self._render(REQUEST, RESPONSE, **kw)
Example #9
0
    def __call__( self, REQUEST={}, RESPONSE=None, **kw ):
        """ Return our rendered StructuredText.
        """
        self._updateFromFS()

        if RESPONSE is not None:
            RESPONSE.setHeader( 'Content-Type', 'text/html' )

        view = _ViewEmulator(self.getId()).__of__(self)
        if _checkConditionalGET(view, extra_context={}):
            return ''

        _setCacheHeaders(view, extra_context={})

        return self._render(REQUEST, RESPONSE, **kw)
    def pt_render(self, source=0, extra_context={}):
        self._updateFromFS()  # Make sure the template has been loaded.

        if not source:
            # If we have a conditional get, set status 304 and return
            # no content
            if _checkConditionalGET(self, extra_context):
                return ''

        result = PDTPageTemplate.inheritedAttribute('pt_render')(
                                self, source, extra_context
                                )
        if not source:
            _setCacheHeaders(self, extra_context)
        return result
 def getExtensibleContent(self, request, name):
   # Be sure that html conversion is done,
   # as it is required to extract extensible content
   old_manager, user = self._forceIdentification(request)
   web_cache_kw = {'name': name,
                   'format': EMBEDDED_FORMAT}
   try:
     self._convert(format='html')
     view = _ViewEmulator().__of__(self)
     # If we have a conditional get, set status 304 and return
     # no content
     if _checkConditionalGET(view, web_cache_kw):
       return ''
     # call caching policy manager.
     _setCacheHeaders(view, web_cache_kw)
     mime, data = self.getConversion(format=EMBEDDED_FORMAT, filename=name)
     document = OFSFile(name, name, data, content_type=mime).__of__(self.aq_parent)
   except (NotConvertedError, ConversionError, KeyError):
     document = DocumentExtensibleTraversableMixin.getExtensibleContent(self, request, name)
   # restore original security context if there's a logged in user
   if user is not None:
     setSecurityManager(old_manager)
   return document
Example #12
0
    def index_html(self,
                   REQUEST,
                   RESPONSE,
                   format=_MARKER,
                   inline=_MARKER,
                   **kw):
        """
      We follow here the standard Zope API for files and images
      and extend it to support format conversion. The idea
      is that an image which ID is "something.jpg" should
      ne directly accessible through the URL
      /a/b/something.jpg. The same is true for a file and
      for any document type which primary purpose is to
      be used by a helper application rather than displayed
      as HTML in a web browser. Exceptions to this approach
      include Web Pages which are intended to be primarily rendered
      withing the layout of a Web Site or withing a standard ERP5 page.
      Please refer to the index_html of TextDocument.

      Should return appropriate format (calling convert
      if necessary) and set headers.

      format -- the format specied in the form of an extension
      string (ex. jpeg, html, text, txt, etc.)

      **kw -- can be various things - e.g. resolution

    """
        from Products.ERP5.Document.Document import VALID_TEXT_FORMAT_LIST,\
                                                            VALID_IMAGE_FORMAT_LIST
        if format is _MARKER and not kw:
            # conversion parameters is mandatory to download the converted content.
            # By default allways return view action.
            # for all WevDAV access return raw content.
            return self.view()
        if format is _MARKER:
            format = None

        web_cache_kw = kw.copy()
        if format:
            web_cache_kw['format'] = format
        view = _ViewEmulator().__of__(self)
        # If we have a conditional get, set status 304 and return
        # no content
        if _checkConditionalGET(view, web_cache_kw):
            return ''
        # call caching policy manager.
        _setCacheHeaders(view, web_cache_kw)

        if not self.checkConversionFormatPermission(format, **kw):
            raise Forbidden('You are not allowed to get this document in this ' \
                            'format')
        mime, data = self.convert(format, **kw)
        output_format = None
        if not format or format == 'base-data':
            # Guess the format from original mimetype
            if mime:
                mimetypes_registry = getToolByName(self.getPortalObject(),
                                                   'mimetypes_registry')
                mimetype_object_list = mimetypes_registry.lookup(mime)
                for mimetype_object in mimetype_object_list:
                    if mimetype_object.extensions:
                        output_format = mimetype_object.extensions[0]
                        break
                    elif mimetype_object.globs:
                        output_format = mimetype_object.globs.strip('*.')
                        break
        if output_format is None:
            output_format = format

        RESPONSE.setHeader('Content-Length', len(data))
        if output_format in VALID_TEXT_FORMAT_LIST:
            RESPONSE.setHeader('Content-Type', '%s; charset=utf-8' % mime)
        else:
            RESPONSE.setHeader('Content-Type', mime)
        if inline is _MARKER:
            # by default, use inline for text and image formats
            inline = output_format in (VALID_TEXT_FORMAT_LIST +
                                       VALID_IMAGE_FORMAT_LIST)
        if not inline:
            # need to return it as attachment
            if format == 'base-data':
                filename = self.getStandardFilename(format=output_format)
            else:
                filename = self.getStandardFilename(format=format)
            # workaround for IE's bug to download files over SSL
            RESPONSE.setHeader('Pragma', '')
            RESPONSE.setHeader('Content-Disposition',
                               'attachment; filename="%s"' % filename)
            RESPONSE.setHeader('Accept-Ranges', 'bytes')
        else:
            RESPONSE.setHeader('Content-Disposition', 'inline')
        return str(data)
Example #13
0
    def __call__(self):
      """
        If a Web Section has a default document, we render
        the default document instead of rendering the Web Section
        itself.

        The implementation is based on the presence of specific
        variables in the REQUEST (besides editable_mode and
        ignore_layout).

        current_web_section -- defines the Web Section which is
        used to display the current document.

        current_web_document -- defines the Document (ex. Web Page)
        which is being displayed within current_web_section.

        is_web_section_default_document -- a boolean which is
        set each time we display a default document as a section.

        We use REQUEST parameters so that they are reset for every
        Web transaction and can be accessed from widgets.
      """
      # Register current web site physical path for later URL generation
      if self.REQUEST.get(self.web_section_key, MARKER) is MARKER:
        self.REQUEST[self.web_section_key] = self.getPhysicalPath()
      self.REQUEST.set('current_web_section', self)
      if not self.REQUEST.get('editable_mode') and not self.REQUEST.get('ignore_layout'):
        document = None
        if self.isDefaultPageDisplayed():
          # The following could be moved to a typed based method for more flexibility
          document = self.getDefaultDocumentValue()
          if document is None:
            # no document found for current user, still such document may exists
            # in some cases user (like Anonymous) can not view document according to portal catalog
            # but we may ask him to login if such a document exists
            isAuthorizationForced = getattr(self, 'isAuthorizationForced', None)
            if isAuthorizationForced is not None and isAuthorizationForced():
              if unrestricted_apply(self.getDefaultDocumentValue) is not None:
                # force user to login as specified in Web Section
                raise Unauthorized
          if document is not None and document.getReference() is not None:
            # we use web_site_module/site_id/section_id/page_reference
            # as the url of the default document.
            self.REQUEST.set('current_web_document', document)
            self.REQUEST.set('is_web_section_default_document', 1)
            document = aq_base(document.asContext(
                id=document.getReference(),
                original_container=document.getParentValue(),
                original_id=document.getId(),
                editable_absolute_url=document.absolute_url())).__of__(self)
        # Try to use a custom renderer if any
        custom_render_method_id = self.getCustomRenderMethodId()
        if custom_render_method_id is not None:
          if document is None:
            document = self
          result = getattr(document, custom_render_method_id)()
          view = _ViewEmulator().__of__(self)
          # If we have a conditional get, set status 304 and return
          # no content
          if _checkConditionalGET(view, extra_context={}):
            return ''
          # call caching policy manager.
          _setCacheHeaders(view, {})
          return result
        elif document is not None:
          return document()
      return Domain.__call__(self)
Example #14
0
    def __call__(self):
        """
        If a Web Section has a default document, we render
        the default document instead of rendering the Web Section
        itself.

        The implementation is based on the presence of specific
        variables in the REQUEST (besides editable_mode and
        ignore_layout).

        current_web_section -- defines the Web Section which is
        used to display the current document.

        current_web_document -- defines the Document (ex. Web Page)
        which is being displayed within current_web_section.

        is_web_section_default_document -- a boolean which is
        set each time we display a default document as a section.

        We use REQUEST parameters so that they are reset for every
        Web transaction and can be accessed from widgets.
      """
        # Register current web site physical path for later URL generation
        if self.REQUEST.get(self.web_section_key, MARKER) is MARKER:
            self.REQUEST[self.web_section_key] = self.getPhysicalPath()
        self.REQUEST.set('current_web_section', self)
        if not self.REQUEST.get('editable_mode') and not self.REQUEST.get(
                'ignore_layout'):
            document = None
            if self.isDefaultPageDisplayed():
                # The following could be moved to a typed based method for more flexibility
                document = self.getDefaultDocumentValue()
                if document is None:
                    # no document found for current user, still such document may exists
                    # in some cases user (like Anonymous) can not view document according to portal catalog
                    # but we may ask him to login if such a document exists
                    isAuthorizationForced = getattr(self,
                                                    'isAuthorizationForced',
                                                    None)
                    if isAuthorizationForced is not None and isAuthorizationForced(
                    ):
                        if unrestricted_apply(
                                self.getDefaultDocumentValue) is not None:
                            # force user to login as specified in Web Section
                            raise Unauthorized
                if document is not None and document.getReference(
                ) is not None:
                    # we use web_site_module/site_id/section_id/page_reference
                    # as the url of the default document.
                    self.REQUEST.set('current_web_document', document)
                    self.REQUEST.set('is_web_section_default_document', 1)
                    document = aq_base(
                        document.asContext(
                            id=document.getReference(),
                            original_container=document.getParentValue(),
                            original_id=document.getId(),
                            editable_absolute_url=document.absolute_url())
                    ).__of__(self)
            else:
                isAuthorizationForced = getattr(self, 'isAuthorizationForced',
                                                None)
                if isAuthorizationForced is not None and isAuthorizationForced(
                ):
                    if self.getPortalObject(
                    ).portal_membership.isAnonymousUser():
                        # force anonymous to login
                        raise Unauthorized
            # Try to use a custom renderer if any
            custom_render_method_id = self.getCustomRenderMethodId()
            if custom_render_method_id is not None:
                if document is None:
                    document = self
                result = getattr(document, custom_render_method_id)()
                view = _ViewEmulator().__of__(self)
                # If we have a conditional get, set status 304 and return
                # no content
                if _checkConditionalGET(view, extra_context={}):
                    return ''
                # call caching policy manager.
                _setCacheHeaders(view, {})
                return result
            elif document is not None:
                return document()
        return Domain.__call__(self)
Example #15
0
    def index_html(self,
                   REQUEST,
                   RESPONSE,
                   format=_MARKER,
                   inline=_MARKER,
                   **kw):
        """XXXXXX"""
        range = REQUEST.get_header('Range', None)
        if range is None:
            start = None
            end = None
        else:
            ranges = HTTPRangeSupport.parseRange(range)
            (start, end) = ranges[0]

        if (format is _MARKER) and (not kw) and (range is None):
            # conversion parameters is mandatory to download the converted content.
            # By default allways return view action.
            # for all WevDAV access return raw content.
            return self.view()

        if format is _MARKER:
            format = None

        web_cache_kw = kw.copy()
        if format:
            web_cache_kw['format'] = format
        view = _ViewEmulator().__of__(self)
        # If we have a conditional get, set status 304 and return
        # no content
        if _checkConditionalGET(view, web_cache_kw):
            return ''
        # call caching policy manager.
        _setCacheHeaders(view, web_cache_kw)

        if not self.checkConversionFormatPermission(format, **kw):
            raise Forbidden('You are not allowed to get this document in this ' \
                            'format')
        mime, data = self.convert(format, **kw)
        total_length = len(data)
        if end is None:
            end = total_length
        if start is not None:
            data = data[start:end - 1]

        RESPONSE.setHeader('Content-Length', len(data))
        RESPONSE.setHeader('Content-Type', mime)
        filename = self.getStandardFilename(format=format)
        # workaround for IE's bug to download files over SSL
        RESPONSE.setHeader('Pragma', '')
        RESPONSE.setHeader('Content-Disposition',
                           'attachment; filename="%s"' % filename)
        RESPONSE.setHeader('Accept-Ranges', 'bytes')
        if start is None:
            RESPONSE.setStatus(200)
        else:
            RESPONSE.setHeader(
                'Content-Range',
                'bytes %s-%s/%s' % (start, end - 1, total_length))
            RESPONSE.setStatus(206)
        return str(data)
Example #16
0
  def index_html(self, REQUEST, RESPONSE, format=_MARKER, inline=_MARKER, **kw):
    """
      We follow here the standard Zope API for files and images
      and extend it to support format conversion. The idea
      is that an image which ID is "something.jpg" should
      ne directly accessible through the URL
      /a/b/something.jpg. The same is true for a file and
      for any document type which primary purpose is to
      be used by a helper application rather than displayed
      as HTML in a web browser. Exceptions to this approach
      include Web Pages which are intended to be primarily rendered
      withing the layout of a Web Site or withing a standard ERP5 page.
      Please refer to the index_html of TextDocument.

      Should return appropriate format (calling convert
      if necessary) and set headers.

      format -- the format specied in the form of an extension
      string (ex. jpeg, html, text, txt, etc.)

      **kw -- can be various things - e.g. resolution

    """
    from Products.ERP5.Document.Document import VALID_TEXT_FORMAT_LIST,\
                                                        VALID_IMAGE_FORMAT_LIST
    if format is _MARKER and not kw:
      # conversion parameters is mandatory to download the converted content.
      # By default allways return view action.
      # for all WevDAV access return raw content.
      return self.view()
    if format is _MARKER:
      format = None

    web_cache_kw = kw.copy()
    if format:
      web_cache_kw['format'] = format
    view = _ViewEmulator().__of__(self)
    # If we have a conditional get, set status 304 and return
    # no content
    if _checkConditionalGET(view, web_cache_kw):
      return ''
    # call caching policy manager.
    _setCacheHeaders(view, web_cache_kw)

    if not self.checkConversionFormatPermission(format, **kw):
      raise Forbidden('You are not allowed to get this document in this ' \
                      'format')
    mime, data = self.convert(format, **kw)
    output_format = None
    if not format or format == 'base-data':
      # Guess the format from original mimetype
      if mime:
        mimetypes_registry = getToolByName(self.getPortalObject(),
                                                            'mimetypes_registry')
        mimetype_object_list = mimetypes_registry.lookup(mime)
        for mimetype_object in mimetype_object_list:
          if mimetype_object.extensions:
            output_format = mimetype_object.extensions[0]
            break
          elif mimetype_object.globs:
            output_format = mimetype_object.globs.strip('*.')
            break
    if output_format is None:
      output_format = format

    RESPONSE.setHeader('Content-Length', len(data))
    if output_format in VALID_TEXT_FORMAT_LIST:
      RESPONSE.setHeader('Content-Type', '%s; charset=utf-8' % mime)
    else:
      RESPONSE.setHeader('Content-Type', mime)
    if inline is _MARKER:
      # by default, use inline for text and image formats
      inline = output_format in (VALID_TEXT_FORMAT_LIST + VALID_IMAGE_FORMAT_LIST)
    if not inline:
      # need to return it as attachment
      if format == 'base-data':
        filename = self.getStandardFilename(format=output_format)
      else:
        filename = self.getStandardFilename(format=format)
      RESPONSE.setHeader('Cache-Control', 'Private') # workaround for Internet Explorer's bug
      # workaround for IE's bug to download files over SSL
      RESPONSE.setHeader('Pragma', '')
      RESPONSE.setHeader('Content-Disposition',
                         'attachment; filename="%s"' % filename)
      RESPONSE.setHeader('Accept-Ranges', 'bytes')
    return str(data)