Ejemplo n.º 1
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the document with the given client object.

        o If supplied, use 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 propagation!
                r = 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 = HTML.__call__(self, (client, bself), REQUEST, **kw)

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

        finally:
            security.removeContext(self)

        have_key = RESPONSE.headers.__contains__
        if not (have_key('content-type') or have_key('Content-Type')):
            if 'content_type' in self.__dict__:
                c = self.content_type
            else:
                encoding = getattr(self, 'encoding', default_encoding)
                if six.PY2 and not isinstance(r, six.text_type):
                    # Prevent double-encoding edge cases under Python 2
                    r = r.decode(encoding)
                c, e = guess_content_type(self.getId(), r.encode(encoding))
            RESPONSE.setHeader('Content-Type', c)
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result
Ejemplo n.º 2
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
Ejemplo n.º 3
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the DTML given a client object, REQUEST mapping,
        Response, and key word arguments."""

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

        finally: security.removeContext(self)
Ejemplo n.º 4
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render the DTML given a client object, REQUEST mapping,
        Response, and key word arguments."""

        security = getSecurityManager()
        security.addContext(self)
        try:
            return HTML.__call__(self, client, REQUEST, **kw)
        finally:
            security.removeContext(self)
Ejemplo n.º 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)

        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
Ejemplo n.º 6
0
class STXTopic(TextTopic):
    """
    A structured-text topic. Holds a HTMLFile object.
    """
    index_html = None

    def __call__(self, REQUEST=None):
        """ View the STX Help Topic """
        self._check_for_update()
        return self.htmlfile(self, REQUEST)

    htmlfile = HTML("""\
    <html>
      <head><title><dtml-var title_or_id></title>
      </head>
      <body bgcolor="#FFFFFF">
        <dtml-var obj fmt="structured-text">
      </body>
    </html>""")
Ejemplo n.º 7
0
class ReSTTopic(TextTopic):
    """
    A reStructuredText [1]_ topic.  Similar to STXTopic, it uses a
    simle DTML construct to render its contents - this time using the
    *reStructuredText* language.

    .. [1] reStructuredText
       (http://docutils.sourceforge.net/rst.html)
    """
    index_html = None

    def __call__(self, REQUEST=None):
        """ Renders the ReST Help Topic """
        self._check_for_update()
        return self.htmlfile(self, REQUEST)

    htmlfile = HTML("""\
    <html>
      <head><title><dtml-var title_or_id></title>
      </head>
      <body bgcolor="#FFFFFF">
        <dtml-var obj fmt="restructured-text">
      </body>
    </html>""")
