def manage_afterAdd(self, item, container): """ Setup tasks upon instantiation """ if not 'lockout' in self.objectIds(): lockout = ZopePageTemplate(id='lockout', text=BASIC_LOCKOUT) lockout.title = 'User Lockout' lockout.manage_permission(view, roles=['Anonymous'], acquire=1) self._setObject('lockout', lockout, set_owner=0)
def get_mail_body(self, fields, request, context): """Returns the mail-body with footer. """ schema = get_fields(context) all_fields = [f for f in fields # TODO # if not (f.isLabel() or f.isFileField()) and not (getattr(self, # 'showAll', True) and f.getServerSide())] if not (INamedFile.providedBy(fields[f])) and not (getattr(self, 'showAll', True) and IFieldExtender(schema[f]).serverSide) ] # which fields should we show? if getattr(self, 'showAll', True): live_fields = all_fields else: live_fields = [ f for f in all_fields if f in getattr(self, 'showFields', ())] if not getattr(self, 'includeEmpties', True): all_fields = live_fields live_fields = [f for f in all_fields if fields[f]] for f in all_fields: value = fields[f] if value: live_fields.append(f) #bare_fields = [schema[f] for f in live_fields] bare_fields = dict([(f, fields[f]) for f in live_fields]) 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 replacer = DollarVarReplacer(fields).sub extra = { 'data': bare_fields, 'fields': dict([(i, j.title) for i, j in getFieldsInOrder(schema)]), 'mailer': self, 'body_pre': self.body_pre and replacer(self.body_pre), 'body_post': self.body_post and replacer(self.body_post), 'body_footer': self.body_footer and replacer(self.body_footer), } template = ZopePageTemplate(self.__name__) template.write(bodyfield) template = template.__of__(context) body = template.pt_render(extra_context=extra) # if isinstance(body, unicode): #body = body.encode("utf-8") #keyid = getattr(self, 'gpg_keyid', None) #encryption = gpg and keyid # if encryption: #bodygpg = gpg.encrypt(body, keyid) # if bodygpg.strip(): #body = bodygpg return body
def __init__(self, id, filepath, fullname, properties): """ Initialise a new instance of XMLTemplate. """ FSObject.__init__(self, id, filepath, fullname, properties) self.ZBindings_edit(self._default_bindings) self.__name__ = id self.title = id self.id = id self._setPropValue('content_type', 'text/xml') self.setup_transformProperties() self.setup_schemaProperties() try: fp = expandpath(self._filepath+'.propsheet') prop_map = parsePropertiesFile(fp, 1) for propdict in prop_map: setattr(self, propdict['id'], propdict['default_value']) self._properties = prop_map except: raise ZopePageTemplate.__init__(self, id)
def _make_composite(self): from OFS.Folder import Folder f = Folder() f.getPhysicalPath = lambda: () f.getPhysicalRoot = lambda f=f: f from ZPublisher.HTTPRequest import HTTPRequest f.REQUEST = HTTPRequest('', dict(HTTP_HOST='localhost:8080'), {}) from Products.CompositePage.composite import Composite f.composite = Composite() f.composite._setId("composite") from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate t = ZopePageTemplate( id="template", text=template_text, content_type="text/html") f.composite.template = t from Products.CompositePage.slot import Slot 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) from Products.CompositePage.element import CompositeElement e1 = CompositeElement('e1', f.a1) slot_a._setObject(e1.id, e1) return f.composite
def __setstate__(self, state): # Perform on-the-fly migration from unicode. if isinstance(state.get('_text'), unicode): state['_text'] = state['_text'].encode('utf-8') if isinstance(state.get('title'), unicode): state['title'] = state['title'].encode('utf-8') ZopePageTemplate.inheritedAttribute('__setstate__')(self, state)
def test_cook_zope2_page_templates_good_format_attr_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', GOOD_FORMAT_ATTR_UNICODE) hack_pt(pt, self.app) self.assertEqual( pt.pt_render().strip(), '<p>title of <Application at > is Zope</p>')
def _createZODBClone(self): """ Create a ZODB (editable) equivalent of this object. """ target = ZopePageTemplate(self.getId(), _CUSTOMIZED_TEMPLATE_ZPT) target._setProperty('rest', self.raw, 'text') return target
def test_cook_zope2_page_templates_good_format_attr_str(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', GOOD_FORMAT_ATTR_STR) hack_pt(pt, self.portal) self.assertEqual( pt.pt_render().strip(), '<p>title of <PloneSite at plone> is Plone site</p>')
def test_access_to_private_content_not_allowed_via_rich_text(self): try: from plone.app.textfield.value import RichTextValue except ImportError: return from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate foobar = create_private_document(self.portal, 'foobar') login(self.portal, TEST_USER_NAME) foobar.text = RichTextValue(u'Secret.', 'text/plain', 'text/html') self.assertEqual( self.portal.portal_workflow.getInfoFor(foobar, 'review_state'), 'private') # Check that guarded_getattr is happy for the current user. self.assertEqual(guarded_getattr(self.portal, 'foobar'), foobar) self.assertEqual( guarded_getattr(self.portal.foobar, 'text'), foobar.text) # Access to text.output may be more restricted than access to the # text object itself, but this makes no sense, so we switch that # off in this test. # self.assertRaises( # Unauthorized, guarded_getattr, self.portal.foobar.text, 'output') self.portal.foobar.text.__allow_access_to_unprotected_subobjects__ = 1 self.assertEqual( guarded_getattr(self.portal.foobar.text, 'output'), '<p>Secret.</p>') TEMPLATE = '<p tal:content="structure python:%s" />' pt = ZopePageTemplate( 'mytemplate', TEMPLATE % "'access {0.foobar.text.output}'.format(context)") hack_pt(pt, context=self.portal) self.assertEqual(pt.pt_render(), '<p>access <p>Secret.</p></p>') # Check the same for anonymous. logout() self.assertRaises( Unauthorized, guarded_getattr, self.portal, 'foobar') self.assertRaises( Unauthorized, guarded_getattr, self.portal.foobar, 'text') # *If* somehow anonymous can access the text, then we have allowed # access to the output as well. self.assertEqual( guarded_getattr(self.portal.foobar.text, 'output'), '<p>Secret.</p>') # But for the template anonymous would need access to everything, # which rightly fails. self.assertRaises(Unauthorized, pt.pt_render) # Test the simpler access without str.format for the current user. login(self.portal, TEST_USER_NAME) pt = ZopePageTemplate( 'mytemplate', TEMPLATE % "context.foobar.text.output") hack_pt(pt, context=self.portal) self.assertEqual(pt.pt_render(), '<p><p>Secret.</p></p>') # and for anonymous logout() self.assertRaises(Unauthorized, pt.pt_render)
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_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_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 manage_afterAdd(self, item, container): """ Setup tasks upon instantiation """ if 'login_form' not 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_cook_zope2_page_templates_good_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', six.text_type(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 """ 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', 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 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(u'Auto-generated default page') app._setObject('index_html', root_pt) self.commit(u'Added default view for root object')
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 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)
class Report(BaseReport, ZenPackable): """Report object""" __pychecker__ = 'no-override' meta_type = 'Report' # this is deprecated don't use!!! description = "" security = ClassSecurityInfo() _relations = ZenPackable._relations def __init__(self, id, title = None, text=None, content_type='text/html'): ZenModelRM.__init__(self, id); self._template = ZopePageTemplate(id, text, content_type) self.title = title def __call__(self, *args, **kwargs): """Return our rendered template not our default page """ if not 'args' in kwargs: kwargs['args'] = args template = self._template.__of__(self) path_info = template.REQUEST['PATH_INFO'].replace(' ', '%20') if (path_info.startswith('/zport/dmd/Reports') and path_info not in template.REQUEST['HTTP_REFERER'] and 'adapt=false' not in template.REQUEST['QUERY_STRING']): url = '/zport/dmd/reports#reporttree:' url += path_info.replace('/', '.') template.REQUEST['RESPONSE'].redirect(url) self.auditRunReport() return template.pt_render(extra_context={'options': kwargs}) def ZScriptHTML_tryForm(self, *args, **kwargs): """Test form called from ZMI test tab """ return self.__call__(self, args, kwargs) def manage_main(self): """Return the ZMI edit page of our template not ourself """ template = self._template.__of__(self) return template.pt_editForm() pt_editForm = manage_main def pt_editAction(self, REQUEST, title, text, content_type, expand): """Send changes to our template instead of ourself""" template = self._template.__of__(self) return template.pt_editAction(REQUEST, title, text, content_type, expand)
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_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)
class Report(BaseReport, ZenPackable): """Report object""" __pychecker__ = 'no-override' meta_type = 'Report' # this is deprecated don't use!!! description = "" security = ClassSecurityInfo() _relations = ZenPackable._relations def __init__(self, id, title=None, text=None, content_type='text/html'): ZenModelRM.__init__(self, id) self._template = ZopePageTemplate(id, text, content_type) self.title = title def __call__(self, *args, **kwargs): """Return our rendered template not our default page """ if not 'args' in kwargs: kwargs['args'] = args template = self._template.__of__(self) path_info = template.REQUEST['PATH_INFO'].replace(' ', '%20') if (path_info.startswith('/zport/dmd/Reports') and path_info not in template.REQUEST['HTTP_REFERER'] and 'adapt=false' not in template.REQUEST['QUERY_STRING']): url = '/zport/dmd/reports#reporttree:' url += path_info.replace('/', '.') template.REQUEST['RESPONSE'].redirect(url) self.auditRunReport() return template.pt_render(extra_context={'options': kwargs}) def ZScriptHTML_tryForm(self, *args, **kwargs): """Test form called from ZMI test tab """ return self.__call__(self, args, kwargs) def manage_main(self): """Return the ZMI edit page of our template not ourself """ template = self._template.__of__(self) return template.pt_editForm() pt_editForm = manage_main def pt_editAction(self, REQUEST, title, text, content_type, expand): """Send changes to our template instead of ourself""" template = self._template.__of__(self) return template.pt_editAction(REQUEST, title, text, content_type, expand)
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_cook_zope2_page_templates_bad_key_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_KEY_UNICODE) hack_pt(pt, self.app) self.assertEqual( pt.pt_render(), '<p>access by key: <Folder at test_folder_1_></p>') self.app.test_folder_1_.__roles__ = ['Manager'] with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual( "You are not allowed to access 'test_folder_1_' in this context", str(err.exception))
def test_cook_zope2_page_templates_bad_key_str(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_KEY_STR) hack_pt(pt, self.app) self.assertEqual( pt.pt_render(), '<p>access by key: {}</p>'.format( escape(repr(self.app.test_folder_1_)))) self.app.test_folder_1_.__roles__ = ['Manager'] with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual( "You are not allowed to access 'test_folder_1_' in this context", str(err.exception))
def test_cook_zope2_page_templates_bad_attr_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_ATTR_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)) hack_pt(pt, context=self.app) 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_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="python:'{0._delObject}'.format(context)" />""") hack_pt(pt, context=self.app) with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual( "You are not allowed to access '_delObject' in this context", str(err.exception))
class Assignment(base.Assignment): implements(ITALPortlet) title = u"" # overrides the readonly property method from the base class def __init__(self, title=u"", tal=u""): self.pt = ZopePageTemplate(id='__tal_portlet__') self.title = title self.tal = tal def _get_tal(self): return self.pt.read() def _set_tal(self, value): self.pt.pt_edit(value, 'text/html') tal = property(_get_tal, _set_tal)
class Assignment(base.Assignment): title = u"" # overrides the readonly property method from the base class def __init__(self, title=u"", tal=u""): self.pt = ZopePageTemplate(id='__tal_portlet__') self.title = title self.tal = tal def _get_tal(self): return self.pt.read() def _set_tal(self, value): self.pt.pt_edit(value, 'text/html') tal = property(_get_tal, _set_tal)
def _createObjectByType( self, name, body, content_type ): if name.endswith('.py'): ob = PythonScript( name ) ob.write( body ) elif name.endswith('.dtml'): ob = DTMLDocument( '', __name__=name ) ob.munge( body ) elif content_type in ('text/html', 'text/xml' ): ob = ZopePageTemplate( name, str( body ) , content_type=content_type ) elif content_type[:6]=='image/': ob=Image( name, '', body, content_type=content_type ) else: ob=File( name, '', body, content_type=content_type ) return ob
def pt_render(self, source=0, extra_context={}): doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) # Unmarshall arguments to __call__ API args = extra_context.get("options", []) kwargs = extra_context.copy() if kwargs.has_key("options"): del kwargs["options"] if kwargs.has_key("context"): del kwargs["context"] batch_mode = extra_context.get("batch_mode", 0) request = extra_context.get("REQUEST", None) if not request: request = get_request() if request.get("debug", 0): return doc_xml report_tool = getToolByName(self, "portal_report") pdf = report_tool.renderPDF(self.pdf_stylesheet, doc_xml, context=self.pt_getContext()["here"], *args, **kwargs) if request and not batch_mode: request.RESPONSE.setHeader("Content-Type", "application/pdf") request.RESPONSE.setHeader("Content-Length", len(pdf)) request.RESPONSE.setHeader("Content-Disposition", "inline;filename=%s.pdf" % self.title_or_id()) return pdf
def pt_upload(self, REQUEST, file=''): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV" if type(file) is not StringType: if not file: raise ValueError, 'File not specified' file = file.read() if file.startswith("PK") : # FIXME: this condition is probably not enough # this is a OOo zip file, extract the content builder = OOoBuilder(file) attached_files_list = [n for n in builder.getNameList() if n.startswith(self._OLE_directory_prefix) or n.startswith('Pictures') or n == 'META-INF/manifest.xml' ] # destroy a possibly pre-existing OLE document set if self.OLE_documents_zipstring: self.OLE_documents_zipstring = None # create a zip archive and store it if attached_files_list: memory_file = StringIO() try: zf = ZipFile(memory_file, mode='w', compression=ZIP_DEFLATED) except RuntimeError: zf = ZipFile(memory_file, mode='w') for attached_file in attached_files_list: zf.writestr(attached_file, builder.extract(attached_file) ) zf.close() memory_file.seek(0) self.OLE_documents_zipstring = memory_file.read() self.content_type = builder.getMimeType() file = builder.prepareContentXml(self.ooo_xml_file_id) return ZopePageTemplate.pt_upload(self, REQUEST, file)
def pt_render(self, source=0, extra_context={}): doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) # Unmarshall arguments to __call__ API args = extra_context.get('options', []) kwargs = extra_context.copy() if kwargs.has_key('options'): del kwargs['options'] if kwargs.has_key('context'): del kwargs['context'] batch_mode = extra_context.get('batch_mode', 0) request = extra_context.get('REQUEST', None) if not request: request = get_request() if request.get('debug',0): return doc_xml report_tool = getToolByName(self, 'portal_report') pdf = report_tool.renderPDF(self.pdf_stylesheet, doc_xml, context=self.pt_getContext()['here'], *args, **kwargs) if request and not batch_mode: request.RESPONSE.setHeader('Content-Type','application/pdf') request.RESPONSE.setHeader('Content-Length',len(pdf)) request.RESPONSE.setHeader('Content-Disposition','inline;filename=%s.pdf' % self.title_or_id()) return pdf
def _createObjectByType(self, name, body, content_type): encoding = self.getEncoding() or 'utf-8' if six.PY2 and isinstance(body, six.text_type): body = body.encode(encoding) if name.endswith('.py'): ob = PythonScript(name) ob.write(body) return ob if name.endswith('.dtml'): ob = DTMLDocument('', __name__=name) ob.munge(body) return ob if content_type in ('text/html', 'text/xml'): return ZopePageTemplate(name, body, content_type=content_type) if isinstance(body, six.text_type): body = body.encode(encoding) if content_type[:6] == 'image/': return Image(name, '', body, content_type=content_type) return File(name, '', body, content_type=content_type)
def test_access_to_private_content_not_allowed_via_rich_text(self): try: # This is only available for tests if we have plone.app.dexterity, # which in tests is by default only the case for Plone 5. from plone.app.textfield.value import RichTextValue except ImportError: return from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate setRoles(self.portal, TEST_USER_ID, ['Manager']) login(self.portal, TEST_USER_NAME) wf_tool = self.portal.portal_workflow wf_tool.setChainForPortalTypes(['Document'], 'simple_publication_workflow') self.portal.invokeFactory('Document', 'foobar') foobar = self.portal.foobar foobar.text = RichTextValue(u'Secret.', 'text/plain', 'text/html') self.assertEqual( self.portal.portal_workflow.getInfoFor(foobar, 'review_state'), 'private') logout() pt = ZopePageTemplate('mytemplate', ''' <p tal:content="structure python:'access {0.foobar.text.output}'.format(context).lower()" /> ''') # noqa hack_pt(pt, context=self.portal) self.assertRaises(Unauthorized, pt.pt_render)
def get(self, name, filepath): cache = self.get_cache_storage() update = False if filepath not in cache: update = True else: data = cache[filepath] # check mtime if (os.path.exists(filepath) and os.path.getmtime(filepath) > data['mtime']): # need to update, it changed update = True if update: if not os.path.exists(filepath): cache[filepath] = { 'template': None, 'mtime': 9999999999 } else: fi = open(filepath) cache[filepath] = { 'template': ZopePageTemplate(name, fi.read()), 'mtime': os.path.getmtime(filepath) } fi.close() return cache[filepath]['template']
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 from AccessControl.SecurityManagement import getSecurityManager pt = ZopePageTemplate('mytemplate', pt_content) noSecurityManager() old_security_policy = setSecurityPolicy(UnauthorizedSecurityPolicy()) try: hack_pt(pt, context=self.app) with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual('Nothing is allowed!', str(err.exception)) finally: setSecurityPolicy(old_security_policy)
def PUT_factory( self, name, typ, body ): """ Dispatcher for PUT requests to non-existent IDs. Returns an object of the appropriate type (or None, if we don't know what to do). """ major, minor = typ.split('/', 1) if major == 'image': return Image( id=name , title='' , file='' , content_type=typ ) if major == 'text': if minor == 'x-python': return PythonScript( id=name ) if minor in ('html', 'xml'): return ZopePageTemplate( name ) return DTMLMethod( __name__=name ) return None
class HTMLPortlet(LocalPropertyManager, Folder): """ """ meta_type = METATYPE_HTMLPORTLET icon = 'misc_/NaayaCore/HTMLPortlet.gif' manage_options = ( ({'label': 'Properties Ex', 'action': 'manage_properties_html'},) + (Folder.manage_options[0],) + Folder.manage_options[3:] ) def all_meta_types(self, interfaces=None): """ """ y = [] additional_meta_types = ['Image', 'File'] for x in Products.meta_types: if x['name'] in additional_meta_types: y.append(x) return y security = ClassSecurityInfo() title = LocalProperty('title') body = LocalProperty('body') 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 __call__(self, context={}, *args): """ """ if not context.has_key('args'): context['args'] = args context['skin_files_path'] = self.getLayoutTool().getSkinFilesPath() wrappedTemplate = self.template.__of__(self) context['here'] = self return wrappedTemplate.pt_render(extra_context=context) def get_type_label(self): #returns the label for the portlet type return PORTLETS_TYPES[self.portlettype] #zmi actions security.declareProtected(view_management_screens, 'manage_properties_html') def manage_properties(self, title='', body='', lang=None, REQUEST=None): """ """ if lang is None: lang = self.gl_get_selected_language() self._setLocalPropValue('title', lang, title) self._setLocalPropValue('body', lang, body) self._p_changed = 1 if REQUEST: REQUEST.RESPONSE.redirect('manage_properties_html?save=ok') #zmi pages security.declareProtected(view_management_screens, 'manage_properties_html') manage_properties_html = PageTemplateFile('zpt/htmlportlet_manage_properties', globals())
def _createObjectByType( self, name, body, content_type ): if isinstance( body, unicode ): encoding = self.getEncoding() if encoding is None: body = body.encode() else: body = body.encode( encoding ) if name.endswith('.py'): ob = PythonScript( name ) ob.write( body ) elif name.endswith('.dtml'): ob = DTMLDocument( '', __name__=name ) ob.munge( body ) elif content_type in ('text/html', 'text/xml' ): ob = ZopePageTemplate( name, body , content_type=content_type ) elif content_type[:6]=='image/': ob=Image( name, '', body, content_type=content_type ) else: ob=File( name, '', body, content_type=content_type ) return ob
def pt_render(self, source=0, extra_context={}): doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context) # Unmarshall arguments to __call__ API args = extra_context.get('options', []) kwargs = extra_context.copy() if kwargs.has_key('options'): del kwargs['options'] if kwargs.has_key('context'): del kwargs['context'] batch_mode = extra_context.get('batch_mode', 0) request = extra_context.get('REQUEST', None) if not request: request = get_request() if request.get('debug', 0): return doc_xml report_tool = getToolByName(self, 'portal_report') pdf = report_tool.renderPDF(self.pdf_stylesheet, doc_xml, context=self.pt_getContext()['here'], *args, **kwargs) if request and not batch_mode: request.RESPONSE.setHeader('Content-Type', 'application/pdf') request.RESPONSE.setHeader('Content-Length', len(pdf)) request.RESPONSE.setHeader( 'Content-Disposition', 'inline;filename=%s.pdf' % self.title_or_id()) return pdf
def test_cook_zope2_page_templates_bad_attr_unicode(self): from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate pt = ZopePageTemplate('mytemplate', BAD_ATTR_UNICODE) hack_pt(pt) self.assertRaises(Unauthorized, pt.pt_render) hack_pt(pt, context=self.portal) self.assertRaises(Unauthorized, pt.pt_render)
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 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 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 from AccessControl.SecurityManagement import getSecurityManager pt = ZopePageTemplate('mytemplate', pt_content) noSecurityManager() old_security_policy = setSecurityPolicy(UnauthorizedSecurityPolicy()) getSecurityManager() try: hack_pt(pt, context=self.app) with self.assertRaises(Unauthorized) as err: pt.pt_render() self.assertEqual("Nothing is allowed!", str(err.exception)) finally: setSecurityPolicy(old_security_policy)
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)