File: FSPageTemplate.py

package info (click to toggle)
zope-cmf 1.3.3-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,540 kB
  • ctags: 2,579
  • sloc: python: 16,976; sh: 51; makefile: 41
file content (196 lines) | stat: -rw-r--r-- 6,981 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
# 
##########################################################################
""" Customizable page templates that come from the filesystem.

$Id: FSPageTemplate.py,v 1.8.8.8 2003/09/01 16:09:22 tseaver Exp $
"""

from string import split, replace
from os import stat
import re, sys

import Globals, Acquisition
from DateTime import DateTime
from DocumentTemplate.DT_Util import html_quote
from Acquisition import aq_parent
from AccessControl import getSecurityManager, ClassSecurityInfo
from Shared.DC.Scripts.Script import Script
from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate, Src

from DirectoryView import registerFileExtension, registerMetaType, expandpath
from CMFCorePermissions import ViewManagementScreens, View, FTPAccess
from FSObject import FSObject
from utils import getToolByName

xml_detect_re = re.compile('^\s*<\?xml\s+')

class FSPageTemplate(FSObject, Script, PageTemplate):
    "Wrapper for Page Template"
     
    meta_type = 'Filesystem Page Template'

    _owner = None  # Unowned

    manage_options=(
        (
            {'label':'Customize', 'action':'manage_main'},
            {'label':'Test', 'action':'ZScriptHTML_tryForm'},
            )
        )

    security = ClassSecurityInfo()
    security.declareObjectProtected(View)

    security.declareProtected(ViewManagementScreens, 'manage_main')
    manage_main = Globals.DTMLFile('dtml/custpt', globals())

    # Declare security for unprotected PageTemplate methods.
    security.declarePrivate('pt_edit', 'write')

    def __init__(self, id, filepath, fullname=None, properties=None):
        FSObject.__init__(self, id, filepath, fullname, properties)
        self.ZBindings_edit(self._default_bindings)

    def _createZODBClone(self):
        """Create a ZODB (editable) equivalent of this object."""
        obj = ZopePageTemplate(self.getId(), self._text, self.content_type)
        obj.expand = 0
        obj.write(self.read())
        return obj

    def ZCacheable_isCachingEnabled(self):
        return 0

    def _readFile(self, reparse):
        fp = expandpath(self._filepath)
        file = open(fp, 'r')    # not 'rb', as this is a text file!
        try: 
            data = file.read()
        finally: 
            file.close()
        if reparse:
            if xml_detect_re.match(data):
                # Smells like xml
                self.content_type = 'text/xml'
            else:
                try:
                    del self.content_type
                except (AttributeError, KeyError):
                    pass
            self.write(data)

    security.declarePrivate('read')
    def read(self):
        # Tie in on an opportunity to auto-update
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('read')(self)

    ### The following is mainly taken from ZopePageTemplate.py ###

    expand = 0

    func_defaults = None
    func_code = ZopePageTemplate.func_code
    _default_bindings = ZopePageTemplate._default_bindings

    security.declareProtected(View, '__call__')

    def pt_macros(self):
        # Tie in on an opportunity to auto-reload
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('pt_macros')(self)

    def pt_render(self, source=0, extra_context={}):
        self._updateFromFS()  # Make sure the template has been loaded.
        try:
            if not source: # Hook up to caching policy.

                REQUEST = getattr( self, 'REQUEST', None )

                if REQUEST:

                    content = aq_parent( self )

                    mgr = getToolByName( content
                                       , 'caching_policy_manager'
                                       , None
                                       )

                    if mgr:
                        view_name = self.getId()
                        RESPONSE = REQUEST[ 'RESPONSE' ]
                        headers = mgr.getHTTPCachingHeaders( content
                                                           , view_name
                                                           , extra_context
                                                           )
                        for key, value in headers:
                            RESPONSE.setHeader( key, value )

            return FSPageTemplate.inheritedAttribute('pt_render')( self,
                    source, extra_context )

        except RuntimeError:
            if Globals.DevelopmentMode:
                err = FSPageTemplate.inheritedAttribute( 'pt_errors' )( self )
                if not err:
                    err = sys.exc_info()
                err_type = err[0]
                err_msg = '<pre>%s</pre>' % replace( str(err[1]), "\'", "'" )
                msg = 'FS Page Template %s has errors: %s.<br>%s' % (
                    self.id, err_type, html_quote(err_msg) )
                raise RuntimeError, msg
            else:
                raise
                
    security.declarePrivate( '_ZPT_exec' )
    _ZPT_exec = ZopePageTemplate._exec

    security.declarePrivate( '_exec' )
    def _exec(self, bound_names, args, kw):
        """Call a FSPageTemplate"""
        try:
            response = self.REQUEST.RESPONSE
        except AttributeError:
            response = None
        # Read file first to get a correct content_type default value.
        self._updateFromFS()
        # call "inherited"
        result = self._ZPT_exec( bound_names, args, kw )
        return result
 
    # Copy over more methods
    security.declareProtected(FTPAccess, 'manage_FTPget')
    security.declareProtected(View, 'get_size')
    security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource',
        'document_src')

    pt_getContext = ZopePageTemplate.pt_getContext
    ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams
    manage_FTPget = ZopePageTemplate.manage_FTPget
    get_size = ZopePageTemplate.get_size
    getSize = get_size
    PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource
    document_src = ZopePageTemplate.document_src


d = FSPageTemplate.__dict__
d['source.xml'] = d['source.html'] = Src()

Globals.InitializeClass(FSPageTemplate)

registerFileExtension('pt', FSPageTemplate)
registerFileExtension('html', FSPageTemplate)
registerFileExtension('htm', FSPageTemplate)
registerMetaType('Page Template', FSPageTemplate)