Ejemplo n.º 8
0
    def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
        """Render using the given client object

        o If client is not passed, we are being called as a sub-template:
          don't do any error propagation.

        o If supplied, use the 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
                    headers_get = RESPONSE.headers.get

                    if headers_get('content-length', None) is None:
                        RESPONSE.setHeader('content-length', len(data))

                    if headers_get('content-type', None) is None and \
                       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 'validate' in self.__dict__:
            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 = 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 = HTML.__call__(self, client, REQUEST, **kw)

            if RESPONSE is None or not isinstance(r, str):
                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.__contains__
        if not (have_key('content-type') or have_key('Content-Type')):
            if 'content_type' in self.__dict__:
                c = self.content_type
            else:
                encoding = getattr(self, 'encoding', default_encoding)
                c, e = guess_content_type(self.getId(), r.encode(encoding))
            RESPONSE.setHeader('Content-Type', c)
        result = decapitate(r, RESPONSE)
        if not self._cache_namespace_keys:
            self.ZCacheable_set(result)
        return result
Ejemplo n.º 9
0
 def read_raw(self):
     if not self._reading:
         self._updateFromFS()
     return HTML.read_raw(self)
Ejemplo n.º 10
0
    def raise_standardErrorMessage(self,
                                   client=None,
                                   REQUEST={},
                                   error_type=None,
                                   error_value=None,
                                   tb=None,
                                   error_tb=None,
                                   error_message='',
                                   tagSearch=re.compile(r'[a-zA-Z]>').search,
                                   error_log_url=''):

        try:
            if error_type is None: error_type = sys.exc_info()[0]
            if error_value is None: error_value = sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb = sys.exc_info()[2]
            if type(tb) is not str and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is str and not error_tb:
                error_tb = tb

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek = 1

            if hasattr(error_type, '__name__'):
                error_name = error_type.__name__
            else:
                error_name = 'Unknown'

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message = error_value

            if client is None:
                client = self

            if not REQUEST:
                REQUEST = aq_acquire(self, 'REQUEST')

            try:
                s = aq_acquire(client, 'standard_error_message')

                # For backward compatibility, we pass 'error_name' as
                # 'error_type' here as historically this has always
                # been a string.
                kwargs = {
                    'error_type': error_name,
                    'error_value': error_value,
                    'error_tb': error_tb,
                    'error_traceback': error_tb,
                    'error_message': xml_escape(str(error_message)),
                    'error_log_url': error_log_url
                }

                if getattr(aq_base(s), 'isDocTemp', 0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error('Exception while rendering an error message',
                             exc_info=True)
                try:
                    strv = repr(error_value)  # quotes tainted strings
                except:
                    strv = ('<unprintable %s object>' %
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)") %
                    (html_quote(sys.exc_info()[1]), ))

            # If we've been asked to handle errors, just return the rendered
            # exception and let the ZPublisher Exception Hook deal with it.
            return error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb = None
Ejemplo n.º 11
0
    def raise_standardErrorMessage(
        self, client=None, REQUEST={},
        error_type=None, error_value=None, tb=None,
        error_tb=None, error_message='',
        tagSearch=re.compile(r'[a-zA-Z]>').search,
        error_log_url=''):

        try:
            if error_type  is None: error_type =sys.exc_info()[0]
            if error_value is None: error_value=sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb=sys.exc_info()[2]
            if type(tb) is not type('') and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is type('') and not error_tb:
                error_tb = tb

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek = 1

            if hasattr(error_type, '__name__'):
                error_name = error_type.__name__
            else:
                error_name = 'Unknown'

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message=error_value

            if client is None:
                client = self

            if not REQUEST:
                REQUEST = aq_acquire(self, 'REQUEST')

            try:
                s = aq_acquire(client, 'standard_error_message')

                # For backward compatibility, we pass 'error_name' as
                # 'error_type' here as historically this has always
                # been a string.
                kwargs = {'error_type': error_name,
                          'error_value': error_value,
                          'error_tb': error_tb,
                          'error_traceback': error_tb,
                          'error_message': error_message,
                          'error_log_url': error_log_url}

                if getattr(aq_base(s), 'isDocTemp', 0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error(
                    'Exception while rendering an error message',
                    exc_info=True
                    )
                try:
                    strv = repr(error_value) # quotes tainted strings
                except:
                    strv = ('<unprintable %s object>' % 
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)")%(
                    html_quote(sys.exc_info()[1]),
                    ))

            # If we've been asked to handle errors, just return the rendered
            # exception and let the ZPublisher Exception Hook deal with it.
            return error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb = None
Ejemplo n.º 12
0
 def read_raw(self):
     if not self._reading:
         self._updateFromFS()
     return HTML.read_raw(self)
Ejemplo n.º 13
0
class BadFile(FSObject):

    """
        Represent a file which was not readable or parseable
        as its intended type.
    """
    meta_type = 'Bad File'
    icon = 'p_/broken'

    BAD_FILE_VIEW = """\
<dtml-var manage_page_header>
<dtml-var manage_tabs>
<h2> Bad Filesystem Object: &dtml-getId; </h2>

<h3> File Contents </h3>
<pre>
<dtml-var getFileContents>
</pre>

