def test_renameObjectByPaths_postonly(self): from Products.PythonScripts.PythonScript import PythonScript script = PythonScript('script') script._filepath = 'script' src = """context.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL'], REQUEST=context.REQUEST)""" script.write(src) self.portal.evil = script csrf_token = self._get_authenticator() self.publish('/plone/evil', extra={'_authenticator': csrf_token}, request_method='POST') self.assertEqual('News', self.portal.news.Title()) owner_basic = ptc.portal_owner + ':' + ptc.default_password csrf_token = self._get_authenticator(owner_basic) self.publish('/plone/evil', extra={'_authenticator': csrf_token}, basic=owner_basic) self.assertEqual('News', self.portal.news.Title()) self.publish('/plone/evil', request_method='POST', extra={'_authenticator': csrf_token}, basic=owner_basic) self.assertEqual('EVIL', self.portal.news.Title()) self.setRoles(['Manager']) self.portal.news.setTitle('News') self.portal.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL']) self.assertEqual('EVIL', self.portal.news.Title()) self.portal.news.setTitle('News') self.setRoles(['Member']) self.portal.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL']) self.assertEqual('News', self.portal.news.Title())
def test_preserve_names_with_extensions(self): # Verifies that FSConnection retains original object names # even though the object names already have extensions. conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) for n in range(3): script = PythonScript('script%d.py' % n) script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder for n in range(3): self.assert_(hasattr(f, 'script%d.py' % n)) self.assert_(not hasattr(f, 'script%d' % n)) # white box test: verify the scripts were actually stored # with .py extensions. dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) for n in range(3): self.assert_(('script%d.py' % n) in names, names) finally: conn2.close() finally: conn.close()
def __init__(self, *args, **kw): """ override to call __init__ of python scripts in order to set correctly bindings """ XMLObject.__init__(self, *args, **kw) ZopePythonScript.__init__(self, *args, **kw)
def _initDCWorkflowScripts( workflow, scripts, context ): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str( s_info[ 'script_id' ] ) # no unicode! meta_type = s_info[ 'meta_type' ] filename = s_info[ 'filename' ] file = '' if filename: file = context.readDataFile( filename ) if meta_type == PythonScript.meta_type: script = PythonScript( id ) script.write( file ) elif meta_type == ExternalMethod.meta_type: script = ExternalMethod( id , '' , s_info['module'] , s_info['function'] ) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod( file, __name__=id ) if workflow.scripts.has_key(id): workflow.scripts._delObject(id) workflow.scripts._setObject( id, script )
def test_constructContent_simple_STI(self): from AccessControl import Unauthorized from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManager import setSecurityPolicy from Products.CMFCore.PortalFolder import PortalFolder from Products.CMFCore.TypesTool \ import ScriptableTypeInformation as STI from Products.CMFCore.tests.base.dummy import DummyFactoryDispatcher from Products.CMFCore.tests.base.tidata import STI_SCRIPT from Products.PythonScripts.PythonScript import PythonScript site = self._makeSite().__of__(self.root) acl_users = site.acl_users setSecurityPolicy(self._oldPolicy) newSecurityManager(None, acl_users.all_powerful_Oz) tool = self._makeOne().__of__(site) sti_baz = STI('Baz', permission='Add portal content', constructor_path='addBaz') tool._setObject('Baz', sti_baz) script = PythonScript('addBaz') script.write(STI_SCRIPT) tool._setObject('addBaz', script) folder = site._setObject( 'folder', PortalFolder(id='folder') ) folder.manage_addProduct = {'FooProduct': DummyFactoryDispatcher(folder) } folder._owner = (['acl_users'], 'user_foo') self.assertEqual( folder.getOwner(), acl_users.user_foo ) try: tool.constructContent('Baz', container=folder, id='page2') except Unauthorized: self.fail('CMF Collector issue #165 (Ownership bug): ' 'Unauthorized raised' ) self.assertEqual(folder.page2.portal_type, 'Baz')
def migrate_to_1_12(db): """ Convert resources script lib File into PythonScript and Image """ libs = db.resources.objectValues('File') for lib in libs: lib_id = lib.id() lib_data = lib.data content_type = lib.getContentType() if 'image' in content_type: db.resources.manage_delObjects(lib_id) lib_id = manage_addImage(db.resources, lib_id, lib_data) else: error_re = re.compile('^## Errors:$', re.MULTILINE) ps = PythonScript('testing') try: lib_data = asUnicode(lib_data) except UnicodeDecodeError, e: logger.info("Unknown encoding, skipping: %s" % lib_id) continue ps.write(lib_data) if not error_re.search(ps.read()): db.resources.manage_delObjects(lib_id) ignored = manage_addPythonScript(db.resources, lib_id) sc = db.resources._getOb(lib_id) sc.write(lib_data) logger.info("Converted to Script: %s" % lib_id) continue
def test_renameObjectByPaths_postonly(self): from Products.PythonScripts.PythonScript import PythonScript script = PythonScript("script") script._filepath = "script" src = """context.plone_utils.renameObjectsByPaths(paths=['/plone/news'], new_ids=['news'], new_titles=['EVIL'], REQUEST=context.REQUEST)""" script.write(src) self.portal.evil = script csrf_token = self._get_authenticator() self.publish("/plone/evil", extra={"_authenticator": csrf_token}, request_method="POST") self.assertEqual("News", self.portal.news.Title()) owner_basic = SITE_OWNER_NAME + ":" + SITE_OWNER_PASSWORD csrf_token = self._get_authenticator(owner_basic) self.publish("/plone/evil", extra={"_authenticator": csrf_token}, basic=owner_basic) self.assertEqual("News", self.portal.news.Title()) self.publish("/plone/evil", request_method="POST", extra={"_authenticator": csrf_token}, basic=owner_basic) self.assertEqual("EVIL", self.portal.news.Title()) self.setRoles(["Manager"]) self.portal.news.setTitle("News") self.portal.plone_utils.renameObjectsByPaths(paths=["/plone/news"], new_ids=["news"], new_titles=["EVIL"]) self.assertEqual("EVIL", self.portal.news.Title()) self.portal.news.setTitle("News") self.setRoles(["Member"]) self.portal.plone_utils.renameObjectsByPaths(paths=["/plone/news"], new_ids=["news"], new_titles=["EVIL"]) self.assertEqual("News", self.portal.news.Title())
def _newPS(self, txt, bind=None): from Products.PythonScripts.PythonScript import PythonScript ps = PythonScript('ps') #ps.ZBindings_edit(bind or {}) ps.write(txt) ps._makeFunction() return ps
def createPythonScript(self, id_, title, code): """Creare new Python Script object.""" ps = PythonScript(id_) if title: ps.ZPythonScript_setTitle(title) ps.write(code) ps._makeFunction() return ps
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise 'Bad Request', ( 'The id %s is invalid as a class name.' % id) if not meta_type: meta_type=id r={} for data in self.aq_acquire('_getProductRegistryData')('zclasses'): r['%(product)s/%(id)s' % data]=data['meta_class'] bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise 'Invalid class', b Z=ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) constScript = PythonScript(id+'_add') constScript.write(addDefault % {'id': id, 'title':id+' constructor'}) self._setObject(constScript.getId(), constScript) self.manage_addPermission( id+'_add_permission', id+' constructor permission', 'Add %ss' % meta_type ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', 'Add %ss' % meta_type ) Z=self._getOb(id) Z.propertysheets.permissions.manage_edit( selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type] ) if REQUEST is not None: return self.manage_main(self,REQUEST, update_menu=1)
def Base_runPythonScript(self, code): script = PythonScript('Python Shell Script').__of__(self) code_line_list = code.split('\r\n') code = '\n'.join(code_line_list) script.write(code) if script._code is None: raise ValueError, repr(script.errors) return script()
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 compileFormulaScript(self, script_id, formula, with_args=False): # disable CSRF to allow script saving if hasattr(self, "REQUEST"): alsoProvides(self.REQUEST, IDisableCSRFProtection) # Remember the current user member = self.getCurrentMember() if member.__class__.__name__ == "SpecialUser": user = member else: user = member.getUser() # Switch to the db's owner (formula must be compiled with the higher # access rights, but their execution will always be perform with the # current access rights) owner = self.getOwner() newSecurityManager(None, owner) ps = self.getFormulaScript(script_id) if not ps: ps = PythonScript(script_id) self.scripts._setObject(script_id, ps) ps = self.getFormulaScript(script_id) if with_args: ps._params = "*args" safe_utils = get_utils() import_list = [] for module in safe_utils: import_list.append( "from %s import %s" % ( module, ", ".join(safe_utils[module])) ) import_list = ";".join(import_list) formula = _expandIncludes(self, formula) if (formula.strip().count('\n') == 0 and not formula.startswith('return ')): formula = "return " + formula str_formula = STR_FORMULA % { 'script_id': script_id, 'import_list': import_list, 'formula': formula } ps.write(str_formula) if self.debugMode: logger.info(script_id + " compiled") # Switch back to the original user newSecurityManager(None, user) return ps
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 __call__(self, value, *args, **kwargs): if not isinstance(value, PythonScript): script = PythonScript('no_id') script.ZPythonScript_edit('**options', value) value = script script._compile() if script.errors: return '<br/>\n'.join(script.errors) else: return 1
def _customizeScript(self,scriptName,params=""): message="" if not(scriptName in self.objectIds()): # if no scriptname script in current form manager defaultscript = getattr(self,scriptName) # gets the first script acquired scriptBody = defaultscript.body() script = PythonScript(scriptName) script.ZPythonScript_edit(params=params,body=scriptBody) script.write(scriptBody) self._setObject(scriptName,script) message+="portal_status_message=custom "+scriptName+" has been added"+scriptBody return message
def register_script_object(self, object_name): file_path = '%s/%s.py' % (self.scripts_home, object_name) try: content = open(file_path).read() if not content: raise CustomError('Empty file : %s' % file_path) content = content % {'libplugin_id' : self.config['id']} script_ob = PythonScript(object_name) script_ob.write(content) self.folder._setObject(object_name, script_ob) except Exception, err: LOG('', ERROR, err)
def manage_addZClass(self, id, title="", baseclasses=[], meta_type="", CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise BadRequest, ("The id %s is invalid as a class name." % id) if not meta_type: meta_type = id r = {} for data in self.aq_acquire("_getProductRegistryData")("zclasses"): r["%(product)s/%(id)s" % data] = data["meta_class"] bases = [] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise ValueError, "Invalid class: %s" % b Z = ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type = meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id + "_addForm", id + " constructor input form", addFormDefault % {"id": id, "meta_type": meta_type} ) constScript = PythonScript(id + "_add") constScript.write(addDefault % {"id": id, "title": id + " constructor"}) self._setObject(constScript.getId(), constScript) self.manage_addPermission(id + "_add_permission", id + " constructor permission", "Add %ss" % meta_type) self.manage_addPrincipiaFactory( id + "_factory", id + " factory", meta_type, id + "_addForm", "Add %ss" % meta_type ) Z = self._getOb(id) Z.propertysheets.permissions.manage_edit(selected=["Add %ss" % id]) Z.manage_setPermissionMapping( permission_names=["Create class instances"], class_permissions=["Add %ss" % meta_type] ) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction(1) self._v_f = f = ps._v_f if f is not None: self.func_code = f.func_code self.func_defaults = f.func_defaults else: # There were errors in the compile. # No signature. self.func_code = bad_func_code() self.func_defaults = None self._body = ps._body self._params = ps._params if not self.title: self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def manage_doCustomize(self, folder_path, body=None, RESPONSE=None): ''' Makes a PythonScript with the same code. ''' custFolder = self.getCustomizableObject() fpath = tuple(split(folder_path, '/')) folder = self.restrictedTraverse(fpath) if body is None: body = self.read() id = self.getId() obj = PythonScript(id) folder._verifyObjectPaste(obj, validate_src=0) folder._setObject(id, obj) obj = folder._getOb(id) obj.write(body) if RESPONSE is not None: RESPONSE.redirect('%s/%s/manage_main' % ( folder.absolute_url(), id))
def getScript(self, context): # Generate Python script object body = self.ScriptBody role = self.ProxyRole script = PythonScript(self.__name__) script = script.__of__(context) # Skip check roles script._validateProxy = lambda i=None: None # Force proxy role if role != u'none': script.manage_proxy((role,)) body = body.encode('utf-8') params = 'fields, easyform, request' script.ZPythonScript_edit(params, body) return script
def testRestrictedIteration(self): """ Check content iterators can be used by restricted python code. """ # To let restricted python access methods on folder marker = object() saved_class_attributes = {} for method_id in ("objectIds", "objectValues", "objectItems"): roles_id = method_id + "__roles__" saved_class_attributes[roles_id] = getattr(HBTreeFolder2, roles_id, marker) setattr(HBTreeFolder2, roles_id, None) try: h = HBTreeFolder2() # whatever value, as long as it has an __of__ h._setOb("foo", HBTreeFolder2()) script = PythonScript("script") script.ZPythonScript_edit( "h", dedent( """ for dummy in h.objectIds(): pass for dummy in h.objectValues(): pass for dummy in h.objectItems(): pass """ ), ) class DummyRequest(object): # To make Shared.DC.Scripts.Bindings.Bindings._getTraverseSubpath # happy other = {} script.REQUEST = DummyRequest script(h) finally: for roles_id, orig in saved_class_attributes.iteritems(): if orig is marker: delattr(HBTreeFolder2, roles_id) else: setattr(HBTreeFolder2, roles_id, orig)
def updateScript(self, body, role): # Regenerate Python script object # Sync set of script source code, proxy role and # creation of Python Script object. bodyField = self.schema["ScriptBody"] proxyField = self.schema["ProxyRole"] script = PythonScript(self.title_or_id()) script = script.__of__(self) # Force proxy role if role != "none": script.manage_proxy((role,)) script.ZPythonScript_edit("fields, ploneformgen, request", body) PythonField.set(bodyField, self, script) StringField.set(proxyField, self, role)
def test_resource_registry_vector(self): for vector in ('less-variables.js', 'less-modify.js'): src = ''' class ctx: def format(self, *args, **kwargs): self.foo=context return "foo" context.portal_registry['plone.lessvariables']['foo'] = ctx() context.portal_registry['plone.lessvariables']['bar'] = "{foo.foo.__class__}" js = context.restrictedTraverse("%s") return js() ''' % vector from Products.PythonScripts.PythonScript import PythonScript script = PythonScript('evil') script._filepath = 'evil' script.write(src) self.portal.evil = script output = self.publish('/plone/evil') self.assertFalse( 'Products.CMFPlone.Portal.PloneSite' in output.body)
def test_python_script(self, with_proxy_roles=0): conn = self.db.open() try: app = conn.root()['Application'] script = PythonScript('script') script.write('##title=test script\nreturn "OK"') script._makeFunction() app._setObject(script.id, script, set_owner=0) if with_proxy_roles: # set a proxy role and verify nothing breaks script._proxy_roles = ('System Administrator',) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] script = app.script self.assertEqual(script.title, 'test script') res = script() self.assertEqual(res, 'OK') finally: conn2.close() finally: conn.close()
def test_non_conflicting_name_extensions1(self): # Verifies that FSConnection can write to 'script0.py' then 'script0' conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # It's OK to write to 'script0.py' then 'script0'. script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0') in names, names) conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder self.assertEqual(f['script0.py'](), 'OK') self.assertEqual(f['script0'](), 'Hello, world!') finally: conn2.close() finally: conn.close()
def test_non_conflicting_name_extensions2(self): # Verifies that FSConnection can write to 'script0.py' and 'script0' # at the same time conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # It's OK to write to 'script0.py' then 'script0'. script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() conn2 = self.db.open() try: app = conn2.root()['Application'] f = app.folder self.assertEqual(f['script0.py'](), 'OK') self.assertEqual(f['script0'](), 'Hello, world!') finally: conn2.close() finally: conn.close()
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 __init__(self, filename, _prefix=None,__name__=None): # Figure out where the file is if _prefix is None: _prefix=SOFTWARE_HOME elif type(_prefix) is not type(''): _prefix = package_home(_prefix) # Come up with a good name... if not __name__: __name__=os.path.split(filename)[-1] # Default to '.py' extension if not os.path.splitext(filename)[1]: filename = filename + '.py' self.filename = os.path.join(_prefix, filename) PythonScript.__init__(self, __name__) f = open(self.filename) body = f.read() f.close() self.ZPythonScript_edit('', body)
def _write(self, text): ps = PythonScript(self.id) ps.write(text) ps._makeFunction() ps._editedBindings() self._v_f = f = ps._v_f self._body = ps._body self._params = ps._params fc = f.func_code self._setFuncSignature(f.func_defaults, fc.co_varnames, fc.co_argcount)
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction() self._v_ft = ps._v_ft self.__code__ = ps.__code__ self.__defaults__ = ps.__defaults__ self._body = ps._body self._params = ps._params self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def _initDCWorkflowScripts( workflow, scripts, context ): """ Initialize DCWorkflow scripts """ for s_info in scripts: id = str( s_info[ 'script_id' ] ) # no unicode! meta_type = s_info[ 'meta_type' ] filename = s_info[ 'filename' ] file = '' if filename: file = context.readDataFile( filename ) if meta_type == PythonScript.meta_type: script = PythonScript( id ) script.write( file ) elif meta_type == ExternalMethod.meta_type: script = ExternalMethod( id , '' , s_info['module'] , s_info['function'] ) elif meta_type == DTMLMethod.meta_type: script = DTMLMethod( file, __name__=id ) else: for mt in workflow.scripts.filtered_meta_types(): if mt['name']==meta_type: if hasattr(mt['instance'], 'write'): script = mt['instance'](id) script.write(file) else: script = mt['instance'](file, __name__=id) break else: raise ValueError, 'Invalid type: %s' % meta_type if workflow.scripts.has_key(id): workflow.scripts._delObject(id) workflow.scripts._setObject( id, script )
def installUi(self): '''Installs the user interface.''' # Delete the existing folder if it existed. zopeContent = self.app.objectIds() if 'ui' in zopeContent: self.app.manage_delObjects(['ui']) self.app.manage_addFolder('ui') # Some useful imports from Products.PythonScripts.PythonScript import PythonScript from Products.PageTemplates.ZopePageTemplate import \ manage_addPageTemplate # Browse the physical folder and re-create it in the Zope folder j = os.path.join ui = j(j(appy.getPath(), 'gen'), 'ui') for root, dirs, files in os.walk(ui): folderName = root[len(ui):] # Get the Zope folder that corresponds to this name zopeFolder = self.app.ui if folderName: for name in folderName.strip(os.sep).split(os.sep): zopeFolder = zopeFolder._getOb(name) # Create sub-folders at this level for name in dirs: zopeFolder.manage_addFolder(name) # Create files at this level for name in files: baseName, ext = os.path.splitext(name) f = file(j(root, name)) if ext in gen.File.imageExts: zopeFolder.manage_addImage(name, f) elif ext == '.pt': manage_addPageTemplate(zopeFolder, baseName, '', f.read()) elif ext == '.py': obj = PythonScript(baseName) zopeFolder._setObject(baseName, obj) zopeFolder._getOb(baseName).write(f.read()) else: zopeFolder.manage_addFile(name, f) f.close() # Update the home page if 'index_html' in zopeContent: self.app.manage_delObjects(['index_html']) manage_addPageTemplate(self.app, 'index_html', '', homePage) # Update the error page if 'standard_error_message' in zopeContent: self.app.manage_delObjects(['standard_error_message']) manage_addPageTemplate(self.app, 'standard_error_message', '',errorPage)
def test_constructContent(self): from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManager import setSecurityPolicy from AccessControl.unauthorized import Unauthorized from Products.PythonScripts.PythonScript import PythonScript from Products.CMFCore.PortalFolder import PortalFolder from Products.CMFCore.TypesTool \ import ScriptableTypeInformation as STI from Products.CMFCore.tests.base.dummy import DummyFactoryDispatcher from Products.CMFCore.tests.base.tidata import STI_SCRIPT site = self.site acl_users = self.acl_users ttool = self.ttool setSecurityPolicy(self._oldPolicy) newSecurityManager(None, acl_users.all_powerful_Oz) self.site._owner = (['acl_users'], 'all_powerful_Oz') sti_baz = STI('Baz', permission='Add portal content', constructor_path='addBaz') ttool._setObject('Baz', sti_baz) ttool._setObject('addBaz', PythonScript('addBaz')) s = ttool.addBaz s.write(STI_SCRIPT) f = site._setObject('folder', PortalFolder(id='folder')) f.manage_addProduct = {'FooProduct': DummyFactoryDispatcher(f)} f._owner = (['acl_users'], 'user_foo') self.assertEqual(f.getOwner(), acl_users.user_foo) ttool.constructContent('Dummy Content', container=f, id='page1') try: ttool.constructContent('Baz', container=f, id='page2') except Unauthorized: self.fail('CMF Collector issue #165 (Ownership bug): ' 'Unauthorized raised') wf = site.portal_workflow.wf wf.creation_guard.changeFromProperties({'guard_expr': 'python:False'}) try: ttool.constructContent('Dummy Content', container=f, id='page3') except Unauthorized, e: self.assertEqual(str(e), "Cannot create Dummy Content")
def getScript(self, context): # Generate Python script object body = self.ScriptBody role = self.ProxyRole script = PythonScript(self.__name__) script = script.__of__(context) # Skip check roles script._validateProxy = lambda i=None: None # Force proxy role if role != u'none': script.manage_proxy((role, )) body = body.encode('utf-8') params = 'fields, easyform, request' script.ZPythonScript_edit(params, body) return script
def test_auto_rename_on_extension_conflict(self): # When you create a Python Script called "script0", Ape adds a # .py extension. If, in a second transaction, you add # "script0.py", Ape must rename the current "script0.py" to # "script0" to make room for the new "script0.py". conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) # Can't write to 'script0' then 'script0.py'. script = PythonScript('script0') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0') not in names, names) # script0.py already exists, so Ape should automatically rename. script = PythonScript('script0.py') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() # Did it write them correctly? text = open(os.path.join(dir, 'script0')).read() self.assert_(text.find('OK') > 0, text) self.assert_(text.find('Hello, world!') < 0, text) text = open(os.path.join(dir, 'script0.py')).read() self.assert_(text.find('OK') < 0, text) self.assert_(text.find('Hello, world!') > 0, text) finally: conn.close()
def getScript(self, context): # Generate Python script object body = self.ScriptBody role = self.ProxyRole script = PythonScript(self.__name__) script = script.__of__(context) # Skip check roles script._validateProxy = lambda i=None: None # Force proxy role if role != u"none": script.manage_proxy((role, )) if six.PY2 and isinstance(body, six.text_type): body = body.encode("utf-8") params = "fields, easyform, request" script.ZPythonScript_edit(params, body) return script
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 = split(typ, '/') 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') and SUPPORTS_PAGE_TEMPLATES: return ZopePageTemplate(name) return DTMLMethod(__name__=name) return None
def _write(self, text, compile): ''' Parses the source, storing the body, params, title, bindings, and source in self. If compile is set, compiles the function. ''' ps = PythonScript(self.id) ps.write(text) if compile: ps._makeFunction(1) self._v_f = f = ps._v_f if f is not None: self.func_code = f.func_code self.func_defaults = f.func_defaults else: # There were errors in the compile. # No signature. self.func_code = bad_func_code() self.func_defaults = None self._body = ps._body self._params = ps._params self.title = ps.title self._setupBindings(ps.getBindingAssignments().getAssignedNames()) self._source = ps.read() # Find out what the script sees.
def updateScript(self, body, role): # Regenerate Python script object # Sync set of script source code, proxy role and # creation of Python Script object. bodyField = self.schema["ScriptBody"] proxyField = self.schema["ProxyRole"] script = PythonScript(self.title_or_id()) script = script.__of__(self) # Force proxy role if role != "none": script.manage_proxy((role, )) script.ZPythonScript_edit("fields, ploneformgen, request", body) PythonField.set(bodyField, self, script) StringField.set(proxyField, self, role)
def installUi(self): '''Installs the user interface.''' # Some useful imports from OFS.Folder import manage_addFolder from OFS.Image import manage_addImage, manage_addFile from Products.PythonScripts.PythonScript import PythonScript from Products.PageTemplates.ZopePageTemplate import \ manage_addPageTemplate # Delete the existing folder if it existed. zopeContent = self.app.objectIds() if 'ui' in zopeContent: self.app.manage_delObjects(['ui']) manage_addFolder(self.app, 'ui') # Browse the physical ui folders (the Appy one and an app-specific, if # the app defines one) and create the corresponding objects in the Zope # folder. In the case of files having the same name in both folders, # the one from the app-specific folder is chosen. j = os.path.join uiFolders = [j(j(appy.getPath(), 'gen'), 'ui')] appUi = j(self.config.diskFolder, 'ui') if os.path.exists(appUi): uiFolders.insert(0, appUi) for ui in uiFolders: for root, dirs, files in os.walk(ui): folderName = root[len(ui):] # Get the Zope folder that corresponds to this name zopeFolder = self.app.ui if folderName: for name in folderName.strip(os.sep).split(os.sep): zopeFolder = zopeFolder._getOb(name) # Create sub-folders at this level for name in dirs: if not hasattr(zopeFolder.aq_base, name): manage_addFolder(zopeFolder, name) # Create files at this level for name in files: zopeName, ext = os.path.splitext(name) if ext not in ('.pt', '.py'): # In the ZODB, pages and scripts have their name without # their extension. zopeName = name if hasattr(zopeFolder.aq_base, zopeName): continue f = file(j(root, name)) if zopeName == 'favicon.ico': if not hasattr(self.app, zopeName): # Copy it at the root. Else, IE won't notice it. manage_addImage(self.app, zopeName, f) elif ext in gen.File.imageExts: manage_addImage(zopeFolder, zopeName, f) elif ext == '.pt': manage_addPageTemplate(zopeFolder, zopeName, '', f.read()) elif ext == '.py': obj = PythonScript(zopeName) zopeFolder._setObject(zopeName, obj) zopeFolder._getOb(zopeName).write(f.read()) else: manage_addFile(zopeFolder, zopeName, f) f.close() # Update the home page if 'index_html' in zopeContent: self.app.manage_delObjects(['index_html']) manage_addPageTemplate(self.app, 'index_html', '', homePage) # Update the error page if 'standard_error_message' in zopeContent: self.app.manage_delObjects(['standard_error_message']) manage_addPageTemplate(self.app, 'standard_error_message', '', errorPage)
def _createZODBClone(self): """Create a ZODB (editable) equivalent of this object.""" obj = PythonScript(self.getId()) obj.write(self.read()) return obj
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None, zope_object=0): """Add a Z Class """ if bad_id(id) is not None: raise BadRequest, ('The id %s is invalid as a class name.' % id) if not meta_type: meta_type = id r = {} for data in self.aq_acquire('_getProductRegistryData')('zclasses'): r['%(product)s/%(id)s' % data] = data['meta_class'] bases = [] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) elif r.has_key(b): bases.append(r[b]) else: raise ValueError, 'Invalid class: %s' % b Z = ZClass(id, title, bases, zope_object=zope_object) Z._zclass_.meta_type = meta_type self._setObject(id, Z) if CreateAFactory and meta_type: self.manage_addDTMLMethod( id + '_addForm', id + ' constructor input form', addFormDefault % { 'id': id, 'meta_type': meta_type }, ) constScript = PythonScript(id + '_add') constScript.write(addDefault % { 'id': id, 'title': id + ' constructor' }) self._setObject(constScript.getId(), constScript) self.manage_addPermission(id + '_add_permission', id + ' constructor permission', 'Add %ss' % meta_type) self.manage_addPrincipiaFactory(id + '_factory', id + ' factory', meta_type, id + '_addForm', 'Add %ss' % meta_type) Z = self._getOb(id) Z.propertysheets.permissions.manage_edit(selected=['Add %ss' % id]) Z.manage_setPermissionMapping( permission_names=['Create class instances'], class_permissions=['Add %ss' % meta_type]) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def DeployMassStandards(self, remove_oldstuff=0, DestinationURL=None): """ copy images and other documents into the instance unless they are already there """ t={} # create folders root = self.getRoot() rootbase = getattr(root, 'aq_base', root) osj = os.path.join standards_home = osj(package_home(globals()),'standards') t = self._deployImages(root, standards_home, t=t, remove_oldstuff=remove_oldstuff) #www_home = osj(standards_home,'www') #t = self._deployImages(root.www, www_home, #t=t, remove_oldstuff=remove_oldstuff) # shortcut addPG = root.manage_addProduct['PageTemplates'].manage_addPageTemplate AddParam2URL = Utils.AddParam2URL for filestr in os.listdir(standards_home): if filestr[-5:] == '.dtml': id, title = cookIdAndTitle(filestr.replace('.dtml','')) if hasattr(rootbase, id) and remove_oldstuff: root.manage_delObjects([id]) if not hasattr(rootbase, id): file = DTMLFile('standards/%s'%filestr.replace('.dtml',''), globals()).read() root.manage_addDTMLDocument(id, title, file=file) t[id] ="DTML Document" elif filestr[-4:] == '.zpt': id, title = cookIdAndTitle(filestr.replace('.zpt','')) if hasattr(rootbase, id) and remove_oldstuff: root.manage_delObjects([id]) if not hasattr(rootbase, id): file = open(osj(standards_home,filestr)).read() addPG(id, title=title, text=file) t[id]="Page Template" elif filestr[-3:] == '.py': id, title = cookIdAndTitle(filestr.replace('.py','')) if hasattr(rootbase, id) and remove_oldstuff: root.manage_delObjects([id]) if not hasattr(rootbase, id): file = open(osj(standards_home, filestr)).read() id = root._setObject(id, PythonScript(id)) root._getOb(id).write(file) t[id]="Script (Python)" if DestinationURL: msg = '' for k,v in t.items(): msg = "%s (%s)\n%s"%(k,v,msg) url = AddParam2URL(DestinationURL,{'manage_tabs_message':\ "Standard objects deployed\n\n%s"%msg}) self.REQUEST.RESPONSE.redirect(url) else: return "Standard objects deployed\n%s"%t
def restricted_exec(self, body, varmap=None): ps = PythonScript('temp') if varmap is None: varmap = {} ps.ZPythonScript_edit(join(varmap.keys(), ','), body) return ps.__of__(self)(varmap.values())
def testHTML(self): self.REQUEST['BODY'] = BASIC_HTML ttool = TypesTool() fti = FTIDATA_CMF[0].copy() del fti['id'] ttool._setObject('Document', FTI('Document', **fti)) ps = self.site._setObject('source_html', PythonScript('source_html')) zpt = self.site._setObject('source_html', ZopePageTemplate('source_html_template')) dir = abspath(dirname(utils.__file__)) _file = path_join(dir, 'skins', 'zpt_content', 'source_html.py') data = open(_file, 'r').read() ps.write(data) _file = path_join(dir, 'skins', 'zpt_content', 'source_html_template.pt') data = open(_file, 'r').read() zpt.write(data) d = self._makeOne('foo') d._setPortalTypeName('Document') d.PUT(self.REQUEST, self.RESPONSE) rnlinesplit = compile(r'\r?\n?') simple_lines = rnlinesplit.split(BASIC_HTML) get_lines = rnlinesplit.split(d.manage_FTPget()) # strip off headers meta_pattern = compile(r'meta name="([a-z]*)" ' + r'content="([a-z]*)"') title_pattern = compile(r'<title>(.*)</title>') simple_headers = [] while simple_lines and simple_lines[0] != '<BODY>': header = simple_lines[0].strip().lower() match = meta_pattern.search(header) if match: simple_headers.append(match.groups()) else: match = title_pattern.search(header) if match: simple_headers.append(('title', match.group(1))) simple_lines = simple_lines[1:] get_headers = [] while get_lines and get_lines[0] != '<BODY>': header = get_lines[0].strip().lower() match = meta_pattern.search(header) if match: get_headers.append(match.groups()) else: match = title_pattern.search(header) if match: get_headers.append(('title', match.group(1))) get_lines = get_lines[1:] self.assertEqual(get_lines, simple_lines) self.assertTrue(get_headers) self.assertTrue(simple_headers) self.assertTrue(len(get_headers) >= len(simple_headers)) for header in simple_headers: self.assertTrue(header in get_headers) body1 = d.EditableBody() self.REQUEST['BODY'] = d.manage_FTPget() d.PUT(self.REQUEST, self.RESPONSE) self.assertEqual(d.EditableBody(), body1)
def setUp(self): from Products.PythonScripts.PythonScript import PythonScript BodyAdapterTestCase.setUp(self) self._obj = PythonScript('foo_script') self._BODY = _PYTHONSCRIPT_BODY
def afterSetUp(self): self._cachemanager = MemcachedManager("cache") self._cache = self._cachemanager.ZCacheManager_getCache() self.folder.script = PythonScript("test-script") self._script = self.folder.script
def manage_beforeDelete(self, item, container): """ This method is called, when the object is deleted. """ PythonScript.inheritedAttribute('manage_beforeDelete')(self, item, container) self.delete_portlet_for_object(item)
def importContent(context): """Import base content into the Plone site.""" portal = context.getSite() # Because the portal doesn't implement __contains__? existing_content = portal.keys() target_language, is_combined_language, locale = _get_locales_info(portal) request = getattr(portal, 'REQUEST', None) # Set up Language specific information _set_language_settings(portal, is_combined_language) _setup_calendar(locale) _setup_visible_ids(target_language, locale) # TODO Content translations # The front-page frontpage_id = 'front-page' if frontpage_id not in existing_content: title = _translate(u'front-title', target_language, u"Welcome to Plone") description = _translate( u'front-description', target_language, u"Congratulations! You have successfully installed Plone.") content = createContent( 'Document', id=frontpage_id, title=title, description=description, ) content = addContentToContainer(portal, content) # TODO front-page text # TODO Enable presentation mode ##fp.setPresentation(True) portal.setDefaultPage('front-page') _publish(content) content.reindexObject() # News topic news_id = 'news' if news_id not in existing_content: title = _translate(u'news-title', target_language, u'News') description = _translate(u'news-description', target_language, u'Site News') allowed_types = ['News Item'] container = createContent('Folder', id=news_id, title=title, description=description) container = addContentToContainer(portal, container) _createObjectByType('Collection', container, id='aggregator', title=title, description=description) aggregator = container['aggregator'] # Set the content-types that can be added to this container. # FIXME The following 3 lines ##container.setConstrainTypesMode(constraintypes.ENABLED) ##container.setLocallyAllowedTypes(allowed_types) ##container.setImmediatelyAddableTypes(allowed_types) container.setOrdering('unordered') container.setDefaultPage('aggregator') _publish(container) # Set the Collection criteria. #: Sort on the Effective date aggregator.sort_on = u'effective' aggregator.reverse_sort = True #: Query by Type and Review State aggregator.query = [ { 'i': u'portal_type', 'o': u'plone.app.querystring.operation.selection.is', 'v': [u'News Item'], }, { 'i': u'review_state', 'o': u'plone.app.querystring.operation.selection.is', 'v': [u'published'], }, ] aggregator.setLayout('summary_view') _publish(aggregator) # Events topic events_id = 'events' if events_id not in existing_content: title = _translate(u'events-title', target_language, u'Events') description = _translate(u'events-description', target_language, u'Site Events') allowed_types = ['Event'] container = createContent('Folder', id=events_id, title=title, description=description) container = addContentToContainer(portal, container) _createObjectByType('Collection', container, id='aggregator', title=title, description=description) aggregator = container['aggregator'] # Set the content-types that can be added to this container. # FIXME The following 3 lines ##container.setConstrainTypesMode(constraintypes.ENABLED) ##container.setLocallyAllowedTypes(allowed_types) ##container.setImmediatelyAddableTypes(allowed_types) container.setOrdering('unordered') container.setDefaultPage('aggregator') _publish(container) # Set up the collection # type_crit = topic.addCriterion('Type', 'ATPortalTypeCriterion') # type_crit.setValue('Event') # topic.addCriterion('start', 'ATSortCriterion') # state_crit = topic.addCriterion('review_state', 'ATSimpleStringCriterion') # state_crit.setValue('published') # date_crit = topic.addCriterion('start', 'ATFriendlyDateCriteria') # # Set date reference to now # date_crit.setValue(0) # # Only take events in the future # date_crit.setDateRange('+') # This is irrelevant when the date is now # date_crit.setOperation('more') _publish(aggregator) # configure Members folder members_id = 'Members' if members_id not in existing_content: title = _translate(u'members-title', target_language, u'Users') description = _translate(u'members-description', target_language, u"Site Users") container = createContent('Folder', id=members_id, title=title, description=description) container = addContentToContainer(portal, container) container.setOrdering('unordered') container.reindexObject() _publish(container) # add index_html to Members area if 'index_html' not in container: container._setObject('index_html', PythonScript('index_html')) index_html = getattr(container, 'index_html') index_html.write(member_indexhtml) index_html.ZPythonScript_setTitle('User Search') # Block all right column portlets by default manager = queryUtility(IPortletManager, name='plone.rightcolumn') if manager is not None: assignable = getMultiAdapter((container, manager), ILocalPortletAssignmentManager) assignable.setBlacklistStatus('context', True) assignable.setBlacklistStatus('group', True) assignable.setBlacklistStatus('content_type', True)
def read(self): ps = PythonScript(self.id) ps._body = self._body ps._params = self._params return ps.read()
def _testScript(self,txt): theScript = PythonScript('test') theScript.ZBindings_edit({}) theScript.write(txt) theScript._makeFunction() return theScript()
def test_non_conflicting_name_extensions3(self): # Verifies that FSConnection can write to 'script0.py' # then 'script0.dtml', then 'script0'. # Then verifies that removal of items works correctly. conn = self.db.open() try: app = conn.root()['Application'] f = Folder() f.id = 'folder' app._setObject(f.id, f, set_owner=0) script = PythonScript('script0.py') script.write('##title=test script\nreturn "OK"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0.dtml') script.write('##title=test script\nreturn "No DTML here"') f._setObject(script.id, script, set_owner=0) transaction.commit() script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() dir = os.path.join(self.conn.basepath, 'folder') names = os.listdir(dir) self.assert_(('script0.py') in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) conn2 = self.db.open() try: app2 = conn2.root()['Application'] f2 = app2.folder self.assertEqual(f2['script0.py'](), 'OK') self.assertEqual(f2['script0.dtml'](), 'No DTML here') self.assertEqual(f2['script0'](), 'Hello, world!') finally: transaction.abort() conn2.close() f._delObject('script0.py') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) f._delObject('script0') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') not in names, names) script = PythonScript('script0') script.write('##title=test script\nreturn "Hello, world!"') f._setObject(script.id, script, set_owner=0) transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') in names, names) self.assert_(('script0') in names, names) f._delObject('script0.dtml') transaction.commit() names = os.listdir(dir) self.assert_(('script0.py') not in names, names) self.assert_(('script0.dtml') not in names, names) self.assert_(('script0') in names, names) finally: conn.close()
def evaluate(self): python_script = PythonScript('update_script_runner').__of__(self) python_script.write(self.update_script) return python_script()
def load_py(filename): id = os.path.basename(filename) ob = PythonScript(id) ob.write(file(filename).read()) return ob
def __init__(self, id, **kw): ZMIField.__init__(self, id, **kw) PythonScript.__init__(self, id)
def setUp(self): from Products.PythonScripts.PythonScript import PythonScript self._obj = PythonScript('foo_script') self._BODY = _PYTHONSCRIPT_BODY
def _newPS(self, txt, bind=None): from Products.PythonScripts.PythonScript import PythonScript ps = PythonScript('ps') ps.write(txt) ps._makeFunction() return ps
def _newfun(self, code): verify(code) return PythonScript._newfun(self, code)