def test_nested_folders(self): from Products.PythonScripts.PythonScript import manage_addPythonScript self.layer['app'].manage_addFolder("repository") repository = self.layer['app']["repository"] repository.manage_addFolder("foo") repository.foo.manage_addFolder("bar") manage_addPythonScript(repository.foo.bar, 'example.py') script = repository.foo.bar['example.py'] serialised = serialise_directory(repository) try: cwd = os.getcwd() git_repo = tempfile.mkdtemp() os.chdir(git_repo) os.system("mkdir foo") os.system("mkdir foo/bar") with open(os.path.join(git_repo, "foo", "bar", "example.py"), 'wb') as real_file: real_file.write(script.manage_DAVget()) os.system("git init") os.system("git add foo") os.system("git cia -m 'example'") for hashed, contents in serialised: path = os.path.join(git_repo, ".git", "objects", hashed[:2], hashed[2:]) self.assertEqual(open(path, 'rb').read(), contents) finally: os.chdir(cwd) shutil.rmtree(git_repo)
def test_python_script(self): from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(self.layer['app'], 'example.py') script = self.layer['app']['example.py'] serialised = serialise_object(script) try: cwd = os.getcwd() git_repo = tempfile.mkdtemp() with open(os.path.join(git_repo, "example.py"), 'wb') as real_file: # Duplicate the file on the filesystem real_file.write(script.manage_DAVget()) os.chdir(git_repo) os.system("git init") os.system("git add example.py") os.system("git cia -m 'example'") expected_hash = git_hash(serialised) path = os.path.join(git_repo, ".git", "objects", expected_hash[:2], expected_hash[2:]) self.assertEqual(open(path, 'rb').read(), serialised) finally: os.chdir(cwd) shutil.rmtree(git_repo)
def addPythonScript(obj,id): f=open(test_dir+'/'+id+'.pys') file=f.read() f.close() manage_addPythonScript(obj,id) obj._getOb(id).write(file) return getattr(obj,id)
def addPythonScript(obj, id): f = open(test_dir + '/' + id + '.pys') file = f.read() f.close() manage_addPythonScript(obj, id) obj._getOb(id).write(file) return getattr(obj, id)
def _update(self, portal): rdf_calendars = portal.objectValues([RDFCalendar.meta_type]) if rdf_calendar_available and len(rdf_calendars): try: # deleteing DateRangeIndex if availalble portal.getCatalogTool().delIndex("resource_interval") self.log.debug("Deleted resource_interval (DateRangeIndex) fro" "m portal_catalog") except: pass # adding start_end and end_date indexes portal.getCatalogTool().addIndex("start_date", "DateIndex") self.log.debug("Added start_date (DateIndex) to portal_catalog") portal.getCatalogTool().addIndex("end_date", "DateIndex") self.log.debug("Added end_date (DateIndex) to portal_catalog") portal_path = get_portal_path(self, portal) script_content = open(portal_path + "/skel/others/local_events.py", "r").read() for rdfcalendar_ob in rdf_calendars: try: rdfcalendar_ob.manage_delObjects(["self_events"]) self.log.debug( "Removed self_events (RDFSummary) to\ RDFCalendar" ) except: break # adding local_events Script (Python) from Naaya skel manage_addPythonScript(rdfcalendar_ob, "local_events") local_events_ob = rdfcalendar_ob._getOb("local_events") local_events_ob._params = "year=None, month=None, day=None" local_events_ob.write(script_content) self.log.debug("Added local_events (Python Script) to RDFCalen" "dar") return True
def setUp(self): # set up a zodb # we can't use DemoStorage here 'cos it doesn't support History self.dir = tempfile.mkdtemp() self.s = FileStorage(os.path.join(self.dir, 'testHistory.fs'), create=True) self.connection = ZODB.DB(self.s).open() r = self.connection.root() a = Application() r['Application'] = a self.root = a # create a python script manage_addPythonScript(a, 'test') self.ps = ps = a.test # commit some changes ps.write('return 1') t = transaction.get() # undo note made by Application instantiation above. t.description = None t.note('Change 1') t.commit() ps.write('return 2') t = transaction.get() t.note('Change 2') t.commit() ps.write('return 3') t = transaction.get() t.note('Change 3') t.commit()
def importResourceFromJSON(self, container, id, element): """ """ id = id.encode('utf-8') resource_type = element['type'] if id in container.objectIds(): container.manage_delObjects([id]) if resource_type == "Page Template": obj = manage_addPageTemplate(container, id) obj.title = element['title'] obj.write(element['data']) elif resource_type == "Script (Python)": manage_addPythonScript(container, id) obj = container._getOb(id) obj.ZPythonScript_setTitle(element['title']) obj.write(element['data']) elif resource_type == "Image": id = manage_addImage(container, id, element['data'].decode('base64'), content_type=element['contenttype']) else: container.manage_addFile(id) obj = getattr(container, id) obj.meta_type = resource_type obj.title = element['title'] data = element['data'].decode('base64') obj.update_data(data, content_type=element['contenttype'])
def test_scriptable_mail_host(self): setRoles(self.portal, TEST_USER_ID, [ 'Manager', ]) self.portal.sc_executed = False manage_addPythonScript(self.portal, 'scriptablemailhost') sc = self.portal['scriptablemailhost'] message = "hello, world!" mto = "*****@*****.**" mfrom = "*****@*****.**" subject = "test 7f14cb3d-d0b7-4950-b863-329da017a9e8" script = "context.MailHost.send(messageText, mto=mto, mfrom=mfrom, subject=subject)\n" sc.ZPythonScript_edit( "messageText, mto, mfrom, subject, encode, immediate, charset, msg_type", StringIO(script)) mm = self.portal['MultiMailHost'] mm._setChain("default", [ { 'action': 'send and stop', 'mailhost': 'scriptablemailhost' }, ]) mm.send(message, mto, mfrom, subject) lastMessage = self.portal.MailHost.messages[-1] self.assertTrue(('Subject: %s' % subject) in lastMessage)
def _create_eionet_survey(container): portal_map = container.getGeoMapTool() meeting_type = portal_map.getSymbolTitle(container.geo_type) survey_details = EIONET_SURVEYS[meeting_type] manage_addMegaSurvey(container, survey_details['id'], survey_details['title']) eionet_survey = container._getOb(survey_details['id']) eionet_survey.meeting_eionet_survey = True eionet_survey.allow_anonymous = 1 eionet_survey._p_changed = True for question in survey_details['questions']: eionet_survey.addWidget(**question) for widget in eionet_survey.objectValues(): widget.locked = True widget._p_changed = True if meeting_type == 'NRC meeting': # Create validation_html and validation_onsubmit for custom validation validation_onsubmit = os.path.join( os.path.dirname(__file__), 'eionet_survey', 'validation_onsubmit_NRC_meeting.txt') manage_addPythonScript(eionet_survey, 'validation_onsubmit') script_content = open(validation_onsubmit, 'rb').read() params = 'datamodel, errors' script_title = 'Custom validation logic' eionet_survey._getOb('validation_onsubmit').ZPythonScript_edit( params, script_content) eionet_survey._getOb('validation_onsubmit').ZPythonScript_setTitle( script_title) validation_html = os.path.join(os.path.dirname(__file__), 'eionet_survey', 'validation_html_NRC_meeting.txt') validation_title = "Custom questionnaire HTML" manage_addPageTemplate(eionet_survey, 'validation_html', validation_title, open(validation_html).read())
def importResourceFromXML(self, container, node): """ """ id = str(node.getAttribute('id')) resource_type = node.getAttribute('type') if id in container.objectIds(): container.manage_delObjects([id]) if resource_type == "Page Template": obj = manage_addPageTemplate(container, id) obj.title = node.getAttribute('title') obj.write(node.firstChild.data) elif resource_type == "Script (Python)": manage_addPythonScript(container, id) obj = container._getOb(id) obj.ZPythonScript_setTitle(node.getAttribute('title')) obj.write(node.firstChild.data) elif resource_type == "Image": id = manage_addImage(container, id, node.firstChild.data.decode('base64'), content_type=node.getAttribute('contenttype')) else: container.manage_addFile(id) obj = getattr(container, id) obj.meta_type = resource_type obj.title = node.getAttribute('title') obj.update_data(node.firstChild.data.decode('base64'), content_type=node.getAttribute('contenttype'))
def setUp(self): # set up a zodb # we can't use DemoStorage here 'cos it doesn't support History self.dir = tempfile.mkdtemp() self.s = FileStorage(os.path.join(self.dir,'testHistory.fs'),create=True) self.connection = ZODB.DB(self.s).open() r = self.connection.root() a = Application() r['Application'] = a self.root = a # create a python script manage_addPythonScript(a,'test') self.ps = ps = a.test # commit some changes ps.write('return 1') t = transaction.get() # undo note made by Application instantiation above. t.description = None t.note('Change 1') t.commit() ps.write('return 2') t = transaction.get() t.note('Change 2') t.commit() ps.write('return 3') t = transaction.get() t.note('Change 3') t.commit()
def loadSkelton(self, REQUEST, skelton='zch'): "Add Page Template PythonScript, DTMLMethod and Image read from skelton directory." for entry in os.listdir(os.path.join(package_home(globals()), 'skelton', skelton)): if entry[-3:] == '.pt' or entry[-4:]=='.pys' or entry[-5:]=='.dtml' or entry[-4:]=='.gif': f=open(os.path.join(package_home(globals()), 'skelton', skelton, entry), 'rb') file=f.read() f.close() try: if entry[-3:] == '.pt': id = entry[:-3] manage_addPageTemplate(self, id, '', file, encoding='utf-8') elif entry[-4:] == '.pys': id = entry[:-4] manage_addPythonScript(self,id) self._getOb(id).write(file) elif entry[-5:] == '.dtml': id = entry[:-5] self.manage_addDTMLMethod(id,'',file) elif entry[-4:] == '.gif': id = entry[:-4] self.manage_addImage(id,file,content_type='image/gif') except: pass if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER'])
def test_scriptable_mail_host(self): setRoles(self.portal, TEST_USER_ID, ['Manager',]) self.portal.sc_executed = False manage_addPythonScript(self.portal, 'scriptablemailhost') sc = self.portal['scriptablemailhost'] message = "hello, world!" mto = "*****@*****.**" mfrom = "*****@*****.**" subject = "test 7f14cb3d-d0b7-4950-b863-329da017a9e8" script = "context.MailHost.send(messageText, mto=mto, mfrom=mfrom, subject=subject)\n" sc.ZPythonScript_edit("messageText, mto, mfrom, subject, encode, immediate, charset, msg_type", StringIO(script)) mm = self.portal['MultiMailHost'] mm._setChain("default", [ { 'action': 'send and stop', 'mailhost': 'scriptablemailhost' }, ] ) mm.send(message, mto, mfrom, subject) lastMessage = self.portal.MailHost.messages[-1] self.assertTrue(('Subject: %s'%subject) in lastMessage)
def addPythonScript(obj, id, file): file_path = Globals.package_home(globals()) f = open(file_path + '/' + file + '.py') file = f.read() f.close() manage_addPythonScript(obj, id) obj._getOb(id).write(file) return getattr(obj, id)
def addPythonScript(folder, id, params='', body=''): """Add a PythonScript to folder.""" from Products.PythonScripts.PythonScript import manage_addPythonScript # clean up any 'ps' that's already here.. if id in folder: del folder[id] manage_addPythonScript(folder, id) folder[id].ZPythonScript_edit(params, body)
def setupWorkflowScript(self): """Setup a dummy workflow script on the plone workflow.""" wftool = getToolByName(self.portal, 'portal_workflow') manage_addPythonScript(wftool.plone_workflow.scripts, 'dummy') wftool.plone_workflow.scripts.dummy.ZPythonScript_edit( 'state_change', '') trans = wftool.plone_workflow.transitions.publish trans.script_name = 'dummy'
def manage_create_validation_onsubmit(self, REQUEST=None): """ create a blank validation_onsubmit template in this survey """ datafile = path.join(path.dirname(__file__), "www", "initial_validation_onsubmit.txt") id = "validation_onsubmit" manage_addPythonScript(self, id) self._getOb(id).write(open(datafile, "rb").read()) if REQUEST is not None: url = self[id].absolute_url() + "/manage_workspace" REQUEST.RESPONSE.redirect(url)
def manage_create_validation_onsubmit(self, REQUEST=None): """ create a blank validation_onsubmit template in this survey """ datafile = os.path.join(os.path.dirname(__file__), 'www', 'initial_validation_onsubmit.txt') id = 'validation_onsubmit' manage_addPythonScript(self, id) self._getOb(id).write(open(datafile, 'rb').read()) if REQUEST is not None: url = self[id].absolute_url() + '/manage_workspace' REQUEST.RESPONSE.redirect(url)
def loadDefaultData(self): """ """ # set default 'Naaya' configuration NySite.__dict__['createPortalTools'](self) NySite.__dict__['loadDefaultData'](self) # remove Naaya default content layout_tool = self.getLayoutTool() naaya_skins = [ skin.getId() for skin in layout_tool.objectValues('Naaya Skin') ] logos = [image.getId() for image in layout_tool.objectValues('Image')] layout_tool.manage_delObjects(naaya_skins + logos) self.getPortletsTool().manage_delObjects( ['menunav_links', 'topnav_links']) self.manage_delObjects('info') # load groupware skel self.loadSkeleton(Globals.package_home(globals())) if rdf_calendar_available: manage_addRDFCalendar(self, id="portal_rdfcalendar", title="Events calendar") rdfcalendar_ob = self._getOb('portal_rdfcalendar') # adding range index to catalog class Empty(object): pass extra = Empty() # Extra has to be an object.. see DateRangeIndex extra.since_field = 'start_date' extra.until_field = 'end_date' self.getCatalogTool().addIndex('resource_interval', 'DateRangeIndex', extra=extra) # adding local_events Script (Python) manage_addPythonScript(rdfcalendar_ob, 'local_events') local_events_ob = rdfcalendar_ob._getOb('local_events') local_events_ob._params = 'year=None, month=None, day=None' local_events_ob.write( open( os.path.dirname(__file__) + '/skel/others/local_events.py', 'r').read()) self.getPortletsTool().assign_portlet('library', 'right', 'portlet_latestuploads_rdf', True) # set default main topics self.getPropertiesTool().manageMainTopics(['about', 'library']) # add meta on brains for group local roles self.getCatalogTool().addColumn('ny_ldap_group_roles')
def cutover(self, dmd): ''' Remove index_html and replace with a python script that will redirect to /zport/dmd/ ''' app = dmd.getPhysicalRoot() if app.hasObject('index_html'): app._delObject('index_html') from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(app, 'index_html') newIndexHtml = app._getOb('index_html') text = 'container.REQUEST.RESPONSE.redirect("/zport/dmd/")\n' newIndexHtml.ZPythonScript_edit('', text)
def cutover(self, dmd): """ Remove index_html and replace with a python script that will redirect to /zport/dmd/ """ app = dmd.getPhysicalRoot() if app.hasObject("index_html"): app._delObject("index_html") from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(app, "index_html") newIndexHtml = app._getOb("index_html") text = 'container.REQUEST.RESPONSE.redirect("/zport/dmd/")\n' newIndexHtml.ZPythonScript_edit("", text)
def loadDefaultData(self): """ """ # set default 'Naaya' configuration NySite.__dict__['createPortalTools'](self) NySite.__dict__['loadDefaultData'](self) # remove Naaya default content layout_tool = self.getLayoutTool() naaya_skins = [skin.getId() for skin in layout_tool.objectValues('Naaya Skin')] logos = [image.getId() for image in layout_tool.objectValues('Image')] layout_tool.manage_delObjects(naaya_skins + logos) self.getPortletsTool().manage_delObjects(['menunav_links', 'topnav_links']) self.manage_delObjects('info') # load groupware skel self.loadSkeleton(Globals.package_home(globals())) if rdf_calendar_available: manage_addRDFCalendar(self, id="portal_rdfcalendar", title="Events calendar") rdfcalendar_ob = self._getOb('portal_rdfcalendar') # adding range index to catalog class Empty(object): pass extra = Empty() # Extra has to be an object.. see DateRangeIndex extra.since_field = 'start_date' extra.until_field = 'end_date' self.getCatalogTool().addIndex('resource_interval', 'DateRangeIndex', extra=extra) # adding local_events Script (Python) manage_addPythonScript(rdfcalendar_ob, 'local_events') local_events_ob = rdfcalendar_ob._getOb('local_events') local_events_ob._params = 'year=None, month=None, day=None' local_events_ob.write(open(os.path.dirname(__file__) + '/skel/others/local_events.py', 'r').read()) self.getPortletsTool().assign_portlet('library', 'right', 'portlet_latestuploads_rdf', True) # set default main topics self.getPropertiesTool().manageMainTopics(['about', 'library']) # add meta on brains for group local roles self.getCatalogTool().addColumn('ny_ldap_group_roles')
def test_from_script(self): # Test that a script like this works: # data = context.restrictedTraverse('@@wkpdf').get_pdf_file() # return data from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(self.portal, 'test_script') self.portal.test_script.ZPythonScript_edit('', 'return ' "context.restrictedTraverse('@@wkpdf').get_pdf_file()") transaction.commit() host, port = self.layer['zserver_info'] portalid = self.portal.getId() url = "http://%(host)s:%(port)i/%(portalid)s/test_script" % locals() result = urlopen(url) pdf_data = result.read() self.pdf_contains(pdf_data, 'PdfPortal')
def setUp(self): from Products.PythonScripts.PythonScript import manage_addPythonScript super(PythonScriptBrowserTests, self).setUp() Zope2.App.zcml.load_site(force=True) uf = self.app.acl_users uf.userFolderAddUser('manager', 'manager_pass', ['Manager'], []) manage_addPythonScript(self.app, 'py_script') self.browser = Browser() self.browser.addHeader( 'Authorization', 'basic {}'.format(codecs.encode( # NOQA: flake8: P101 b'manager:manager_pass', 'base64').decode())) self.browser.open('http://localhost/py_script/manage_main')
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) blank = 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_from_script(self): # Test that a script like this works: # data = context.restrictedTraverse('@@wkpdf').get_pdf_file() # return data from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(self.portal, 'test_script') self.portal.test_script.ZPythonScript_edit( '', 'return ' "context.restrictedTraverse('@@wkpdf').get_pdf_file()") transaction.commit() host, port = self.layer['zserver_info'] portalid = self.portal.getId() url = "http://%(host)s:%(port)i/%(portalid)s/test_script" % locals() result = urlopen(url) pdf_data = result.read() self.pdf_contains(pdf_data, 'PdfPortal')
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_Condition_PathExpression(self): portal = self.portal folder = self.folder object = self.object manage_addPythonScript(self.root, 'test_script') script = self.root.test_script script.ZPythonScript_edit('', 'return context.getId()') ai = self._makeOne(id='view', title='View', action=Expression(text='view'), condition=Expression(text='portal/test_script'), category='global', visible=True) ec = createExprContext(folder, portal, object) self.assertTrue(ai.testCondition(ec))
def test_Condition_PathExpression(self): portal = self.portal folder = self.folder object = self.object manage_addPythonScript(self.root, 'test_script') script = self.root.test_script script.ZPythonScript_edit('', 'return context.getId()') ai = self._makeOne( id='view', title='View', action=Expression(text='view'), condition=Expression(text='portal/test_script'), category='global', visible=True ) ec = createExprContext(folder, portal, object) self.failUnless(ai.testCondition(ec))
def setUp(self): from Products.PythonScripts.PythonScript import manage_addPythonScript super(PythonScriptBrowserTests, self).setUp() Zope2.App.zcml.load_site(force=True) uf = self.app.acl_users uf.userFolderAddUser('manager', 'manager_pass', ['Manager'], []) manage_addPythonScript(self.app, 'py_script') self.browser = Browser() self.browser.addHeader( 'Authorization', 'basic {}'.format( codecs.encode( # noqa: P101 b'manager:manager_pass', 'base64').decode())) self.browser.open('http://localhost/py_script/manage_main')
def add_search_script(context): portal = context.getSite() versions = portal.portal_migration.coreVersions() if(versions.get('Plone', versions.get('Plone Instance', '1.0')) >= '4.2b1'): return if 'search' in portal.objectIds(): return title = translate("Search", domain="plone", context=portal.REQUEST) # add python script manage_addPythonScript(portal, 'search', REQUEST=portal.REQUEST) script = portal['search'] script.ZPythonScript_setTitle(title.encode('utf-8')) script.write("return context.restrictedTraverse('@@gsa-search')()\n")
def add_search_script(context): portal = context.getSite() versions = portal.portal_migration.coreVersions() if (versions.get('Plone', versions.get('Plone Instance', '1.0')) >= '4.2b1'): return if 'search' in portal.objectIds(): return title = translate("Search", domain="plone", context=portal.REQUEST) # add python script manage_addPythonScript(portal, 'search', REQUEST=portal.REQUEST) script = portal['search'] script.ZPythonScript_setTitle(title.encode('utf-8')) script.write("return context.restrictedTraverse('@@gsa-search')()\n")
def loadRDF(self): """ loads rdf files """ from os.path import join from Products.PythonScripts.PythonScript import manage_addPythonScript file_list = [ "gemet-backbone.html", "gemet-backbone.rdf", "gemet-definitions.html", "gemet-definitions.rdf", "gemet-groups.html", "gemet-groups.rdf", "gemet-relations.html", "gemet-skoscore.rdf", ] for file_name in file_list: file_content = open(join(package_home(globals()), "rdfs", file_name + ".py"), "r").read() manage_addPythonScript(self, file_name) self._getOb(file_name).write(file_content)
def runCustomInstallerCode(site): """ Run custom add-on product installation code to modify Plone site object and others Python scripts can be created by Products.PythonScripts.PythonScript.manage_addPythonScript http://svn.zope.org/Products.PythonScripts/trunk/src/Products/PythonScripts/PythonScript.py?rev=114513&view=auto @param site: Plone site """ # Create the script in the site root id = "redirect_handler" # Don't override the existing installation if not id in site.objectIds(): manage_addPythonScript(site, id) script = site[id] # Define the script parameters parameters = "url, host, port, path" script.ZPythonScript_edit(parameters, DEFAULT_REDIRECT_PY_CONTENT)
def runCustomInstallerCode(site): """ Run custom add-on product installation code to modify Plone site object and others Python scripts can be created by Products.PythonScripts.PythonScript.manage_addPythonScript http://svn.zope.org/Products.PythonScripts/trunk/src/Products/PythonScripts/PythonScript.py?rev=114513&view=auto # noqa @param site: Plone site """ # Create the script in the site root id = "redirect_handler" # Don't override the existing installation if id not in site.objectIds(): manage_addPythonScript(site, id) script = site[id] # Define the script parameters parameters = "url, host, port, path" script.ZPythonScript_edit(parameters, DEFAULT_REDIRECT_PY_CONTENT)
def _update(self, portal): rdf_calendars = portal.objectValues([ RDFCalendar.meta_type, ]) if rdf_calendar_available and len(rdf_calendars): try: #deleteing DateRangeIndex if availalble portal.getCatalogTool().delIndex('resource_interval') self.log.debug('Deleted resource_interval (DateRangeIndex) fro' 'm portal_catalog') except: pass #adding start_end and end_date indexes portal.getCatalogTool().addIndex('start_date', 'DateIndex') self.log.debug('Added start_date (DateIndex) to portal_catalog') portal.getCatalogTool().addIndex('end_date', 'DateIndex') self.log.debug('Added end_date (DateIndex) to portal_catalog') portal_path = get_portal_path(self, portal) script_content = open(portal_path + '/skel/others/local_events.py', 'r').read() for rdfcalendar_ob in rdf_calendars: try: rdfcalendar_ob.manage_delObjects([ 'self_events', ]) self.log.debug('Removed self_events (RDFSummary) to\ RDFCalendar') except: break #adding local_events Script (Python) from Naaya skel manage_addPythonScript(rdfcalendar_ob, 'local_events') local_events_ob = rdfcalendar_ob._getOb('local_events') local_events_ob._params = 'year=None, month=None, day=None' local_events_ob.write(script_content) self.log.debug('Added local_events (Python Script) to RDFCalen' 'dar') return True
def _addDefaultData(self): # add default CSS file style_css = open(join(NAAYATHESAURUS_PATH, "zpt", "NaayaThesaurus", "style_presentation.zpt")) content = style_css.read() style_css.close() manage_addPageTemplate(self, "thesaurus_css", title="Naaya Thesaurus CSS", text=content) # add RDF files file_content = open(join(NAAYATHESAURUS_PATH, "rdfs", "thesaurus-labels.spy"), "r").read() manage_addPythonScript(self, "thesaurus-labels.rdf") self._getOb("thesaurus-labels.rdf").write(file_content) file_content = open(join(NAAYATHESAURUS_PATH, "rdfs", "thesaurus-relations.spy"), "r").read() manage_addPythonScript(self, "thesaurus-relations.rdf") self._getOb("thesaurus-relations.rdf").write(file_content) file_content = open(join(NAAYATHESAURUS_PATH, "rdfs", "thesaurus-themes-relations.spy"), "r").read() manage_addPythonScript(self, "thesaurus-themes-relations.rdf") self._getOb("thesaurus-themes-relations.rdf").write(file_content) file_content = open(join(NAAYATHESAURUS_PATH, "rdfs", "thesaurus-themes-labels.spy"), "r").read() manage_addPythonScript(self, "thesaurus-themes-labels.rdf") self._getOb("thesaurus-themes-labels.rdf").write(file_content)
def loadDefaultData(self): """ """ #set default 'Naaya' configuration NySite.__dict__['createPortalTools'](self) NySite.__dict__['loadDefaultData'](self) #remove Naaya default content layout_tool = self.getLayoutTool() naaya_skins = [skin.getId() for skin in layout_tool.objectValues('Naaya Skin')] logos = [image.getId() for image in layout_tool.objectValues('Image')] layout_tool.manage_delObjects(naaya_skins + logos) self.manage_delObjects('info') #load site skeleton - configuration self.loadSkeleton(ENVIROWINDOWS_PRODUCT_PATH) #custom indexes try: self.getCatalogTool().manage_addIndex('resource_area', 'TextIndexNG2', extra={'default_encoding': 'utf-8', 'splitter_single_chars': 1}) except: pass try: self.getCatalogTool().manage_addIndex('resource_focus', 'TextIndexNG2', extra={'default_encoding': 'utf-8', 'splitter_single_chars': 1}) except: pass try: self.getCatalogTool().manage_addIndex('resource_area_exp', 'TextIndexNG2', extra={'default_encoding': 'utf-8', 'splitter_single_chars': 1}) except: pass try: self.getCatalogTool().manage_addIndex('resource_focus_exp', 'TextIndexNG2', extra={'default_encoding': 'utf-8', 'splitter_single_chars': 1}) except: pass try: self.getCatalogTool().manage_addIndex('resource_country', 'TextIndexNG2', extra={'default_encoding': 'utf-8', 'splitter_single_chars': 1}) except: pass #default RDF Calendar settings manage_addRDFCalendar(self, id=ID_RDFCALENDAR, title=TITLE_RDFCALENDAR, week_day_len=1) rdfcalendar_ob = self._getOb(ID_RDFCALENDAR) #adding local_events Script (Python) manage_addPythonScript(rdfcalendar_ob, 'local_events') local_events_ob = rdfcalendar_ob._getOb('local_events') local_events_ob._params = 'year=None, month=None, day=None' local_events_ob.write(open(os.path.dirname(__file__) + '/skel/others/local_events.py', 'r').read()) #Adding custom SchemaTool properties schema_tool = self.getSchemaTool() naaya_folder_schema = schema_tool.getSchemaForMetatype(METATYPE_FOLDER) widget_args = dict( label='Allow users enrolment here?', data_type='bool', widget_type='Checkbox', localized=True, ) naaya_folder_schema.addWidget('show_contributor_request_role', **widget_args) naaya_consultation_schema = schema_tool.getSchemaForMetatype( 'Naaya Consultation') if naaya_consultation_schema: naaya_consultation_schema.addWidget('show_contributor_request_role', **widget_args) naaya_simple_consultation_schema = schema_tool.getSchemaForMetatype( 'Naaya Simple Consultation') if naaya_simple_consultation_schema: naaya_simple_consultation_schema.addWidget( 'show_contributor_request_role', **widget_args) #add survey tool try: from Products.NaayaSurvey.SurveyTool import manage_addSurveyTool manage_addSurveyTool(self) except: pass self._install_link_checker() addNyFolder(self, id='events', title='Events', publicinterface=1) folder_meta_types = FolderMetaTypes(self._getOb('events')) folder_meta_types.set_values(['Naaya Event']) event_folder_custom_index = ( "<metal:block use-macro=\"python:here.getFormsTool()." "getForm('event_folder_index').macros['page']\" />") self['events']['index'].pt_edit(text=event_folder_custom_index, content_type='')
def portal_fixture(self, app): """ Create a groupware site and return the portal_id. XXX: Create a script that adds all zope customizations """ import os import transaction from Products.PageTemplates.ZopePageTemplate import ( manage_addPageTemplate) from Products.PythonScripts.PythonScript import manage_addPythonScript from naaya.groupware.groupware_site import manage_addGroupwareSite from naaya.gwapplications.applications import GWApplications from Products.CookieCrumbler.CookieCrumbler import manage_addCC portal_id = 'gw_portal' #Adding groupware site manage_addGroupwareSite(app, portal_id, 'Groupware Test Site') # # This *things* bellow should be added automatically somehow on site # creation. # #Zope customization path zope_customisation = os.path.join(os.path.dirname(__file__), '..', 'zope_customisation') def get_content(filename): return open(os.path.join(zope_customisation, filename), 'rb').read() #index_html, now registered as simpleView app._delObject('index_html') #gw_macro manage_addPageTemplate(app, 'gw_macro', '') app.gw_macro.write(get_content('gw_macro.zpt')) #CookieCrumbler manage_addCC(app, 'login') #login_form manage_addPageTemplate(app.login, 'login_form', '') app.login.login_form.write( get_content('cookie_crumbler/login_form.zpt')) manage_addPythonScript(app.login, 'index_html') app.login.index_html.write( get_content('cookie_crumbler/index_html.py')) manage_addPythonScript(app.login, 'logged_in') app.login.logged_in.write(get_content('cookie_crumbler/logged_in.py')) manage_addPythonScript(app.login, 'logged_out') app.login.logged_out.write( get_content('cookie_crumbler/logged_out.py')) """ Not required: #GWApplications #appid, title, admin_mail, mail_from app._setObject('applications', GWApplications('applications', 'Applications', '*****@*****.**', '*****@*****.**')) """ return portal_id
def setupSimpleblog_workflow(wf): "..." wf.setProperties(title='SimpleBlog Workflow') for s in ['published', 'draft']: wf.states.addState(s) for t in ['publish', 'retract']: wf.transitions.addTransition(t) for v in ['review_history', 'comments', 'time', 'actor', 'action']: wf.variables.addVariable(v) for l in []: wf.worklists.addWorklist(l) for p in ('Access contents information', 'Modify portal content', 'View'): wf.addManagedPermission(p) from Products.PythonScripts.PythonScript import manage_addPythonScript for p in ['sbPublishEntry']: manage_addPythonScript(wf.scripts, p) srcdef = wf.scripts['sbPublishEntry'] srcdef.ZPythonScript_edit('', script_sbPublishEntry) ## Initial State wf.states.setInitialState('draft') ## States initialization sdef = wf.states['published'] sdef.setProperties(title="""Public""", transitions=('retract',)) sdef.setPermission('Access contents information', 1, ['Anonymous', 'Manager']) sdef.setPermission('Modify portal content', 0, ['Manager', 'Owner']) sdef.setPermission('View', 0, ['Anonymous', 'Authenticated', 'Manager']) sdef = wf.states['draft'] sdef.setProperties(title="""""", transitions=('publish',)) sdef.setPermission('Access contents information', 0, ['Manager', 'Owner']) sdef.setPermission('Modify portal content', 0, ['Manager', 'Owner']) sdef.setPermission('View', 0, ['Manager', 'Owner']) ## Transitions initialization tdef = wf.transitions['publish'] tdef.setProperties(title="""Reviewer publishes content""", new_state_id="""published""", trigger_type=1, script_name="""""", after_script_name='sbPublishEntry', actbox_name="""Publish""", actbox_url="""%(content_url)s/content_publish_form""", actbox_category="""workflow""", props={'guard_roles': 'Manager; Owner'}, ) tdef = wf.transitions['retract'] tdef.setProperties(title="""Member retracts published item""", new_state_id="""draft""", trigger_type=1, script_name="""""", after_script_name="""""", actbox_name="""Retract""", actbox_url="""%(content_url)s/content_retract_form""", actbox_category="""workflow""", props={'guard_roles': 'Owner; Manager'}, ) ## State Variable wf.variables.setStateVar('review_state') ## Variables initialization vdef = wf.variables['review_history'] vdef.setProperties(description="""Provides access to workflow history""", default_value="""""", default_expr="""state_change/getHistory""", for_catalog=0, for_status=0, update_always=0, props={'guard_permissions': 'Request review; Review portal content'}) vdef = wf.variables['comments'] vdef.setProperties(description="""Comments about the last transition""", default_value="""""", default_expr="""python:state_change.kwargs.get('comment', '')""", for_catalog=0, for_status=1, update_always=1, props=None) vdef = wf.variables['time'] vdef.setProperties(description="""Time of the last transition""", default_value="""""", default_expr="""state_change/getDateTime""", for_catalog=0, for_status=1, update_always=1, props=None) vdef = wf.variables['actor'] vdef.setProperties(description="""The ID of the user who performed the last transition""", default_value="""""", default_expr="""user/getId""", for_catalog=0, for_status=1, update_always=1, props=None) vdef = wf.variables['action'] vdef.setProperties(description="""The last transition""", default_value="""""", default_expr="""transition/getId|nothing""", for_catalog=0, for_status=1, update_always=1, props=None)
def make_home_redirect(portal): if not portal.hasObject('index_html'): manage_addPythonScript(portal, 'index_html') script = portal.index_html script.write(INDEX_HTML_CODE)
def portal_fixture(self, app): """ Create a groupware site and return the portal_id. XXX: Create a script that adds all zope customizations """ import os import transaction from Products.PageTemplates.ZopePageTemplate import ( manage_addPageTemplate) from Products.PythonScripts.PythonScript import manage_addPythonScript from naaya.groupware.groupware_site import manage_addGroupwareSite from naaya.gwapplications.applications import GWApplications from Products.CookieCrumbler.CookieCrumbler import manage_addCC portal_id = 'gw_portal' #Adding groupware site manage_addGroupwareSite(app, portal_id , 'Groupware Test Site') # # This *things* bellow should be added automatically somehow on site # creation. # #Zope customization path zope_customisation = os.path.join(os.path.dirname(__file__), '..', 'zope_customisation') def get_content(filename): return open(os.path.join(zope_customisation, filename), 'rb').read() #index_html, now registered as simpleView app._delObject('index_html') #gw_macro manage_addPageTemplate(app, 'gw_macro', '') app.gw_macro.write(get_content('gw_macro.zpt')) #CookieCrumbler manage_addCC(app, 'login') #login_form manage_addPageTemplate(app.login, 'login_form', '') app.login.login_form.write( get_content('cookie_crumbler/login_form.zpt')) manage_addPythonScript(app.login, 'index_html') app.login.index_html.write( get_content('cookie_crumbler/index_html.py')) manage_addPythonScript(app.login, 'logged_in') app.login.logged_in.write( get_content('cookie_crumbler/logged_in.py')) manage_addPythonScript(app.login, 'logged_out') app.login.logged_out.write( get_content('cookie_crumbler/logged_out.py')) """ Not required: #GWApplications #appid, title, admin_mail, mail_from app._setObject('applications', GWApplications('applications', 'Applications', '*****@*****.**', '*****@*****.**')) """ return portal_id
def test_factory(self): from Products.PythonScripts.PythonScript import manage_addPythonScript # Only passing the id container = DummyFolder('container') manage_addPythonScript(container, 'testing') self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, '') self.assertIn('# Example code:', container.testing.body()) self.assertEqual(container.testing.params(), '') # Passing id and a title container = DummyFolder('container') manage_addPythonScript(container, 'testing', title='This is a title') self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertIn('# Example code:', container.testing.body()) self.assertEqual(container.testing.params(), '') # Passing id, title and a request that has no file container = makerequest(DummyFolder('container')) container.REQUEST.form = {} manage_addPythonScript(container, 'testing', title='This is a title', REQUEST=container.REQUEST) self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertIn('# Example code:', container.testing.body()) self.assertEqual(container.testing.params(), '') # Passing id, title and a request ith a file string container = makerequest(DummyFolder('container')) container.REQUEST.form = {'file': 'return 1'} manage_addPythonScript(container, 'testing', title='This is a title', REQUEST=container.REQUEST) self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertEqual(container.testing.body(), 'return 1\n') self.assertEqual(container.testing.params(), '') # Passing id, title and a request with a file object container = makerequest(DummyFolder('container')) container.REQUEST.form = {'file': io.BytesIO(b'return 1')} manage_addPythonScript(container, 'testing', title='This is a title', REQUEST=container.REQUEST) self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertEqual(container.testing.body(), 'return 1\n') self.assertEqual(container.testing.params(), '') # Passing id, title and a file string container = makerequest(DummyFolder('container')) manage_addPythonScript(container, 'testing', title='This is a title', file=b'return 1') self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertEqual(container.testing.body(), 'return 1\n') self.assertEqual(container.testing.params(), '') # Passing id, title and a file object container = makerequest(DummyFolder('container')) manage_addPythonScript(container, 'testing', title='This is a title', file=io.BytesIO(b'return 1')) self.assertEqual(container.testing.getId(), 'testing') self.assertEqual(container.testing.title, 'This is a title') self.assertEqual(container.testing.body(), 'return 1\n') self.assertEqual(container.testing.params(), '')
def build(self): self.db = None self.storage = None conn = None try: self.zodbConnect() conn = self.db.open() root = conn.root() app = root.get('Application') if app and getattr(app, self.sitename, None) is not None: print "zport portal object exists; exiting." return except self.connectionFactory.exceptions.OperationalError as e: print "zenbuild: Database does not exist." sys.exit(1) finally: if conn: conn.close() if self.db: self.db.close() self.db = None if self.storage: self.storage.close() self.storage = None # TODO: remove the port condition, in here for now because there is no SQL dump of postgresql if self.options.fromXml: self.connect() from Products.ZenModel.ZentinelPortal import manage_addZentinelPortal manage_addZentinelPortal(self.app, self.sitename) site = self.app._getOb(self.sitename) # build index_html if self.app.hasObject('index_html'): self.app._delObject('index_html') from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(self.app, 'index_html') newIndexHtml = self.app._getOb('index_html') text = 'container.REQUEST.RESPONSE.redirect(container.zport.virtualRoot() + "/zport/dmd/")\n' newIndexHtml.ZPythonScript_edit('', text) # build standard_error_message if self.app.hasObject('standard_error_message'): self.app._delObject('standard_error_message') file = open(zenPath('Products/ZenModel/dtml/standard_error_message.dtml')) try: text = file.read() finally: file.close() import OFS.DTMLMethod OFS.DTMLMethod.addDTMLMethod(self.app, id='standard_error_message', file=text) # Convert the acl_users folder at the root to a PAS folder and update # the login form to use the Zenoss login form Security.replaceACLWithPAS(self.app, deleteBackup=True) auth0_setup(self.app) account_locker_setup(self.app) # Add groupManager to zport.acl acl = site.acl_users if not hasattr(acl, 'groupManager'): plugins.ZODBGroupManager.addZODBGroupManager(acl, 'groupManager') acl.groupManager.manage_activateInterfaces(['IGroupsPlugin',]) trans = transaction.get() trans.note("Initial ZentinelPortal load by zenbuild.py") trans.commit() print "ZentinelPortal loaded at %s" % self.sitename # build dmd from Products.ZenModel.DmdBuilder import DmdBuilder dmdBuilder = DmdBuilder(site, self.options.evthost, self.options.evtuser, self.options.evtpass, self.options.evtdb, self.options.evtport, self.options.smtphost, self.options.smtpport, self.options.pagecommand) dmdBuilder.build() transaction.commit() # Load XML Data from Products.ZenModel.XmlDataLoader import XmlDataLoader dl = XmlDataLoader(noopts=True, app=self.app) dl.loadDatabase() else: cmd = "gunzip -c %s | %s --usedb=zodb" % ( zenPath("Products/ZenModel/data/zodb.sql.gz"), zenPath("Products/ZenUtils/ZenDB.py"), ) returncode = os.system(cmd) if returncode: print >> sys.stderr, "There was a problem creating the database from the sql dump." sys.exit(1) # Relstorage may have already loaded items into the cache in the # initial connection to the database. We have to expire everything # in the cache in order to prevent errors with overlapping # transactions from the model which was just imported above. if self.options.zodb_cacheservers: self.flush_memcached(self.options.zodb_cacheservers.split()) self.connect() # Set all the attributes site = getattr(self.app, self.sitename, None) site.dmd.smtpHost = self.options.smtphost site.dmd.smtpPort = self.options.smtpport site.dmd.pageCommand = self.options.pagecommand site.dmd.uuid = None for evmgr in (site.dmd.ZenEventManager, site.dmd.ZenEventHistory): evmgr.username = self.options.evtuser evmgr.password = self.options.evtpass evmgr.database = self.options.evtdb evmgr.host = self.options.evthost evmgr.port = self.options.evtport transaction.commit() # Load reports from Products.ZenReports.ReportLoader import ReportLoader rl = ReportLoader(noopts=True, app=self.app) rl.loadDatabase()
def build(self): self.db = None self.storage = None conn = None try: self.zodbConnect() conn = self.db.open() root = conn.root() app = root.get('Application') if app and getattr(app, self.sitename, None) is not None: print "zport portal object exists; exiting." return except self.connectionFactory.exceptions.OperationalError as e: print "zenbuild: Database does not exist." sys.exit(1) finally: if conn: conn.close() if self.db: self.db.close() self.db = None if self.storage: self.storage.close() self.storage = None # TODO: remove the port condition, in here for now because there is no SQL dump of postgresql if self.options.fromXml: self.connect() from Products.ZenModel.ZentinelPortal import manage_addZentinelPortal manage_addZentinelPortal(self.app, self.sitename) site = self.app._getOb(self.sitename) # build index_html if self.app.hasObject('index_html'): self.app._delObject('index_html') from Products.PythonScripts.PythonScript import manage_addPythonScript manage_addPythonScript(self.app, 'index_html') newIndexHtml = self.app._getOb('index_html') text = 'container.REQUEST.RESPONSE.redirect(container.zport.virtualRoot() + "/zport/dmd/")\n' newIndexHtml.ZPythonScript_edit('', text) # build standard_error_message if self.app.hasObject('standard_error_message'): self.app._delObject('standard_error_message') file = open( zenPath('Products/ZenModel/dtml/standard_error_message.dtml')) try: text = file.read() finally: file.close() import OFS.DTMLMethod OFS.DTMLMethod.addDTMLMethod(self.app, id='standard_error_message', file=text) # Convert the acl_users folder at the root to a PAS folder and update # the login form to use the Zenoss login form Security.replaceACLWithPAS(self.app, deleteBackup=True) auth0_setup(self.app) account_locker_setup(self.app) # Add groupManager to zport.acl acl = site.acl_users if not hasattr(acl, 'groupManager'): plugins.ZODBGroupManager.addZODBGroupManager( acl, 'groupManager') acl.groupManager.manage_activateInterfaces([ 'IGroupsPlugin', ]) trans = transaction.get() trans.note("Initial ZentinelPortal load by zenbuild.py") trans.commit() print "ZentinelPortal loaded at %s" % self.sitename # build dmd from Products.ZenModel.DmdBuilder import DmdBuilder dmdBuilder = DmdBuilder(site, self.options.evthost, self.options.evtuser, self.options.evtpass, self.options.evtdb, self.options.evtport, self.options.smtphost, self.options.smtpport, self.options.pagecommand) dmdBuilder.build() transaction.commit() # Load XML Data from Products.ZenModel.XmlDataLoader import XmlDataLoader dl = XmlDataLoader(noopts=True, app=self.app) dl.loadDatabase() else: cmd = "gunzip -c %s | %s --usedb=zodb" % ( zenPath("Products/ZenModel/data/zodb.sql.gz"), zenPath("Products/ZenUtils/ZenDB.py"), ) returncode = os.system(cmd) if returncode: print >> sys.stderr, "There was a problem creating the database from the sql dump." sys.exit(1) # Relstorage may have already loaded items into the cache in the # initial connection to the database. We have to expire everything # in the cache in order to prevent errors with overlapping # transactions from the model which was just imported above. if self.options.zodb_cacheservers: self.flush_memcached(self.options.zodb_cacheservers.split()) self.connect() # Set all the attributes site = getattr(self.app, self.sitename, None) site.dmd.smtpHost = self.options.smtphost site.dmd.smtpPort = self.options.smtpport site.dmd.pageCommand = self.options.pagecommand site.dmd.uuid = None for evmgr in (site.dmd.ZenEventManager, site.dmd.ZenEventHistory): evmgr.username = self.options.evtuser evmgr.password = self.options.evtpass evmgr.database = self.options.evtdb evmgr.host = self.options.evthost evmgr.port = self.options.evtport transaction.commit() # Load reports from Products.ZenReports.ReportLoader import ReportLoader rl = ReportLoader(noopts=True, app=self.app) rl.loadDatabase()