<h3> Exception </h3>
<pre>
<dtml-var getExceptionText>
</pre>
<dtml-var manage_page_footer>
"""

    manage_options = ({'label': 'Error', 'action': 'manage_showError'},)

    def __init__(self, id, filepath, exc_str='', fullname=None,
                 properties=None):
        id = fullname or id # Use the whole filename.
        self.exc_str = exc_str
        self.file_contents = ''
        FSObject.__init__(self, id, filepath, fullname, properties)

    security = ClassSecurityInfo()

    showError = HTML(BAD_FILE_VIEW)

    security.declareProtected(ManagePortal, 'manage_showError')
    def manage_showError(self, REQUEST):
        """
        """
        return self.showError(self, REQUEST)

    security.declarePrivate('_readFile')
    def _readFile(self, reparse):
        """Read the data from the filesystem.
        """
        try:
            file = open(self._filepath, 'rb')
            try:
                data = self.file_contents = file.read()
            finally:
                file.close()
        except:  # No errors of any sort may propagate
            data = self.file_contents = None #give up
        return data

    security.declarePublic('getFileContents')
    def getFileContents(self):
        """
            Return the contents of the file, if we could read it.
        """
        return self.file_contents

    security.declarePublic('getExceptionText')
    def getExceptionText(self):
        """
            Return the exception thrown while reading or parsing
            the file.
        """
        return self.exc_str
Ejemplo n.º 14
0
class HelpSys(Implicit, ObjectManager, Item, Persistent):
    """
    Zope Help System

    Provides browsing and searching of Zope Product Help.
    """
    meta_type = 'Help System'

    security = ClassSecurityInfo()
    security.declareObjectProtected(View)

    manage_options = (
        {
            'label': 'Contents',
            'action': 'menu'
        },
        {
            'label': 'Search',
            'action': 'search'
        },
    )

    def __init__(self, id='HelpSys'):
        self.id = id

    security.declareProtected(access_contents_information, 'helpValues')

    def helpValues(self, spec=None):
        "ProductHelp objects of all Products that have help"
        hv = []
        for product in self.Control_Panel.Products.objectValues():
            productHelp = product.getProductHelp()
            # only list products that actually have help
            if productHelp.helpValues():
                hv.append(productHelp)
        return hv

    # Seaching does an aggregated search of all ProductHelp
    # objects. Only Help Topics for which the user has permissions
    # are returned.

    security.declareProtected(View, '__call__')

    def __call__(self, REQUEST=None, **kw):
        "Searchable interface"
        if REQUEST is not None:
            perms = []
            sm = getSecurityManager()
            for p in self.ac_inherited_permissions(all=True):
                if sm.checkPermission(p[0], self):
                    perms.append(p[0])
            REQUEST.set('permissions', perms)
        results = []
        for ph in self.helpValues():
            results.append(apply(getattr(ph, '__call__'), (REQUEST, ), kw))
        return LazyCat(results)

    security.declareProtected(View, 'searchResults')
    searchResults = __call__

    security.declareProtected(View, 'index_html')
    index_html = DTMLFile('dtml/frame', globals())

    security.declareProtected(View, 'menu')
    menu = DTMLFile('dtml/menu', globals())

    security.declareProtected(View, 'search')
    search = DTMLFile('dtml/search', globals())

    security.declareProtected(View, 'results')
    results = DTMLFile('dtml/results', globals())

    security.declareProtected(View, 'main')
    main = HTML("""<html></html>""")
    standard_html_header = DTMLFile('dtml/menu_header', globals())
    standard_html_footer = DTMLFile('dtml/menu_footer', globals())

    button = DTMLFile('dtml/button', globals())

    security.declareProtected(View, 'HelpButton')

    def HelpButton(self, topic, product):
        """
        Insert a help button linked to a help topic.
        """
        return self.button(self, self.REQUEST, product=product, topic=topic)

    helpURL = DTMLFile('dtml/helpURL', globals())

    security.declareProtected(View, 'helpLink')

    def helpLink(self, product='OFSP', topic='ObjectManager_Contents.stx'):
        # Generate an <a href...> tag linking to a help topic. This
        # is a little lighter weight than the help button approach.
        basepath = self.REQUEST['BASEPATH1']
        products = self.Control_Panel.Products.objectIds()
        if product not in products:
            return None
        help_url = '%s/Control_Panel/Products/%s/Help/%s' % (basepath, product,
                                                             topic)
        help_url = '%s?help_url=%s' % (self.absolute_url(), help_url)

        script="window.open('%s','zope_help','width=600,height=500," \
               "menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes');" \
               "return false;" % escape(help_url, 1).replace("'", "\\'")

        h_link='<a href="%s" onClick="%s" onMouseOver="window.status=' \
               '\'Open online help\'; return true;" onMouseOut="' \
               'window.status=\'\'; return true;">Help!</a>' % (
               escape(help_url, 1), script
               )

        return h_link

    def tpValues(self):
        """
        Tree protocol - returns child nodes

        Aggregates Product Helps with the same title.
        """
        helps = {}
        for help in self.helpValues():
            if helps.has_key(help.title):
                helps[help.title].append(help)
            else:
                helps[help.title] = [help]
        cols = []
        for k, v in helps.items():
            cols.append(TreeCollection(k, v, 0))
        return cols
Ejemplo n.º 15
0
MessageDialog = HTML("""
<HTML>
<HEAD>
<TITLE>&dtml-title;</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FORM ACTION="&dtml-action;" METHOD="GET" <dtml-if
 target>TARGET="&dtml-target;"</dtml-if>>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="10">
