[ZPT] CVS: Zope/lib/python/Products/PageTemplates - GlobalTranslationService.py:1.2.2.1 Expressions.py:1.36.4.2 PythonExpr.py:1.8.4.1 TALES.py:1.31.4.1 ZopePageTemplate.py:1.42.4.4

Chris McDonough chrism@zope.com
Sat, 28 Sep 2002 21:41:04 -0400


Update of /cvs-repository/Zope/lib/python/Products/PageTemplates
In directory cvs.zope.org:/tmp/cvs-serv16902/lib/python/Products/PageTemplates

Modified Files:
      Tag: chrism-install-branch
	Expressions.py PythonExpr.py TALES.py ZopePageTemplate.py 
Added Files:
      Tag: chrism-install-branch
	GlobalTranslationService.py 
Log Message:
Merge chrism-install-branch with head.  Apologies for the spew.


=== Added File Zope/lib/python/Products/PageTemplates/GlobalTranslationService.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Global Translation Service for providing I18n to Page Templates.

$Id: GlobalTranslationService.py,v 1.2.2.1 2002/09/29 01:40:32 chrism Exp $
"""

class DummyTranslationService:
    """Translation service that does nothing and returns the message id."""
    def translate(self, domain, msgid, mapping=None,
                  context=None, target_language=None):
        return msgid
    # XXX Not all of Zope.I18n.ITranslationService is implemented.

translationService = DummyTranslationService()

def setGlobalTranslationService(service):
    """Sets the global translation service, and returns the previous one."""
    global translationService
    old_service = translationService
    translationService = service
    return old_service

def getGlobalTranslationService():
    """Returns the global translation service."""
    return translationService


=== Zope/lib/python/Products/PageTemplates/Expressions.py 1.36.4.1 => 1.36.4.2 ===
--- Zope/lib/python/Products/PageTemplates/Expressions.py:1.36.4.1	Mon Sep 16 02:00:51 2002
+++ Zope/lib/python/Products/PageTemplates/Expressions.py	Sat Sep 28 21:40:32 2002
@@ -46,7 +46,10 @@
 
 if sys.modules.has_key('Zope'):
     import AccessControl
+    import AccessControl.cAccessControl
+    acquisition_security_filter = AccessControl.cAccessControl.aq_validate
     from AccessControl import getSecurityManager
+    from AccessControl.ZopeGuards import guarded_getattr
     try:
         from AccessControl import Unauthorized
     except ImportError:
@@ -59,10 +62,17 @@
              call_with_ns
 else:
     from PythonExpr import getSecurityManager, PythonExpr
+    guarded_getattr = getattr
     try:
         from zExceptions import Unauthorized
     except ImportError:
         Unauthorized = "Unauthorized"
+
+    def acquisition_security_filter(orig, inst, name, v, real_validate):
+        if real_validate(orig, inst, name, v):
+            return 1
+        raise Unauthorized, name
+
     def call_with_ns(f, ns, arg=1):
         if arg==2:
             return f(None, ns)
@@ -144,6 +154,7 @@
     def __init__(self, name, expr, engine):
         self._s = expr
         self._name = name
+        self._hybrid = 0
         paths = expr.split('|')
         self._subexprs = []
         add = self._subexprs.append
@@ -153,6 +164,7 @@
                 # This part is the start of another expression type,
                 # so glue it back together and compile it.
                 add(engine.compile(('|'.join(paths[i:]).lstrip())))
+                self._hybrid = 1
                 break
             add(SubPathExpr(path)._eval)
 
@@ -177,8 +189,11 @@
             else:
                 break
         else:
-            # On the last subexpression allow exceptions through.
+            # On the last subexpression allow exceptions through, and
+            # don't autocall if the expression was not a subpath.
             ob = self._subexprs[-1](econtext)
+            if self._hybrid:
+                return ob
 
         if self._name == 'nocall' or isinstance(ob, StringType):
             return ob
@@ -246,7 +261,10 @@
         self._c = compiler.compile(expr)
 
     def __call__(self, econtext):
-        return not econtext.evaluateBoolean(self._c)
+        # We use the (not x) and 1 or 0 formulation to avoid changing
+        # the representation of the result in Python 2.3, where the
+        # result of "not" becomes an instance of bool.
+        return (not econtext.evaluateBoolean(self._c)) and 1 or 0
 
     def __repr__(self):
         return 'not:%s' % `self._s`
@@ -274,33 +292,30 @@
         return 'defer:%s' % `self._s`
 
 
-def restrictedTraverse(self, path, securityManager,
+def restrictedTraverse(object, path, securityManager,
                        get=getattr, has=hasattr, N=None, M=[],
                        TupleType=type(()) ):
 
     REQUEST = {'path': path}
     REQUEST['TraversalRequestNameStack'] = path = path[:] # Copy!
-    if not path[0]:
-        # If the path starts with an empty string, go to the root first.
-        self = self.getPhysicalRoot()
-        if not securityManager.validateValue(self):
-            raise Unauthorized, name
-        path.pop(0)
-
     path.reverse()
     validate = securityManager.validate
-    object = self
+    __traceback_info__ = REQUEST
     while path:
-        __traceback_info__ = REQUEST
         name = path.pop()
 
         if isinstance(name, TupleType):
-            object = apply(object, name)
+            object = object(*name)
             continue
 
-        if name[0] == '_':
-            # Never allowed in a URL.
-            raise AttributeError, name
+        if not name or name[0] == '_':
+            # Skip directly to item access
+            o = object[name]
+            # Check access to the item.
+            if not validate(object, object, name, o):
+                raise Unauthorized, name
+            object = o
+            continue
 
         if name=='..':
             o = get(object, 'aq_parent', M)
@@ -321,23 +336,14 @@
                 container = aq_parent(aq_inner(o))
             elif has(o, 'im_self'):
                 container = o.im_self
-            elif (has(get(object, 'aq_base', object), name)
-                and get(object, name) == o):
+            elif (has(aq_base(object), name) and get(object, name) == o):
                 container = object
             if not validate(object, container, name, o):
                 raise Unauthorized, name
         else:
             # Try an attribute.
-            o = get(object, name, M)
-            if o is not M:
-                # Check access to the attribute.
-                if has(object, 'aq_acquire'):
-                    object.aq_acquire(
-                        name, validate2, validate)
-                else:
-                    if not validate(object, object, name, o):
-                        raise Unauthorized, name
-            else:
+            o = guarded_getattr(object, name, M)
+            if o is M:
                 # Try an item.
                 try:
                     # XXX maybe in Python 2.2 we can just check whether
@@ -350,14 +356,14 @@
                         # Try to re-raise the original attribute error.
                         # XXX I think this only happens with
                         # ExtensionClass instances.
-                        get(object, name)
+                        guarded_getattr(object, name)
                     raise
                 except TypeError, exc:
                     if str(exc).find('unsubscriptable') >= 0:
                         # The object does not support the item interface.
                         # Try to re-raise the original attribute error.
                         # XXX This is sooooo ugly.
-                        get(object, name)
+                        guarded_getattr(object, name)
                     raise
                 else:
                     # Check access to the item.
@@ -366,9 +372,3 @@
         object = o
 
     return object
-
-
-def validate2(orig, inst, name, v, real_validate):
-    if not real_validate(orig, inst, name, v):
-        raise Unauthorized, name
-    return 1


=== Zope/lib/python/Products/PageTemplates/PythonExpr.py 1.8 => 1.8.4.1 ===
--- Zope/lib/python/Products/PageTemplates/PythonExpr.py:1.8	Wed Aug 14 18:17:24 2002
+++ Zope/lib/python/Products/PageTemplates/PythonExpr.py	Sat Sep 28 21:40:32 2002
@@ -43,18 +43,19 @@
             if vname[0] not in '$_':
                 vnames.append(vname)
 
-    def _bind_used_names(self, econtext):
+    def _bind_used_names(self, econtext, _marker=[]):
         # Bind template variables
         names = {}
         vars = econtext.vars
         getType = econtext._engine.getTypes().get
         for vname in self._f_varnames:
-            has, val = vars.has_get(vname)
-            if not has:
+            val = vars.get(vname, _marker)
+            if val is _marker:
                 has = val = getType(vname)
                 if has:
                     val = ExprTypeProxy(vname, val, econtext)
-            if has:
+                    names[vname] = val
+            else:
                 names[vname] = val
         return names
 
@@ -78,3 +79,4 @@
     def __call__(self, text):
         return self._handler(self._name, text,
                              self._econtext._engine)(self._econtext)
+


=== Zope/lib/python/Products/PageTemplates/TALES.py 1.31 => 1.31.4.1 ===
--- Zope/lib/python/Products/PageTemplates/TALES.py:1.31	Wed Aug 14 18:17:24 2002
+++ Zope/lib/python/Products/PageTemplates/TALES.py	Sat Sep 28 21:40:32 2002
@@ -19,6 +19,8 @@
 
 import re, sys, ZTUtils
 from MultiMapping import MultiMapping
+from DocumentTemplate.DT_Util import ustr
+from GlobalTranslationService import getGlobalTranslationService
 
 StringType = type('')
 
@@ -42,8 +44,6 @@
     '''Retain Default'''
 Default = Default()
 
-_marker = []
-
 class SafeMapping(MultiMapping):
     '''Mapping with security declarations and limited method exposure.
 
@@ -58,9 +58,6 @@
     _push = MultiMapping.push
     _pop = MultiMapping.pop
 
-    def has_get(self, key, _marker=[]):
-        v = self.get(key, _marker)
-        return v is not _marker, v
 
 class Iterator(ZTUtils.Iterator):
     def __init__(self, name, seq, context):
@@ -214,19 +211,16 @@
             expression = self._engine.compile(expression)
         __traceback_supplement__ = (
             TALESTracebackSupplement, self, expression)
-        v = expression(self)
-        return v
+        return expression(self)
 
     evaluateValue = evaluate
+    evaluateBoolean = evaluate
 
-    def evaluateBoolean(self, expr):
-        return not not self.evaluate(expr)
-
-    def evaluateText(self, expr, None=None):
+    def evaluateText(self, expr):
         text = self.evaluate(expr)
         if text is Default or text is None:
             return text
-        return str(text)
+        return ustr(text)
 
     def evaluateStructure(self, expr):
         return self.evaluate(expr)
@@ -249,7 +243,13 @@
     def setPosition(self, position):
         self.position = position
 
-
+    def translate(self, domain, msgid, mapping=None,
+                  context=None, target_language=None):
+        if context is None:
+            context = self.contexts.get('here')
+        return getGlobalTranslationService().translate(
+            domain, msgid, mapping=mapping,
+            context=context, target_language=target_language)
 
 class TALESTracebackSupplement:
     """Implementation of ITracebackSupplement"""
@@ -269,8 +269,6 @@
         else:
             from cgi import escape
             return '<b>Names:</b><pre>%s</pre>' % (escape(s))
-        return None
-
 
 
 class SimpleExpr:


=== Zope/lib/python/Products/PageTemplates/ZopePageTemplate.py 1.42.4.3 => 1.42.4.4 ===
--- Zope/lib/python/Products/PageTemplates/ZopePageTemplate.py:1.42.4.3	Mon Sep 16 02:00:51 2002
+++ Zope/lib/python/Products/PageTemplates/ZopePageTemplate.py	Sat Sep 28 21:40:32 2002
@@ -369,3 +369,4 @@
         )
     context.registerHelp()
     context.registerHelpTitle('Zope Help')
+