def testSlotExprCompilerError(self): # Bad slot expressions should produce a reasonable error. text = '<div tal:content="structure slot: a b" />' try: t = ZopePageTemplate( id="template", text=text, content_type="text/html") except TALError, e: msg = str(e)
def test_template_translation(self): tmpl = ZopePageTemplate(id='test_tmpl') tmpl.pt_edit('<p i18n:translate="">Home for' ' <span i18n:name="hours">3</span> hours</p>', 'text/html') self.assertEqual(tmpl.__of__(self.portal)(), u'<p>Home for <span>3</span> hours</p>\n')
def test_use_as_macro(self): use_macro = ZopePageTemplate(id='use_macro').__of__(self.portal) use_macro.pt_edit(use_macro_zpt, 'text/html') self.assertEqual( use_macro(), '\n<div class="left_portlet">\n' '\t<div class="left_portlet_title">new title</div>\n' '\t<div class="left_portlet_content">PORTLET CONTENT</div>\n' '</div>\n')
def test_cook_zope2_page_templates_good_str(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', GOOD_STR) hack_pt(pt) self.assertEqual(pt.pt_render().strip(), '<p>none</p>') hack_pt(pt, context=self.portal) self.assertEqual(pt.pt_render().strip(), '<p><plonesite at plone></p>')
def test_cook_zope2_page_templates_good_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', unicode(GOOD_UNICODE)) hack_pt(pt) self.assertEqual(pt.pt_render().strip(), '<p>none</p>') hack_pt(pt, self.portal) self.assertEqual(pt.pt_render().strip(), '<p><plonesite at plone></p>')
def manage_afterAdd(self, item, container): """ Setup tasks upon instantiation """ if not 'login_form' in self.objectIds(): login_form = ZopePageTemplate(id='login_form', text=BASIC_LOGIN_FORM) login_form.title = 'Login Form' login_form.manage_permission(view, roles=['Anonymous'], acquire=1) self._setObject('login_form', login_form, set_owner=0)
def test_cook_zope2_page_templates_good_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', GOOD_UNICODE) hack_pt(pt) self.assertEqual(pt.pt_render().strip(), '<p>none</p>') hack_pt(pt, self.app) self.assertEqual( pt.pt_render().strip(), '<p><application at ></p>')
def test_no_mappings(self): provideUtility(Registry(), IRegistry) registry = getUtility(IRegistry) registry.registerInterface(IPloneCacheSettings) published = ZopePageTemplate('someView') request = DummyRequest(published, DummyResponse()) self.assertEqual(None, ContentItemLookup(published, request)())
def __init__(self, id, title, body, portlettype, lang): #constructor self.id = id self._setLocalPropValue('title', lang, title) self._setLocalPropValue('body', lang, body) self.portlettype = portlettype self.template = ZopePageTemplate('', HTML_PORTLET_TEMPLATE, 'text/html')
def test_bug_198274(self): # See https://bugs.launchpad.net/bugs/198274 # ZPT w/ '_text' not assigned can't be unpickled. import pickle empty = ZopePageTemplate(id='empty', text=' ', content_type='text/html', output_encoding='ascii') state = pickle.dumps(empty, protocol=1) pickle.loads(state)
def get_template(self, tile_id): tiles_directory = self.get_tile_directory() tile_folder = tiles_directory[tile_id] fi = tile_folder['template.html'] if fi.__class__.__name__ == "FilesystemFile": data = IRawReadFile(fi).read() else: data = str(fi.data) return ZopePageTemplate(tile_id, text=data)
def test_cook_zope2_page_templates_bad_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_UNICODE) hack_pt(pt) with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual( "You are not allowed to access '__class__' in this context", str(err.exception))
def test_cook_zope2_page_templates_aq_parent(self): # Accessing aq_parent should be allowed normally. from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', AQ_TEST) hack_pt(pt, context=self.portal) self.assertEqual( pt.pt_render().strip(), u'<p>parent of <PloneSite at plone> is ' u'<Application at ></p>')
def body_compile(self): if not self.body: return '' pt = ZopePageTemplate(id='__adv_page_tal_body__') pt.pt_edit(self.body, 'text/html') context = aq_inner(self) pt = aq_base(pt).__of__(context) # request is taken by acquisition return pt()
def install_root_view(self): app = self.getApp() if 'index_html' not in app: from Products.PageTemplates.ZopePageTemplate \ import ZopePageTemplate root_pt = ZopePageTemplate('index_html') root_pt.pt_setTitle('Auto-generated default page') app._setObject('index_html', root_pt) self.commit('Added default view for root object')
def setUp(self): import Products.GenericSetup.PageTemplates from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate BodyAdapterTestCase.setUp(self) zcml.load_config('configure.zcml', Products.GenericSetup.PageTemplates) self._obj = ZopePageTemplate('foo_template') self._BODY = _PAGETEMPLATE_BODY
def setUp(self): f = Folder() f.getPhysicalPath = lambda: () f.getPhysicalRoot = lambda f=f: f f.composite = Composite() f.composite._setId("composite") t = ZopePageTemplate( id="template", text=template_text, content_type="text/html") if t.pt_errors(): raise SyntaxError(t.pt_errors()) f.composite.template = t f.composite.filled_slots.slot_a = slot_a = Slot("slot_a") a1 = ZopePageTemplate(id="a1", text="<b>Slot A</b>") f._setObject(a1.id, a1) e1 = CompositeElement('e1', f.a1) slot_a._setObject(e1.id, e1) self.composite = f.composite self.old_policy = setSecurityPolicy(PermissiveSecurityPolicy()) noSecurityManager()
def test_cook_zope2_page_templates_bad_key_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_KEY_UNICODE) hack_pt(pt, self.portal) create_private_document(self.portal, 'secret') login(self.portal, TEST_USER_NAME) self.assertEqual(pt.pt_render().replace('ATDocument', 'Document'), '<p>access by key: <Document at secret></p>') logout() self.assertRaises(Unauthorized, pt.pt_render)
def testSlotExprCompilerError(self): # Bad slot expressions should produce a reasonable error. from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from zope.tal.taldefs import TALError text = '<div tal:content="structure slot: a b" />' try: t = ZopePageTemplate(id="template", text=text, content_type="text/html") except TALError, e: msg = unicode(e)
def test_template_lookup(self): provideUtility(Registry(), IRegistry) registry = getUtility(IRegistry) registry.registerInterface(IPloneCacheSettings) ploneSettings = registry.forInterface(IPloneCacheSettings) ploneSettings.templateRulesetMapping = {'someView': 'rule1'} published = ZopePageTemplate('someView') request = DummyRequest(published, DummyResponse()) self.assertEqual('rule1', ContentItemLookup(published, request)())
def _default_PUT_factory(self, name, typ, body): # Return DTMLDoc/PageTemplate/Image/File, based on sniffing. if name and name.endswith('.pt'): ob = ZopePageTemplate(name, body, content_type=typ) elif typ in ('text/html', 'text/xml', 'text/plain'): ob = DTMLDocument('', __name__=name) elif typ[:6] == 'image/': ob = Image(name, '', body, content_type=typ) else: ob = File(name, '', body, content_type=typ) return ob
def test_cook_zope2_page_templates_bad_item_str(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate secret = create_private_document(self.portal, 'secret') login(self.portal, TEST_USER_NAME) self.portal.testlist = [secret] pt = ZopePageTemplate('mytemplate', BAD_ITEM_STR) hack_pt(pt, self.portal.testlist) self.assertEqual(pt.pt_render().replace('ATDocument', 'Document'), '<p>access by item: <Document at secret></p>') logout() self.assertRaises(Unauthorized, pt.pt_render)
def test_parent_not_content(self): provideUtility(Registry(), IRegistry) registry = getUtility(IRegistry) registry.registerInterface(IPloneCacheSettings) ploneSettings = registry.forInterface(IPloneCacheSettings) ploneSettings.templateRulesetMapping = {} ploneSettings.contentTypeRulesetMapping = {'testtype': 'rule1'} published = ZopePageTemplate('defaultView').__of__(DummyNotContent()) request = DummyRequest(published, DummyResponse()) self.assertEqual(None, ContentItemLookup(published, request)())
def test_access_to_private_content_not_allowed_via_any_attribute(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate # If access to _delObject would be allowed, it would still only say # something like 'bound method _delObject', without actually deleting # anything, because methods are not executed in str.format, but there # may be @properties that give an attacker secret info. pt = ZopePageTemplate( 'mytemplate', ''' <p tal:content="structure python:'access {0._delObject}'.format(context)" /> ''') hack_pt(pt, context=self.app) self.assertRaises(Unauthorized, pt.pt_render)
def _createZODBClone(self): """ Create a ZODB (editable) equivalent of this object. """ if _STX_TEMPLATE == 'DTML': target = DTMLDocument(_CUSTOMIZED_TEMPLATE_DTML, __name__=self.getId()) elif _STX_TEMPLATE == 'ZPT': target = ZopePageTemplate(self.getId(), _CUSTOMIZED_TEMPLATE_ZPT) target._setProperty('stx', self.raw, 'text') return target
def get_mail_body(self, unsorted_data, request, context): """Returns the mail-body with footer. """ schema = get_schema(context) form = DummyFormView(context, request) form.schema = schema form.prefix = 'form' form._update() widgets = {name: widget.render() for name, widget in form.w.items()} data = filter_fields(self, schema, unsorted_data) bodyfield = self.body_pt # pass both the bare_fields (fgFields only) and full fields. # bare_fields for compatability with older templates, # full fields to enable access to htmlValue if isinstance(self.body_pre, basestring): body_pre = self.body_pre else: body_pre = self.body_pre.output if isinstance(self.body_post, basestring): body_post = self.body_post else: body_post = self.body_post.output if isinstance(self.body_footer, basestring): body_footer = self.body_footer else: body_footer = self.body_footer.output extra = { 'data': data, 'fields': OrderedDict([(i, j.title) for i, j in getFieldsInOrder(schema)]), 'widgets': widgets, 'mailer': self, 'body_pre': body_pre and lnbr(dollar_replacer(body_pre, data)), 'body_post': body_post and lnbr(dollar_replacer(body_post, data)), 'body_footer': body_footer and lnbr(dollar_replacer(body_footer, data)), } template = ZopePageTemplate(self.__name__) template.write(bodyfield) template = template.__of__(context) return template.pt_render(extra_context=extra)
def _make_composite(self): from OFS.Folder import Folder from ZPublisher.HTTPRequest import HTTPRequest from ZPublisher.HTTPRequest import HTTPResponse from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from Products.CompositePage.composite import Composite from Products.CompositePage.element import CompositeElement from Products.CompositePage.slot import Slot TEMPLATE_TEXT = '\n'.join(( '<html>', '<body>', """<div tal:replace="structure slot: slot_a (top) """ """'Top News Stories'">slot_a</div>""", """<span tal:replace="structure slot: slot_b """ """'Other News'">slot_b</span>""", '<div tal:replace="structure context/slots/slot_c">slot_c</div>', '</body>', '</html>', )) f = Folder() f.getPhysicalPath = lambda: () f.getPhysicalRoot = lambda f=f: f req = f.REQUEST = HTTPRequest('', dict(HTTP_HOST='localhost:8080'), {}) req.response = HTTPResponse() f.composite = Composite() f.composite._setId("composite") t = ZopePageTemplate(id="template", text=TEMPLATE_TEXT, content_type="text/html") f.composite.template = t f.composite.filled_slots.slot_a = slot_a = Slot("slot_a") t = f.composite.template if t.pt_errors(): raise SyntaxError(t.pt_errors()) a1 = ZopePageTemplate(id="a1", text="<b>Slot A</b>") f._setObject(a1.id, a1) e1 = CompositeElement('e1', f.a1) slot_a._setObject(e1.id, e1) return f.composite
def get_mail_body(self, unsorted_data, request, context): """Returns the mail-body with footer. """ schema = get_schema(context) form = DummyFormView(context, request) form.schema = schema form.prefix = "form" form._update() widgets = filter_widgets(self, form.w) data = filter_fields(self, schema, unsorted_data) bodyfield = self.body_pt # pass both the bare_fields (fgFields only) and full fields. # bare_fields for compatability with older templates, # full fields to enable access to htmlValue if isinstance(self.body_pre, six.string_types): body_pre = self.body_pre else: body_pre = self.body_pre.output if isinstance(self.body_post, six.string_types): body_post = self.body_post else: body_post = self.body_post.output if isinstance(self.body_footer, six.string_types): body_footer = self.body_footer else: body_footer = self.body_footer.output extra = { "data": data, "fields": OrderedDict([(i, j.title) for i, j in getFieldsInOrder(schema)]), "widgets": widgets, "mailer": self, "body_pre": body_pre and lnbr(dollar_replacer(body_pre, data)), "body_post": body_post and lnbr(dollar_replacer(body_post, data)), "body_footer": body_footer and lnbr(dollar_replacer(body_footer, data)), } template = ZopePageTemplate(self.__name__) template.write(bodyfield) template = template.__of__(context) return template.pt_render(extra_context=extra)
def _setWhichTemplate(self, which): import Products.CMFCore.FSSTXMethod from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate Products.CMFCore.FSSTXMethod._STX_TEMPLATE = which if which == 'DTML': self.app.standard_html_header = ( lambda *args, **kw: '<html>\n<body>\n') self.app.standard_html_footer = ( lambda *args, **kw: '</body>\n</html>\n') elif which == 'ZPT': main = ZopePageTemplate('main_template', _TEST_MAIN_TEMPLATE) self.app._setOb('main_template', main)
def assert_is_checked_via_security_manager(self, pt_content): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from AccessControl.SecurityManager import setSecurityPolicy from AccessControl.SecurityManagement import noSecurityManager pt = ZopePageTemplate('mytemplate', pt_content) noSecurityManager() old_security_policy = setSecurityPolicy(UnauthorizedSecurityPolicy()) try: hack_pt(pt, context=self.portal) self.assertRaises(Unauthorized, pt.pt_render) finally: setSecurityPolicy(old_security_policy)