<TR>
  <TD VALIGN="TOP">
  <BR>
  <CENTER><B><FONT SIZE="+6" COLOR="#77003B">!</FONT></B></CENTER>
  </TD>
  <TD VALIGN="TOP">
  <BR><BR>
  <CENTER>
  <dtml-var message>
  </CENTER>
  </TD>
</TR>
<TR>
  <TD VALIGN="TOP">
  </TD>
  <TD VALIGN="TOP">
  <CENTER>
  <INPUT TYPE="SUBMIT" VALUE="   Ok   ">
  </CENTER>
  </TD>
</TR>
</TABLE>
</FORM>
</BODY></HTML>""",
                     target='',
                     action='manage_main',
                     title='Changed')
Ejemplo n.º 16
0
def _raise_standardErrorMessage(self,
                                client=None,
                                REQUEST={},
                                error_type=None,
                                error_value=None,
                                tb=None,
                                error_tb=None,
                                error_message='',
                                tagSearch=re.compile(r'[a-zA-Z]>').search,
                                error_log_url=''):

    try:
        if error_type is None: error_type = sys.exc_info()[0]
        if error_value is None: error_value = sys.exc_info()[1]

        # allow for a few different traceback options
        if tb is None and error_tb is None:
            tb = sys.exc_info()[2]
        if type(tb) is not type('') and (error_tb is None):
            error_tb = pretty_tb(error_type, error_value, tb)
        elif type(tb) is type('') and not error_tb:
            error_tb = tb

        # turn error_type into a string
        if hasattr(error_type, '__name__'):
            error_type = error_type.__name__

        if hasattr(self, '_v_eek'):
            # Stop if there is recursion.
            raise error_type, error_value, tb
        self._v_eek = 1

        if str(error_type).lower() in ('redirect', ):
            raise error_type, error_value, tb

        if not error_message:
            try:
                s = ustr(error_value)
            except:
                s = error_value
            try:
                match = tagSearch(s)
            except TypeError:
                match = None
            if match is not None:
                error_message = error_value

        if client is None: client = self
        if not REQUEST: REQUEST = self.aq_acquire('REQUEST')

        try:
            if hasattr(client, 'standard_error_message'):
                s = getattr(client, 'standard_error_message')
            else:
                client = client.aq_parent
                s = getattr(client, 'standard_error_message')
            kwargs = {
                'error_type': error_type,
                'error_value': error_value,
                'error_tb': error_tb,
                'error_traceback': error_tb,
                'error_message': xml_escape(str(error_message)),
                'error_log_url': error_log_url
            }

            if getattr(aq_base(s), 'isDocTemp', 0):
                v = s(client, REQUEST, **kwargs)
            elif callable(s):
                v = s(**kwargs)
            else:
                v = HTML.__call__(s, client, REQUEST, **kwargs)
        except:
            logger.error('Exception while rendering an error message',
                         exc_info=True)
            try:
                strv = repr(error_value)  # quotes tainted strings
            except:
                strv = ('<unprintable %s object>' %
                        str(type(error_value).__name__))
            v = strv + (
                (" (Also, the following error occurred while attempting "
                 "to render the standard error message, please see the "
                 "event log for full details: %s)") %
                (html_quote(sys.exc_info()[1]), ))
        raise error_type, v, tb
    finally:
        if hasattr(self, '_v_eek'): del self._v_eek
        tb = None