[ZPT] CVS: Packages/Products/PageTemplates (Products/DC/PageTemplates) - PageTemplateFile.py:1.1 Expressions.py:1.11 PageTemplate.py:1.10 TALES.py:1.10 ZopePageTemplate.py:1.8
evan@serenade.digicool.com
evan@serenade.digicool.com
Fri, 11 May 2001 19:45:21 -0400
Update of /cvs-repository/Packages/Products/PageTemplates
In directory serenade:/home/evan/Zope/pt/lib/python/Products/PageTemplates2
Modified Files:
Expressions.py PageTemplate.py TALES.py ZopePageTemplate.py
Added Files:
PageTemplateFile.py
Log Message:
Created PageTemplateFile module and class.
Implemented alternate path '|' operator.
Added 'default' builtin.
Made Expression types available to python expressions as functions.
Changed the way render() calls DTML.
--- Added File PageTemplateFile.py in package Packages/Products/PageTemplates ---
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
"""Filesystem Page Template module
Zope object encapsulating a Page Template from the filesystem.
"""
__version__='$Revision: 1.1 $'[11:-2]
import os, AccessControl, Acquisition, sys
from Globals import package_home, DevelopmentMode
from zLOG import LOG, ERROR, INFO
from string import join, strip, rstrip, split, replace, lower
from Shared.DC.Scripts.Script import Script, BindingsUI
from Shared.DC.Scripts.Signature import FuncCode
from AccessControl import getSecurityManager
from OFS.Traversable import Traversable
from PageTemplate import PageTemplate
from ZopePageTemplate import SecureModuleImporter
from ComputedAttribute import ComputedAttribute
class PageTemplateFile(Script, PageTemplate, Traversable):
"Zope wrapper for filesystem Page Template using TAL, TALES, and METAL"
meta_type = 'Page Template (File)'
func_defaults = None
func_code = FuncCode((), 0)
_need__name__=1
_v_last_read=0
_default_bindings = {'name_subpath': 'traverse_subpath'}
security = AccessControl.ClassSecurityInfo()
security.declareObjectProtected('View')
security.declareProtected('View', '__call__')
security.declareProtected('View management screens',
'read', 'document_src')
def __init__(self, filename, _prefix=None, **kw):
self.ZBindings_edit(self._default_bindings)
if _prefix is None: _prefix=SOFTWARE_HOME
elif type(_prefix) is not type(''):
_prefix = package_home(_prefix)
name = kw.get('__name__')
if not name:
name = os.path.split(filename)[-1]
self.__name__ = name
self.filename = filename = os.path.join(_prefix, filename + '.zpt')
def pt_getContext(self):
root = self.getPhysicalRoot()
c = {'template': self,
'here': self._getContext(),
'container': self._getContainer(),
'nothing': None,
'options': {},
'root': root,
'request': getattr(root, 'REQUEST', None),
'modules': SecureModuleImporter,
}
return c
def _exec(self, bound_names, args, kw):
"""Call a Page Template"""
self._cook_check()
if not kw.has_key('args'):
kw['args'] = args
bound_names['options'] = kw
try:
self.REQUEST.RESPONSE.setHeader('content-type',
self.content_type)
except AttributeError: pass
# Execute the template in a new security context.
security=getSecurityManager()
security.addContext(self)
try:
return self.pt_render(extra_context=bound_names)
finally:
security.removeContext(self)
def _cook_check(self):
if self._v_last_read and not DevelopmentMode:
return
__traceback_info__ = self.filename
try: mtime=os.stat(self.filename)[8]
except: mtime=0
if mtime == self._v_last_read:
return
self.pt_edit(open(self.filename), None)
self._cook()
self._v_last_read = mtime
def document_src(self, REQUEST=None, RESPONSE=None):
"""Return expanded document source."""
if RESPONSE is not None:
RESPONSE.setHeader('Content-Type', self.content_type)
return self.read()
def _get__roles__(self):
imp = getattr(aq_parent(aq_inner(self)),
'%s__roles__' % self.__name__)
if hasattr(imp, '__of__'):
return imp.__of__(self)
return imp
__roles__ = ComputedAttribute(_get__roles__, 1)
def __setstate__(self, state):
raise StorageError, ("Instance of AntiPersistent class %s "
"cannot be stored." % self.__class__.__name__)
--- Updated File Expressions.py in package Packages/Products/PageTemplates --
--- Expressions.py 2001/05/08 01:51:43 1.10
+++ Expressions.py 2001/05/11 23:44:51 1.11
@@ -93,9 +93,8 @@
import re, sys
from TALES import Engine, CompilerError, _valid_name, NAME_RE, \
- TALESError, Undefined
+ TALESError, Undefined, Default
from string import strip, split, join, replace, lstrip
-from DocumentTemplate.DT_Util import TemplateDict
from Acquisition import aq_base, aq_inner, aq_parent
_engine = None
@@ -109,26 +108,50 @@
def installHandlers(engine):
reg = engine.registerType
pe = PathExpr
- for pt in ('standard', 'path', 'nocall', 'exists'):
+ for pt in ('standard', 'path'):
reg(pt, pe)
reg('string', StringExpr)
reg('python', PythonExpr)
reg('not', NotExpr)
reg('import', ImportExpr)
+if sys.modules.has_key('Zope'):
+ from AccessControl import getSecurityManager
+ from DocumentTemplate.DT_Util import TemplateDict, InstanceDict
+ def call_with_ns(f, ns, arg=1):
+ td = TemplateDict()
+ td.validate = getSecurityManager().validate
+ td.this = None
+ td._push(ns['request'])
+ td._push(InstanceDict(ns['here'], td))
+ td._push(ns['var'])
+ try:
+ if arg==2:
+ return f(None, td)
+ else:
+ return f(td)
+ finally:
+ td._pop(3)
+else:
+ def call_with_ns(f, ns, arg=1):
+ if arg==2:
+ return f(None, ns)
+ else:
+ return f(ns)
+
def render(ob, ns):
"""
Calls the object, possibly a document template, or just returns it if
not callable. (From DT_Util.py)
"""
if hasattr(ob, '__render_with_namespace__'):
- ob = ob.__render_with_namespace__(ns)
+ ob = call_with_ns(ob.__render_with_namespace__, ns)
else:
base = aq_base(ob)
if callable(base):
try:
if getattr(base, 'isDocTemp', 0):
- ob = ob(aq_parent(ob), ns)
+ ob = call_with_ns(ob, ns, 2)
else:
ob = ob()
except AttributeError, n:
@@ -139,17 +162,22 @@
path_modifiers = {'if': 0, 'exists': 0, 'nocall':0}
class PathExpr:
- def __init__(self, name, expr):
+ _call_name = ''
+
+ def __init__(self, name, expr, engine):
self._s = expr
self._name = name
- self._path = path = split(expr, '/')
+ self._paths = map(self._prepPath, split(expr, '|'))
+
+ def _prepPath(self, path):
+ path = split(strip(path), '/')
front = path.pop(0)
fronts = split(replace(replace(front, '(', '( '), ')', ' ) '))
- self._base = base = fronts.pop()
+ base = fronts.pop()
if not _valid_name(base):
raise CompilerError, 'Invalid variable name "%s"' % base
# Parse path modifiers
- self.modifiers = modifiers = path_modifiers.copy()
+ modifiers = path_modifiers.copy()
if fronts:
if len(fronts) < 2 or (fronts.pop(0) != '(' or
fronts.pop() != ')'):
@@ -160,54 +188,20 @@
% modifier)
modifiers[modifier] = 1
# Parse path
- self._dynparts = dp = []
+ dp = []
for i in range(len(path)):
e = path[i]
if e[:1] == '?' and _valid_name(e[1:]):
dp.append((i, e[1:]))
dp.reverse()
- # Choose call method
- on = modifiers.get
- callname = on('if') + on('exists') * 2
- callname = ('Render', 'If', 'Exists', 'IfExists')[callname]
- if on('nocall') and callname == 'Render':
- callname = ''
- self._call_name = '_eval' + callname
-
- def _evalRender(self, econtext):
- return render(self._eval(econtext), econtext.contexts)
-
- def _evalIf(self, econtext):
- val = self._eval(econtext)
- if not val:
- return Undefined
- if self.modifiers.has_key('nocall'):
- return val
- return render(val, econtext.contexts)
+ return (base, path, dp), modifiers
- def _evalExists(self, econtext):
- try:
- self._eval(econtext)
- except (Undefined, 'Unauthorized'):
- return 0
- return 1
-
- def _evalIfExists(self, econtext):
- try:
- val = self._eval(econtext)
- except (Undefined, 'Unauthorized'):
- return Undefined
- if self.modifiers.has_key('nocall'):
- return val
- return render(val, econtext.contexts)
-
- def _eval(self, econtext):
- base = self._base
- path = list(self._path) # Copy!
+ def _eval(self, (base, path, dp), econtext):
+ path = list(path) # Copy!
contexts = econtext.contexts
var = contexts['var']
# Expand dynamic path parts from right to left.
- for i, varname in self._dynparts:
+ for i, varname in dp:
val = var[varname]
if type(val) is type(''):
path[i] = val
@@ -217,15 +211,42 @@
path[i:i+1] = list(val)
try:
__traceback_info__ = base
- has, ob = var.has_get(base)
- if not has:
- ob = contexts[base]
+ if base == 'CONTEXTS':
+ ob = contexts
+ else:
+ has, ob = var.has_get(base)
+ if not has:
+ ob = contexts[base]
return restrictedTraverse(ob, path)
- except (AttributeError, KeyError, TypeError, IndexError), e:
- raise Undefined, (self._s, sys.exc_info()), sys.exc_info()[2]
+ except (AttributeError, KeyError, TypeError, IndexError,
+ 'Unauthorized'), e:
+ return Undefined(self._s, sys.exc_info())
def __call__(self, econtext):
- return getattr(self, self._call_name)(econtext)
+ for pathinfo, modifiers in self._paths:
+ ob = self._eval(pathinfo, econtext)
+ mod = modifiers.get
+
+ if isinstance(ob, Undefined):
+ # This path is Undefined, so skip to the next.
+ if mod('exists'):
+ if mod('if'):
+ return Default
+ else:
+ return 0
+ continue
+ if mod('exists') and not mod('if'):
+ # This path is defined, and that's all we wanted to know.
+ return 1
+ if not mod('nocall'):
+ # Render the object, unless explicitly prevented.
+ ob = render(ob, econtext.contexts)
+ if mod('if') and not mod('exists') and not ob:
+ # Skip the object if it is false.
+ continue
+ return ob
+ # We ran out of paths to test, so return the last value.
+ return ob
def __str__(self):
return '%s expression "%s"' % (self._name, self._s)
@@ -237,7 +258,7 @@
_interp = re.compile(r'\$(%(n)s)|\${(%(n)s(?:/%(n)s)*)}' % {'n': NAME_RE})
class StringExpr:
- def __init__(self, name, expr):
+ def __init__(self, name, expr, engine):
self._s = expr
if '%' in expr:
expr = replace(expr, '%', '%%')
@@ -250,7 +271,8 @@
while m is not None:
parts.append(exp[:m.start()])
parts.append('%s')
- vars.append(PathExpr('path', m.group(1) or m.group(2)))
+ vars.append(PathExpr('path', m.group(1) or m.group(2),
+ engine))
exp = exp[m.end():]
m = _interp.search(exp)
if '$' in exp:
@@ -285,14 +307,24 @@
return '<NotExpr %s>' % `self._s`
+class ExprTypeProxy:
+ '''Class that proxies access to an expression type handler'''
+ def __init__(self, name, handler, econtext):
+ self._name = name
+ self._handler = handler
+ self._econtext = econtext
+ def __call__(self, text):
+ return self._handler(self._name, text,
+ self._econtext._engine)(self._econtext)
+
if sys.modules.has_key('Zope'):
from AccessControl import getSecurityManager
from Products.PythonScripts.Guarded import _marker, \
GuardedBlock, theGuard, safebin, WriteGuard, ReadGuard, UntupleFunction
class PythonExpr:
- def __init__(self, name, expr):
- self.expr = expr = strip(expr)
+ def __init__(self, name, expr, engine):
+ self.expr = expr = replace(strip(expr), '\n', ' ')
blk = GuardedBlock('def f():\n return %s\n' % expr)
if blk.errors:
raise CompilerError, ('Python expression error:\n%s' %
@@ -310,8 +342,13 @@
# Bind template variables
var = econtext.contexts['var']
+ getType = econtext._engine.getTypes().get
for vname in self._f_varnames:
has, val = var.has_get(vname)
+ if not has:
+ has = val = getType(vname)
+ if has:
+ val = ExprTypeProxy(vname, val, econtext)
if has:
f.func_globals[vname] = val
@@ -339,7 +376,8 @@
_marker = []
class PythonExpr:
- def __init__(self, name, expr):
+ def __init__(self, name, expr, engine):
+ self.expr = expr = replace(strip(expr), '\n', ' ')
try:
d = {}
exec 'def f():\n return %s\n' % strip(expr) in d
@@ -362,12 +400,15 @@
if has:
f.func_globals[vname] = val
- # Execute the function in a new security context.
- template = econtext.contexts['template']
return f()
+
+ def __str__(self):
+ return 'Python expression "%s"' % self.expr
+ def __repr__(self):
+ return '<PythonExpr %s>' % self.expr
class ImportExpr:
- def __init__(self, name, expr):
+ def __init__(self, name, expr, engine):
self._s = expr
def __call__(self, econtext):
return safebin['__import__'](self._s)
--- Updated File PageTemplate.py in package Packages/Products/PageTemplates --
--- PageTemplate.py 2001/04/27 18:32:45 1.9
+++ PageTemplate.py 2001/05/11 23:44:51 1.10
@@ -142,7 +142,7 @@
def pt_render(self, source=0, extra_context={}):
"""Render this Page Template"""
if self._v_errors:
- return self.pt_diagnostic()
+ raise RuntimeError, 'Page Template %s has errors.' % self.id
output = StringIO()
c = self.pt_getContext()
c.update(extra_context)
@@ -163,12 +163,6 @@
def pt_errors(self):
return self._v_errors
- def pt_diagnostic(self):
- return ('<html><body>\n'
- '<h4>Page Template Diagnostics</h4>\n'
- '<pre> %s\n</pre>'
- '</body></html>\n') % join(self._v_errors, ' \n')
-
def write(self, text):
assert type(text) is type('')
if text[:len(self._error_start)] == self._error_start:
--- Updated File TALES.py in package Packages/Products/PageTemplates --
--- TALES.py 2001/05/08 01:51:43 1.9
+++ TALES.py 2001/05/11 23:44:51 1.10
@@ -106,6 +106,8 @@
return '%s on %s in "%s"' % (self.type, self.value,
self.expression)
return self.expression
+ def __nonzero__(self):
+ return 0
class Undefined(TALESError):
'''Exception raised on traversal of an undefined path'''
@@ -120,9 +122,23 @@
class CompilerError(Exception):
'''TALES Compiler Error'''
+
+class Default:
+ '''Retain Default'''
+ def __nonzero__(self):
+ return 0
+Default = Default()
+
+_marker = []
-class SecureMultiMap:
- '''MultiMapping wrapper with security declarations'''
+class SafeMapping(MultiMapping):
+ '''Mapping with security declarations and limited method exposure.
+
+ Since it subclasses MultiMapping, this class can be used to wrap
+ one or more mapping objects. Restricted Python code will not be
+ able to mutate the SafeMapping or the wrapped mappings, but will be
+ able to read any value.
+ '''
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, *dicts):
self._mm = apply(MultiMapping, dicts)
@@ -196,10 +212,7 @@
except KeyError:
raise CompilerError, (
'Unrecognized expression type "%s".' % type)
- try:
- return handler(type, expr, self)
- except TypeError:
- return handler(type, expr)
+ return handler(type, expr, self)
def getContext(self, contexts=None, **kwcontexts):
if contexts is not None:
@@ -220,21 +233,23 @@
def __init__(self, engine, contexts):
self._engine = engine
self.contexts = contexts
+ contexts['nothing'] = None
+ contexts['default'] = Default
# Keep track of what contexts get pushed as each scope begins.
self._ctxts_pushed = []
# These contexts will need to be pushed.
self._current_ctxts = {'local': 1, 'repeat': 1}
- contexts['local'] = lv = SecureMultiMap()
+ lv = self._context_class()
init_local = contexts.get('local', None)
if init_local:
lv._push(init_local)
- contexts['repeat'] = rep = SecureMultiMap()
+ contexts['local'] = lv
+ contexts['repeat'] = rep = self._context_class()
contexts['loop'] = rep # alias
contexts['global'] = gv = contexts.copy()
- gv['standard'] = contexts
- contexts['var'] = SecureMultiMap(gv, lv)
+ contexts['var'] = self._context_class(gv, lv)
def beginScope(self):
oldctxts = self._current_ctxts
@@ -254,20 +269,14 @@
ctx.clear()
def setLocal(self, name, value):
- if value is not Undefined:
- self._current_ctxts['local'][name] = value
+ self._current_ctxts['local'][name] = value
def setGlobal(self, name, value):
- if value is not Undefined:
- self.contexts['global'][name] = value
+ self.contexts['global'][name] = value
def setRepeat(self, name, expr):
expr = self.evaluate(expr)
- if expr is Undefined:
- # Not sure of this
- it = self._engine.Iterator(name, [Undefined], self)
- else:
- it = self._engine.Iterator(name, expr, self)
+ it = self._engine.Iterator(name, expr, self)
self._current_ctxts['repeat'][name] = it
return it
@@ -275,7 +284,10 @@
if type(expression) is type(''):
expression = self._engine.compile(expression)
try:
- return expression(self)
+ v = expression(self)
+ if isinstance(v, Exception):
+ raise v
+ return v
except TALESError:
raise
except:
@@ -285,13 +297,11 @@
def evaluateBoolean(self, expr):
bool = self.evaluate(expr)
- if bool is Undefined:
- return bool
return not not bool
def evaluateText(self, expr):
text = self.evaluate(expr)
- if text not in (None, Undefined):
+ if text not in (None, Default):
text = str(text)
return text
@@ -305,12 +315,12 @@
def getTALESError(self):
return TALESError
- def getCancelAction(self):
- return Undefined
+ def getDefault(self):
+ return Default
class SimpleExpr:
'''Simple example of an expression type handler'''
- def __init__(self, name, expr):
+ def __init__(self, name, expr, engine):
self._name = name
self._expr = expr
def __call__(self, econtext):
--- Updated File ZopePageTemplate.py in package Packages/Products/PageTemplates --
--- ZopePageTemplate.py 2001/04/27 18:32:45 1.7
+++ ZopePageTemplate.py 2001/05/11 23:44:51 1.8
@@ -149,11 +149,6 @@
'ZScriptHTML_tryForm', 'PrincipiaSearchSource',
'document_src')
- pt_editForm = DTMLFile('dtml/ptEdit', globals())
- manage = manage_main = pt_editForm
-
- pt_diagnostic = DTMLFile('dtml/ptDiagnostic', globals())
-
security.declareProtected('Change Page Templates',
'pt_editAction', 'pt_setTitle', 'pt_edit',
'pt_upload', 'pt_changePrefs')
@@ -168,7 +163,7 @@
if getattr(self, '_v_warnings', None):
message = ("<strong>Warning:</strong> <i>%s</i>"
% join(self._v_warnings, '<br>'))
- return self.pt_editForm(self, REQUEST, manage_tabs_message=message)
+ return self.pt_editForm(manage_tabs_message=message)
def pt_setTitle(self, title):
title = str(title)
@@ -183,7 +178,7 @@
if type(file) is not type(''): file = file.read()
self.write(file)
message = 'Saved changes.'
- return self.pt_editForm(self, REQUEST, manage_tabs_message=message)
+ return self.pt_editForm(manage_tabs_message=message)
def pt_changePrefs(self, REQUEST, height=None, width=None,
dtpref_cols='50', dtpref_rows='20'):
@@ -199,7 +194,7 @@
setc('dtpref_rows', str(rows), path='/', expires=e)
setc('dtpref_cols', str(cols), path='/', expires=e)
REQUEST.form.update({'dtpref_cols': cols, 'dtpref_rows': rows})
- return apply(self.manage_main, (self, REQUEST), REQUEST.form)
+ return self.manage_main()
def ZScriptHTML_tryParams(self):
"""Parameters to test the script with."""
@@ -341,9 +336,15 @@
REQUEST.RESPONSE.redirect(u+'/manage_main')
return ''
-manage_addPageTemplateForm = DTMLFile('dtml/ptAdd', globals())
+#manage_addPageTemplateForm = DTMLFile('dtml/ptAdd', globals())
def initialize(context):
+ from PageTemplateFile import PageTemplateFile
+ manage_addPageTemplateForm = PageTemplateFile('www/ptAdd', globals())
+ _editForm = PageTemplateFile('www/ptEdit', globals())
+ ZopePageTemplate.manage = _editForm
+ ZopePageTemplate.manage_main = _editForm
+ ZopePageTemplate.pt_editForm = _editForm
context.registerClass(
ZopePageTemplate,
permission='Add Page Templates',
@@ -353,3 +354,4 @@
)
context.registerHelp()
context.registerHelpTitle('Zope Help')
+