def manage_addRhaptosSite(self, id, title='', description='', create_userfolder=1, email_from_address='', email_from_name='Rhaptos', validate_email=0, dbauser='******', dbapass=None, dbuser='******', dbpass=None, dbname='repository', dbserver=None, dbport=None, RESPONSE=None): """ Rhaptos Site factory """ temp_id = 'DB_OPTS_TEMP' if not hasattr(self.aq_parent.aq_parent,temp_id): self.aq_parent.aq_parent.manage_addFolder(temp_id) root = self.aq_parent.aq_parent[temp_id] root._dbopts={} root._dbopts['admin']=dbauser root._dbopts['adminpass']=dbapass root._dbopts['user']=dbuser root._dbopts['userpass']=dbpass root._dbopts['dbname']=dbname root._dbopts['server']=dbserver root._dbopts['port']=dbport #manage_addSite(self, id, title, description, create_userfolder, email_from_address, email_from_name, validate_email, custom_policy='Rhaptos Site', RESPONSE=RESPONSE) addPloneSite(self, id, title, description, create_userfolder, email_from_address, email_from_name, validate_email, RESPONSE=RESPONSE, extension_ids=('RhaptosSite:rhaptos-default',))
def setup_plone(app, dest_folder, site_id, products=(), profiles=()): app = makerequest(app) dest = app if dest_folder: if dest_folder not in app.objectIds(): log("Creating destination Folder: '%s'" % dest_folder) app.manage_addFolder(id=dest_folder) dest = dest.restrictedTraverse(dest_folder) if site_id in dest.objectIds(): log('%s already exists in %s - REMOVING IT' % (site_id, dest.absolute_url(1))) if dest.meta_type != 'Folder': raise RuntimeError('Destination must be a Folder instance (found %s)' % dest.meta_type) dest.manage_delObjects([site_id]) log('Creating new Plone site with extension profiles %s' % profiles) addPloneSite(dest, site_id, create_userfolder=True, extension_ids=profiles) plone = dest[site_id] log('Created Plone site at %s' % plone.absolute_url(1)) qit = plone.portal_quickinstaller ids = [p['id'] for p in qit.listInstallableProducts(skipInstalled=1) ] for product in products: if product in ids: qit.installProduct(product) if 'front-page' in plone.objectIds(): plone.manage_delObjects('front-page') return plone
def setup_plone(app, dest_folder, site_id, products=(), profiles=()): app = makerequest(app) dest = app if dest_folder: if dest_folder not in app.objectIds(): log("Creating destination Folder: '%s'" % dest_folder) app.manage_addFolder(id=dest_folder) dest = dest.restrictedTraverse(dest_folder) if site_id in dest.objectIds(): log('%s already exists in %s - REMOVING IT' % (site_id, dest.absolute_url(1))) if dest.meta_type != 'Folder': raise RuntimeError( 'Destination must be a Folder instance (found %s)' % dest.meta_type) dest.manage_delObjects([site_id]) log('Creating new Plone site with extension profiles %s' % profiles) addPloneSite(dest, site_id, create_userfolder=True, extension_ids=profiles) plone = dest[site_id] log('Created Plone site at %s' % plone.absolute_url(1)) qit = plone.portal_quickinstaller ids = [p['id'] for p in qit.listInstallableProducts(skipInstalled=1)] for product in products: if product in ids: qit.installProduct(product) if 'front-page' in plone.objectIds(): plone.manage_delObjects('front-page') return plone
def create(self, app, site_id, products_initial, profiles_initial, site_replace): oids = app.objectIds() if site_id in oids: if site_replace and hasattr(app, site_id): if pre_plone3: app.manage_delObjects([site_id,]) else: try: app.manage_delObjects([site_id,]) except LinkIntegrityNotificationException: pass transaction.commit() print "Removed existing Plone Site" oids = app.objectIds() else: print "A Plone Site already exists and will not be replaced" return # actually add in Plone if site_id not in oids: version = getFSVersionTuple() if version[0] < 4: factory = app.manage_addProduct['CMFPlone'] factory.addPloneSite(site_id, create_userfolder=1) else: # we have to simulate the new zmi admin screen here - at # least provide: # extension_ids # setup_content (plone default is currently 'true') from Products.CMFPlone.factory import addPloneSite extension_profiles = ( 'plonetheme.classic:default', 'plonetheme.sunburst:default' ) addPloneSite( app, site_id, extension_ids=extension_profiles, setup_content=False ) # commit the new site to the database transaction.commit() print "Added Plone Site" # install some products plone = getattr(app, site_id) # set the site so that the component architecture will work # properly if not pre_plone3: setSite(plone) if plone: self.quickinstall(plone, products_initial) # run GS profiles self.runProfiles(plone, profiles_initial) print "Finished"
def afterSetUp(self): PloneTestCase.afterSetUp(self) self.setRoles(['Manager']) addPloneSite(self.app, 'login_portal', content_profile_id='Products.ATContentTypes:default') addPloneSite(self.app, 'another_portal', content_profile_id='Products.ATContentTypes:default') self.browser = Browser(self.app) self.browser.handleErrors = False # Don't get HTTP 500 pages self.login_portal = self.app.login_portal # logins go here self.another_portal = self.app.another_portal # another portal # The extra portals do not get a member setup from the base class. # Add our user to the other portals to simulate an ldap environment. for portal in (self.login_portal, self.another_portal): portal.acl_users.source_users.addUser( TEST_USER_ID, TEST_USER_NAME, TEST_USER_PASSWORD) for role in TEST_USER_ROLES: portal.acl_users.portal_role_manager.doAssignRoleToPrincipal( TEST_USER_ID, role) # Configure the login portal to allow logins from our sites. login_registry = self.login_portal.portal_registry login_registry['plone.allow_external_login_sites'] = ( self.portal.absolute_url(), self.another_portal.absolute_url()) # The normal portal needs to allow logins from the login portal, # otherwise the redirect_to action on login or logout will refuse to # redirect externally. This may need to be done on another_portal too, # but for the current tests this is not needed. portal_registry = self.portal.portal_registry portal_registry['plone.allow_external_login_sites'] = ( self.login_portal.absolute_url(), ) # Configure our sites to use the login portal for logins and logouts login_portal_url = self.login_portal.absolute_url() for portal in (self.portal, self.another_portal): reg = portal.portal_registry reg['plone.external_login_url'] = login_portal_url + '/login' reg['plone.external_logout_url'] = login_portal_url + '/logout' # Configure all sites to use a shared secret and set cookies per path # (normally they would have different domains.) for portal in (self.portal, self.login_portal, self.another_portal): session = portal.acl_users.session session._shared_secret = 'secret' session.path = portal.absolute_url_path() # Turn on self-registration self.portal.manage_permission('Add portal member', roles=['Manager', 'Anonymous'], acquire=0) transaction.commit()
def setupSite(self, prefix='sample', extra_profiles=[]): portal_id = '%s-%s' % (prefix, DateTime().strftime('%y-%m-%d-%H%M%S')) profiles = ['plonetheme.barceloneta:default'] + extra_profiles addPloneSite(self.context, portal_id, extension_ids=profiles) self.site = self.context[portal_id] if 'content' in self.request.form: self.site.restrictedTraverse('@@demo-content')() self.request.response.redirect(self.context.getId() + '/' + portal_id)
def createSite(self, root): site_id = 'ksstestportal' if hasattr(root, site_id): logger.info('Deleting previous site "%s".' % (site_id, )) root.manage_delObjects([site_id]) logger.info('Adding new site "%s".' % (site_id, )) addPloneSite(dispatcher=root, id=site_id, extension_ids=()) return root[site_id]
def afterSetUp(self): PloneTestCase.afterSetUp(self) self.setRoles(['Manager']) addPloneSite(self.app, 'login_portal', content_profile_id='Products.ATContentTypes:default') addPloneSite(self.app, 'another_portal', content_profile_id='Products.ATContentTypes:default') self.browser = Browser(self.app) self.browser.handleErrors = False # Don't get HTTP 500 pages self.login_portal = self.app.login_portal # logins go here self.another_portal = self.app.another_portal # another portal # The extra portals do not get a member setup from the base class. # Add our user to the other portals to simulate an ldap environment. for portal in (self.login_portal, self.another_portal): portal.acl_users.source_users.addUser(TEST_USER_ID, TEST_USER_NAME, TEST_USER_PASSWORD) for role in TEST_USER_ROLES: portal.acl_users.portal_role_manager.doAssignRoleToPrincipal( TEST_USER_ID, role) # Configure the login portal to allow logins from our sites. login_registry = self.login_portal.portal_registry login_registry['plone.allow_external_login_sites'] = ( self.portal.absolute_url(), self.another_portal.absolute_url()) # The normal portal needs to allow logins from the login portal, # otherwise the redirect_to action on login or logout will refuse to # redirect externally. This may need to be done on another_portal too, # but for the current tests this is not needed. portal_registry = self.portal.portal_registry portal_registry['plone.allow_external_login_sites'] = ( self.login_portal.absolute_url(), ) # Configure our sites to use the login portal for logins and logouts login_portal_url = self.login_portal.absolute_url() for portal in (self.portal, self.another_portal): reg = portal.portal_registry reg['plone.external_login_url'] = login_portal_url + '/login' reg['plone.external_logout_url'] = login_portal_url + '/logout' # Configure all sites to use a shared secret and set cookies per path # (normally they would have different domains.) for portal in (self.portal, self.login_portal, self.another_portal): session = portal.acl_users.session session._shared_secret = 'secret' session.path = portal.absolute_url_path() # Turn on self-registration self.portal.manage_permission('Add portal member', roles=['Manager', 'Anonymous'], acquire=0) transaction.commit()
def setupSite(self, prefix='sample', extra_profiles=[]): portal_id = '%s-%s' % (prefix, DateTime().strftime('%d.%m.%y-%H%M%S')) profiles = ['plonetheme.sunburst:default'] + extra_profiles addPloneSite(self.context, portal_id, create_userfolder=True, extension_ids=profiles) self.site = self.context[portal_id] self.request.response.redirect(self.context.getId() + '/' + portal_id)
def recreate_plone_site(self): """ Recreate a Plone site """ # remove /temp_folder first, if existing if 'temp_folder' in self.context.objectIds(): self.context.manage_delObjects(['temp_folder']) data = json.loads(self.request.BODY) site_id = str(data["site_id"]) extension_ids = data["extension_ids"] theme = data.get("theme", "barceloneta") root = self.context.restrictedTraverse("/") if site_id in root.objectIds(): print('Deleting Plone site "{0}"'.format(site_id)) root.manage_delObjects([site_id]) print('Creating Plone site "{0}" with {1}'.format( site_id, extension_ids)) # addPloneSite(root, site_id, extension_ids=extension_ids) addPloneSite(root, site_id) print('Created Plone site "{0}" with {1}'.format( site_id, extension_ids)) site = root[site_id] qi = site.portal_quickinstaller for extension_id in (extension_ids or ()): try: product, profile = extension_id.split(":") except ValueError: product, profile = extension_id, "default" print("Installing {}".format(extension_id)) qi.installProducts([product]) self.request.form["form.button.Enable"] = "DONE" self.request.form["themeName"] = theme view = MyThemingControlpanel(root[site_id], self.request) view.update() # disable content rules (PCM-1773) storage = getUtility(IRuleStorage) storage.active = False # set portal.language to NL # See https://community.plone.org/t/content-types-control-panel-zope-schema-bootstrapinterfaces-constraintnotsatisfied-en-us-language/12761 site.language = 'nl' # update portal_diff settings # https://jira.collective.be/browse/PCM-1591 portal_diff = site.portal_diff for pt in ['SubsiteFolder']: portal_diff._pt_diffs[pt] = { 'any': 'Compound Diff for Dexterity types' } self.request.response.setStatus(201) return "DONE"
def stage2(arg): opts = arg.split() profiles = [opts[0]] if len(opts) > 0 else []; site_id = opts[1] if len(opts) > 1 else 'Plonb'; app = Zope2.app() addPloneSite(app, site_id, extension_ids=profiles, setup_content=False, ) import ipdb ; ipdb.set_trace()
def create(container, site_id, products_initial, profiles_initial, site_replace, default_language): oids = container.objectIds() if site_id in oids: if site_replace: try: container.manage_delObjects([site_id, ]) except LinkIntegrityNotificationException: pass transaction.commit() print "Removed existing Plone Site" oids = container.objectIds() else: print "A Plone Site already exists and will not be replaced" plone = getattr(container, site_id) return plone # actually add in Plone if site_id not in oids: if has_factory_addPloneSite(): # we have to simulate the new zmi admin screen here - at # least provide: # extension_ids # setup_content (plone default is currently 'true') from Products.CMFPlone.factory import addPloneSite extension_profiles = ( 'plonetheme.classic:default', 'plonetheme.sunburst:default', ) addPloneSite( container, site_id, extension_ids=extension_profiles, setup_content=False, default_language=default_language, ) else: factory = container.manage_addProduct['CMFPlone'] factory.addPloneSite(site_id, create_userfolder=1) # commit the new site to the database transaction.commit() print "Added Plone Site" plone = getattr(container, site_id) setDefaultLanguageOnPortalLanguages(plone, default_language) # set the site so that the component architecture will work # properly if not pre_plone3: setSite(plone) if plone: quickinstall(plone, products_initial) # run GS profiles runProfiles(plone, profiles_initial) print "Finished" return plone
def create( container, site_id, products_initial, profiles_initial, site_replace, default_language): oids = container.objectIds() if site_id in oids: if site_replace: # Delete the site, ignoring events container._delObject(site_id, suppress_events=True) transaction.commit() logger.warning("Removed existing Plone Site") oids = container.objectIds() else: logger.warning( "A Plone Site already exists and will not be replaced") plone = getattr(container, site_id) created = False return (plone, created) # actually add in Plone if site_id not in oids: created = True if has_setup_content(): # we have to simulate the new zmi admin screen here - at # least provide: # extension_ids # setup_content (plone default is currently 'true') from Products.CMFPlone.factory import addPloneSite extension_profiles = ( 'plonetheme.classic:default', 'plonetheme.sunburst:default', ) addPloneSite( container, site_id, extension_ids=extension_profiles, setup_content=False, default_language=default_language, ) else: factory = container.manage_addProduct['CMFPlone'] factory.addPloneSite(site_id, create_userfolder=1) # commit the new site to the database transaction.commit() logger.info("Added Plone Site") plone = getattr(container, site_id) setDefaultLanguageOnPortalLanguages(plone, default_language) # set the site so that the component architecture will work # properly if not pre_plone3: setSite(plone) return (plone, created)
def setUpDefaultContent(self, app): """Add the site owner user to the root user folder and log in as that user. Create the Plone site, installing the extension profiles listed in the ``extensionProfiles`` layer class variable. Create the test user inside the site, and disable the default workflow. Note: There is no explicit tear-down of this setup operation, because all persistent changes are torn down when the stacked ZODB ``DemoStorage`` is popped. """ # Create the owner user and "log in" so that the site object gets # the right ownership information app['acl_users'].userFolderAddUser( SITE_OWNER_NAME, SITE_OWNER_PASSWORD, ['Manager'], [] ) z2.login(app['acl_users'], SITE_OWNER_NAME) # Create the site with the default set of extension profiles from Products.CMFPlone.factory import addPloneSite addPloneSite( app, PLONE_SITE_ID, title=PLONE_SITE_TITLE, setup_content=False, default_language=DEFAULT_LANGUAGE, extension_ids=self.extensionProfiles, ) # Turn off default workflow app[PLONE_SITE_ID]['portal_workflow'].setDefaultChain('') # Create the test user. (Plone)PAS does not have an API to create a # user with different userid and login name, so we call the plugin # directly. pas = app[PLONE_SITE_ID]['acl_users'] pas.source_users.addUser( TEST_USER_ID, TEST_USER_NAME, TEST_USER_PASSWORD ) for role in TEST_USER_ROLES: pas.portal_role_manager.doAssignRoleToPrincipal(TEST_USER_ID, role) # Log out again z2.logout()
def create_site(self): profiles = default_profiles if self.args.profiles: profiles.extend(self.args.profiles) addPloneSite( app, self.args.sitepath, title=self.args.title, profile_id=_DEFAULT_PROFILE, extension_ids=profiles, setup_content=True, default_language=self.args.language ) self.portal = app.unrestrictedTraverse(self.args.sitepath) return self.portal
def __call__(self): context = self.context form = self.request.form extensions = [ i['id'] for i in self.profiles()['extensions'] if i.get('selected') ] extension_ids = form.get('extension_ids', []) for extension in extension_ids: extensions.append(extension) # Dados do formulario site_id = form.get('site_id', 'portalmodelo') title = form.get('title_site', 'Portal Modelo') description = form.get('description_site', '') # Se o formulario tiver sido enviado, criaremos o site submitted = form.get('form.submitted', False) if submitted: # Criacao do site site = addPloneSite( context, site_id, title=title, description=description, profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extensions, setup_content=False, default_language='pt-br', ) # Atualizacao de propriedades do site site.manage_changeProperties( title=title, description=description, ) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form extensions = [i['id'] for i in self.profiles()['extensions'] if i.get('selected')] extension_ids = form.get('extension_ids', []) for extension in extension_ids: extensions.append(extension) # Dados do formulario site_id = form.get('site_id', 'portalmodelo') title = form.get('title_site', 'Portal Modelo') description = form.get('description_site', '') # Se o formulario tiver sido enviado, criaremos o site submitted = form.get('form.submitted', False) if submitted: # Criacao do site site = addPloneSite( context, site_id, title=title, description=description, profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extensions, setup_content=False, default_language='pt-br', ) # Atualizacao de propriedades do site site.manage_changeProperties( title=title, description=description, ) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: base_contenttypes = form.get('base_contenttypes', '--no-value--') if base_contenttypes == '--no-value--': if len(self.available_content_frameworks) == 1: base_contenttypes = self.available_content_frameworks[0] else: base_contenttypes = None site_id = form.get('site_id', 'Plone') site = addPloneSite( context, site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), base_contenttypes_profile=base_contenttypes, setup_content=form.get('setup_content', False), default_language=form.get('default_language', 'en'), ) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: site_id = form.get('site_id', 'Plone') # CSRF protect. DO NOT use auto CSRF protection for adding a site alsoProvides(self.request, IDisableCSRFProtection) # check if keyring is installed on root, disable CSRF protection # if it is because it is not installed until a plone site # is created if queryUtility(IKeyManager) is None: LOGGER.info('CSRF protection disabled on initial site ' 'creation') else: # we have a keymanager, check csrf protection manually now checkCSRF(self.request) site = addPloneSite( context, site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), setup_content=form.get('setup_content', False), default_language=form.get('default_language', 'en'), portal_timezone=form.get('portal_timezone', 'UTC') ) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: site_id = form.get('site_id', 'Plone') # CSRF protect. DO NOT use auto CSRF protection for adding a site alsoProvides(self.request, IDisableCSRFProtection) # check if keyring is installed on root, disable CSRF protection # if it is because it is not installed until a plone site # is created if queryUtility(IKeyManager) is None: LOGGER.info('CSRF protection disabled on initial site ' 'creation') else: # we have a keymanager, check csrf protection manually now checkCSRF(self.request) site = addPloneSite( context, site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), setup_content=form.get('setup_content', False), default_language=form.get('default_language', 'en'), portal_timezone=form.get('portal_timezone', 'UTC')) self.request.response.redirect(site.absolute_url()) return '' return self.index()
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: email = form.get('email', None) fullname = form.get('fullname', None) if email or fullname: # Simple naming routine site_id = None while not site_id: site_id = hashlib.md5(str(random.random()))[:5] if not context.get(site_id, None): site_id = None site = addPloneSite( context, site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), setup_content=form.get('setup_content', False), default_language=form.get('default_language', 'en'), ) # setup manager site.portal_membership.addUser(email, fullname) # setup VHM site_alias = form.get('site_id', 'Plone') site.virtual_hosting.addMapping("%s/%s"% (site_alias, site_id)) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: extension_ids = form.get('extension_ids', ()) # Criamos com conteúdo inicial extension_ids.insert(0, 'brasil.gov.portal:default') extension_ids.insert(1, 'brasil.gov.portal:initcontent') site_id = form.get('site_id', 'Plone') title_1 = form.get('title_1', '') title_2 = form.get('title_2', '') title = '%s %s' % (title_1, title_2) site = addPloneSite( context, site_id, title=title, description=form.get('description', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), setup_content=False, default_language='pt-br', ) site.manage_changeProperties(title=title) site.manage_changeProperties(title_1=title_1) site.manage_changeProperties(title_2=title_2) site.manage_changeProperties(orgao=form.get('orgao', '')) self.request.response.redirect(site.absolute_url()) return self.index()
def create_site_for(self, site_record, member_id): if site_record.is_expired() or site_record.created: raise ValueError('This site record is expired or already exists') t_registry = queryUtility(ISiteTemplateRegistry, default=_marker) if t_registry is _marker: raise ValueError('Template Registry cannot be found') extension_profiles = ['plonetheme.sunburst:default',] template_id = site_record.template template = t_registry.get_template_by_id(template_id) normalizer = queryUtility(IIDNormalizer, default=_marker) newsite_id = normalizer.normalize(site_record.id) add_ons = list(template.products) extension_profiles.extend(add_ons) portal = getSite() with Escalation(portal, 'admin'): app = aq_parent(aq_inner(portal)) newsite = addPloneSite(app, newsite_id, title="Pay2Plone Site", extension_ids=extension_profiles) user_info = self._get_current_user_info(portal, member_id) self._add_user_to_site(newsite, **user_info) # TODO: copy user property sheets from old site to new print 'site created: %s' % newsite return newsite
def test_site_creation_without_content_but_with_dexterity(self): """Test site creation without example content have dexterity installed.""" ploneSite = addPloneSite(self.app, 'ploneFoo', title='Foo', setup_content=False) qi = get_installer(ploneSite, self.request) self.assertTrue(qi.is_product_installed('plone.app.dexterity'))
def _setupPloneSite_with_genericsetup(self): '''Creates the site using GenericSetup.''' start = time() if self.base_profile != default_base_profile: self._print('Adding Plone Site (%s) ... ' % (self.base_profile,)) else: self._print('Adding Plone Site ... ') # Add Plone site if PLONE40: from Products.CMFPlone.factory import addPloneSite addPloneSite(self.app, self.id, profile_id=self.base_profile) else: factory = self.app.manage_addProduct['CMFPlone'] factory.addPloneSite(self.id, create_userfolder=1, snapshot=0, profile_id=self.base_profile) self._commit() self._print('done (%.3fs)\n' % (time()-start,))
def test_site_creation_without_content_but_with_content_types(self): """Test site creation without example content have content types.""" ploneSite = addPloneSite(self.app, 'ploneFoo', title='Foo', setup_content=False) # Folder fti = queryUtility(IDexterityFTI, name='Folder') self.assertIsNotNone(fti)
def buildSite(self, form): # CSRF protect. DO NOT use auto CSRF protection for adding a site alsoProvides(self.request, IDisableCSRFProtection) self.request.response.setHeader('Content-type', 'application/json') extension_ids = form.get('extension_ids[]', []) extension_ids.append('castle.cms:default') # TODO: barceloneta needs to just be removed if 'plonetheme.barceloneta:default' in extension_ids: extension_ids.remove('plonetheme.barceloneta:default') site_id = form.get('site_id', 'Castle') try: site = addPloneSite( self.get_creation_context(site_id), site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extension_ids, setup_content=form.get('setup_content', True), default_language=form.get('default_language', 'en'), portal_timezone=form.get('portal_timezone', 'UTC')) # delete news/events since they have default pages attached to them api.content.delete(objects=(site['news'], site['events'])) install.tiles(site, self.request) # need to reindex catalog = api.portal.get_tool('portal_catalog') catalog.manage_catalogRebuild() combine_bundles(site) if DYNAMIC_STORAGE_ENABLED: url = '{}/sites/{}'.format(self.context.absolute_url(), site_id) else: url = '{}/{}'.format(self.context.absolute_url(), site_id) # we do not allow basic auth acl_users = site.acl_users acl_users.manage_delObjects(['credentials_basic_auth']) cookie_auth = acl_users.credentials_cookie_auth # this is relative to [site]/acl_users/credentials_basic_auth # otherwise, doing /login on a site would redirect to [root]/@@secure-login cookie_auth.login_path = u'../../@@secure-login' return json.dumps({'success': True, 'url': url}) except Exception as e: LOGGER.error('Error creating site', exc_info=True) transaction.abort( ) # abort creating this site if there was an error return json.dumps({'success': False, 'msg': str(e)})
def test_not_found_when_acquiring_site(self): from Products.CMFPlone.factory import addPloneSite app = self.layer['app'] addPloneSite( app, 'other_plone', title='other plone', setup_content=False, default_language='en', ) request = self.layer['request'] base_url = request['SERVER_URL'] request.traverse('/plone/other_plone') redirect(PubAfterTraversal(request)) # raise only if MIGHT_REDIRECT request.set('MIGHT_REDIRECT', True) with self.assertRaises(NotFound) as cm: redirect(PubAfterTraversal(request))
def setup_plone(app, import_dir, version, products, ext_profiles=()): ''' create cmed instance ''' app = makerequest(app) # derivate the instance id instance_name = import_dir[import_dir.rfind('/export-') + 8:] instance_name = instance_name.split('__')[ 0] # exclude version from instance_name, if exist version = str(version).replace('.', '_') plone_id = instance_name + '__' + version # add plone site from Products.CMFPlone.factory import addPloneSite try: plone = addPloneSite(app, plone_id, extension_ids=ext_profiles) except BadRequest: # increment sub_version (plone site id) and then create plone site. instance_list = [] for obj in app.values(): if instance_name in obj.getId(): instance_list.append(obj.getId()) instance_list.sort() last = instance_list[-1] if last.count( '_') == 3: # second migration in some version (eg unica__0_8) new_site_id = last + '_1' else: # and so on (eg unica__0_8_2) to_increment = int(last[-1]) + 1 new_site_id = last[:-1] + str(to_increment) plone = addPloneSite(app, new_site_id, extension_ids=ext_profiles) qit = plone.portal_quickinstaller # installs wres.policy ids = [x['id'] for x in qit.listInstallableProducts(skipInstalled=1)] for product in products: if product in ids: qit.installProduct(product) return plone
def setup_plone(app, import_dir, version, products, ext_profiles=()): ''' create cmed instance ''' app = makerequest(app) # derivate the instance id instance_name = import_dir[import_dir.rfind('/export-')+8:] instance_name = instance_name.split('__')[0] # exclude version from instance_name, if exist version = str(version).replace('.', '_') plone_id = instance_name + '__' + version # add plone site from Products.CMFPlone.factory import addPloneSite try: plone = addPloneSite(app, plone_id, extension_ids=ext_profiles) except BadRequest: # increment sub_version (plone site id) and then create plone site. instance_list = [] for obj in app.values(): if instance_name in obj.getId(): instance_list.append(obj.getId()) instance_list.sort() last = instance_list[-1] if last.count('_') == 3: # second migration in some version (eg unica__0_8) new_site_id = last + '_1' else: # and so on (eg unica__0_8_2) to_increment = int(last[-1]) + 1 new_site_id = last[:-1] + str(to_increment) plone = addPloneSite(app, new_site_id, extension_ids=ext_profiles) qit = plone.portal_quickinstaller # installs wres.policy ids = [ x['id'] for x in qit.listInstallableProducts(skipInstalled=1) ] for product in products: if product in ids: qit.installProduct(product) return plone
def afterSetUp(self): PloneTestCase.afterSetUp(self) self.setRoles(["Manager"]) addPloneSite(self.app, "login_portal", content_profile_id="Products.ATContentTypes:default") addPloneSite(self.app, "another_portal", content_profile_id="Products.ATContentTypes:default") self.browser = Browser(self.app) self.browser.handleErrors = False # Don't get HTTP 500 pages self.login_portal = self.app.login_portal # logins go here self.another_portal = self.app.another_portal # another portal # The extra portals do not get a member setup from the base class. # Add our user to the other portals to simulate an ldap environment. for portal in (self.login_portal, self.another_portal): portal.acl_users.source_users.addUser(TEST_USER_ID, TEST_USER_NAME, TEST_USER_PASSWORD) for role in TEST_USER_ROLES: portal.acl_users.portal_role_manager.doAssignRoleToPrincipal(TEST_USER_ID, role) registry = self.login_portal.portal_registry # Configure the login portal to allow logins from our sites. registry["plone.allow_external_login_sites"] = (self.portal.absolute_url(), self.another_portal.absolute_url()) # Configure our sites to use the login portal for logins and logouts login_portal_url = self.login_portal.absolute_url() for portal in (self.portal, self.another_portal): reg = portal.portal_registry reg["plone.external_login_url"] = login_portal_url + "/login" reg["plone.external_logout_url"] = login_portal_url + "/logout" # Configure all sites to use a shared secret and set cookies per path # (normally they would have different domains.) for portal in (self.portal, self.login_portal, self.another_portal): session = portal.acl_users.session session._shared_secret = "secret" session.path = portal.absolute_url_path() # Turn on self-registration self.portal.manage_permission("Add portal member", roles=["Manager", "Anonymous"], acquire=0) transaction.commit()
def testPlonesiteWithUnicodeTitle(self): TITLE = 'Ploné' ploneSite = addPloneSite(self.app, 'ploneFoo', title=TITLE, setup_content=False) ploneSiteTitleProperty = ploneSite.getProperty('title') # CMF stores title as string only so Plone should keep the same track self.assertTrue(isinstance(ploneSiteTitleProperty, str)) self.assertEqual(ploneSiteTitleProperty, TITLE) ploneSiteTitle = ploneSite.Title() self.assertTrue(isinstance(ploneSiteTitle, str)) self.assertEqual(ploneSiteTitle, TITLE)
def setUpDefaultContent_AdditionalPage(self, app, additional_page_id, additional_page_title): z2.login(app['acl_users'], SITE_OWNER_NAME) from Products.CMFPlone.factory import addPloneSite # Set up the second page with another ID here. addPloneSite( app, additional_page_id, title=additional_page_title, setup_content=False, default_language=DEFAULT_LANGUAGE, extension_ids=self.extensionProfiles, ) app[additional_page_id]['portal_workflow'].setDefaultChain('') pas = app[additional_page_id]['acl_users'] pas.source_users.addUser(TEST_USER_ID, TEST_USER_NAME, TEST_USER_PASSWORD) for role in TEST_USER_ROLES: pas.portal_role_manager.doAssignRoleToPrincipal(TEST_USER_ID, role) z2.logout()
def manage_addRhaptosSite(self, id, title='', description='', create_userfolder=1, email_from_address='', email_from_name='Rhaptos', validate_email=0, dbauser='******', dbapass=None, dbuser='******', dbpass=None, dbname='repository', dbserver=None, dbport=None, RESPONSE=None): """ Rhaptos Site factory """ temp_id = 'DB_OPTS_TEMP' if not hasattr(self.aq_parent.aq_parent, temp_id): self.aq_parent.aq_parent.manage_addFolder(temp_id) root = self.aq_parent.aq_parent[temp_id] root._dbopts = {} root._dbopts['admin'] = dbauser root._dbopts['adminpass'] = dbapass root._dbopts['user'] = dbuser root._dbopts['userpass'] = dbpass root._dbopts['dbname'] = dbname root._dbopts['server'] = dbserver root._dbopts['port'] = dbport #manage_addSite(self, id, title, description, create_userfolder, email_from_address, email_from_name, validate_email, custom_policy='Rhaptos Site', RESPONSE=RESPONSE) addPloneSite(self, id, title, description, create_userfolder, email_from_address, email_from_name, validate_email, RESPONSE=RESPONSE, extension_ids=('RhaptosSite:rhaptos-default', ))
def testPlonesiteWithoutUnicodeTitle(self): TITLE = 'Plone' ploneSite = addPloneSite(self.app, 'ploneFoo', title=TITLE, setup_content=False) ploneSiteTitleProperty = ploneSite.getProperty('title') # CMF stores title as string only so Plone should keep the same track self.assertTrue(isinstance(ploneSiteTitleProperty, str)) self.assertEqual(ploneSiteTitleProperty, TITLE) ploneSiteTitle = ploneSite.Title() self.assertTrue(isinstance(ploneSiteTitle, str)) self.assertEqual(ploneSiteTitle, TITLE)
def setup_plone_site(self): config = self.config ext_profiles = list(EXTENSION_PROFILES) ext_profiles.extend(BASE_PROFILES) return addPloneSite( self.context, config['admin_unit_id'].encode('utf-8'), title=config['title'], profile_id=_DEFAULT_PROFILE, extension_ids=ext_profiles, setup_content=False, default_language=config.get('language', 'de-ch'), )
def setup(app): sitename = 'Plone' admin_user = '******' # This is needed to get Plone into an usable state so that invokeFactory actually works from Testing import makerequest root = makerequest.makerequest(app) site = root.get(sitename) # Create site if it does not exist if site is None: from Products.CMFPlone.factory import addPloneSite from Products.CMFPlone.factory import _DEFAULT_PROFILE site = addPloneSite( root, sitename, title='Holland Alumni Portal', profile_id=_DEFAULT_PROFILE, extension_ids=( 'plonetheme.classic:default', 'plonetheme.sunburst:default', 'plone.app.toolbar:default', ), setup_content=True, default_language='en' ) try: admin = root.acl_users.getUserById(admin_user) admin = admin.__of__(site.acl_users) except AttributeError: print "Could not elevate priviliges to user " + admin_user pass from AccessControl.SecurityManagement import newSecurityManager newSecurityManager(None, admin) from zope.site.hooks import setHooks from zope.site.hooks import setSite setHooks() setSite(site) site.setupCurrentSkin(site.REQUEST) # This is needed to get Plone into an usable state so that invokeFactory actually works return site
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: site = addPloneSite( context, 'Plone', profile_id=_DEFAULT_PROFILE, extension_ids=form.get('extension_ids', (u'intranett.policy:default', u'intranett.policy:content')), setup_content=False, default_language=form.get('language', 'no'), ) return self.request.response.redirect(site.absolute_url()) return self.index()
def install(self, app, site_id, title=None, language='en', extension_profiles=EXTENSION_PROFILES): if title is None: title = self.title extension_profiles = list(extension_profiles) extension_profiles.extend(self.profiles) return addPloneSite( app, site_id, title=title, profile_id=self.base, extension_ids=extension_profiles, setup_content=False, default_language=language)
def __call__(self): context = self.context form = self.request.form submitted = form.get('form.submitted', False) if submitted: site_id = form.get('site_id', 'Plone') site = addPloneSite( context, site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=form.get('extension_ids', ()), setup_content=form.get('setup_content', False), default_language=form.get('default_language', 'en'), ) self.request.response.redirect(site.absolute_url()) return self.index()
def __call__(self): context = self.context form = self.request.form extension_ids = form.get('extension_ids', []) extension_ids.insert(0, 'brasil.gov.portal:default') # Criamos com conteúdo inicial extension_ids.insert(1, 'brasil.gov.portal:initcontent') # Dados do formulario orgao = form.get('orgao', '') url_orgao = form.get('url_orgao', '') title_1 = form.get('title_1', '') title_2 = form.get('title_2', '') title = '%s %s' % (title_1, title_2) # Se o formulario tiver sido enviado, criaremos o site submitted = form.get('form.submitted', False) if submitted: alsoProvides(self.request, IDisableCSRFProtection) site_id = form.get('site_id', 'portal') # Criacao do site site = addPloneSite( context, site_id, title=title, description=form.get('description', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extension_ids, setup_content=False, default_language='pt-br', ) # Atualizacao de propriedades do site site.manage_changeProperties( title=title, title_1=title_1, title_2=title_2, orgao=orgao, ) pprop = getToolByName(self.context, 'portal_properties') configs = getattr(pprop, 'brasil_gov', None) configs.manage_changeProperties(url_orgao=url_orgao) self.request.response.redirect(site.absolute_url()) return self.index()
def install(self, app, site_id, title=None, language='en', extension_profiles=EXTENSION_PROFILES): if title is None: title = self.title extension_profiles = list(extension_profiles) extension_profiles.extend(self.profiles) return addPloneSite(app, site_id, title=title, profile_id=self.base, extension_ids=extension_profiles, setup_content=False, default_language=language)
def __call__(self): context = self.context form = self.request.form extension_ids = form.get('extension_ids', []) extension_ids.insert(0, 'brasil.gov.portal:default') # FIXME: Criamos com conteúdo inicial # extension_ids.insert(1, 'brasil.gov.portal:initcontent') # Dados do formulario orgao = form.get('orgao', '') url_orgao = form.get('url_orgao', '') title_1 = form.get('title_1', '') title_2 = form.get('title_2', '') title = '%s %s' % (title_1, title_2) # Se o formulario tiver sido enviado, criaremos o site submitted = form.get('form.submitted', False) if submitted: alsoProvides(self.request, IDisableCSRFProtection) site_id = form.get('site_id', 'portal') # Criacao do site site = addPloneSite( context, site_id, title=title, description=form.get('description', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extension_ids, setup_content=False, default_language='pt-br', ) # Atualizacao de propriedades do site site.manage_changeProperties( title=title, title_1=title_1, title_2=title_2, orgao=orgao, ) pprop = getToolByName(self.context, 'portal_properties') configs = getattr(pprop, 'brasil_gov', None) configs.manage_changeProperties(url_orgao=url_orgao) self.request.response.redirect(site.absolute_url()) return self.index()
#language = "en-jm" default_extension_profiles = ('plone.app.caching:default', 'plonetheme.barceloneta:default', 'incrementic.plonesite:default') print("----------> Initiating install of {} site".format(site_id)) if site_id in app.objectIds(): print "The site was already installed" sys.exit(1) site = addPloneSite( app, site_id, title=SITE_TITLE, profile_id=_DEFAULT_PROFILE, extension_ids=default_extension_profiles, setup_content=True, # default_language=language, ) # Sets the current site as the active site print("----------> Setting {} as the active site".format(site_id)) setSite(app[site_id]) registry = getUtility(IRegistry) navigation_settings = registry.forInterface(INavigationSchema, prefix='plone') image_settings = registry.forInterface(IImagingSchema, prefix='plone') site_settings = registry.forInterface(ISiteSchema, prefix='plone') # set up navigation settings print("----------> Setting Navigation settings")
def __call__(self): form = self.request.form session = create_session() policy_id = form['policy'] client_registry = getUtility(IClientConfigurationRegistry) config = client_registry.get_policy(policy_id) # drop sql tables if form.get('first', False) and config.get('purge_sql', False): self.drop_sql_tables(session) ext_profiles = list(EXTENSION_PROFILES) if config.get('base_profile', None): ext_profiles.append(config.get('base_profile')) # create plone site site = addPloneSite( self.context, form['client_id'], title=form['title'], profile_id=_DEFAULT_PROFILE, extension_ids=ext_profiles, setup_content=False, default_language=config.get('language', 'de-ch'), ) # ldap stool = getToolByName(site, 'portal_setup') if form.get('ldap', False): stool = getToolByName(site, 'portal_setup') stool.runAllImportStepsFromProfile('profile-%s' % form.get('ldap')) # Configure credentials from JSON file at # ~/.opengever/ldap/{hostname}.json configure_ldap_credentials(site) acl_users = getToolByName(site, 'acl_users') plugins = acl_users.plugins # disable source_groups when using ldap for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'source_groups') except KeyError: pass # deactivate recursive groups for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'recursive_groups') except KeyError: pass # move ldap up plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) if form.get('first', False) and form.get('import_users', False): print '===== SYNC LDAP ====' class Object(object): pass # Import LDAP users and groups options = Object() options.site_root = '/' + form['client_id'] options.update_syncstamp = False sync_ldap.run_import(self.context, options) if form.get('configsql'): # register the client in the ogds # is the client already configured? -> delete it clients = session.query(Client).filter_by( client_id=form['client_id']).all() if clients: session.delete(clients[0]) # groups must exist users_groups = session.query(Group).filter_by( groupid=form['group']) inbox_groups = session.query(Group).filter_by( groupid=form['inbox_group']) try: users_group = users_groups[0] except IndexError: raise SetupError("User group '%s' could not be found." % form['group']) try: inbox_group = inbox_groups[0] except IndexError: raise SetupError("Inbox group '%s' could not be found." % form['inbox_group']) active = bool(form.get('active', False)) client = Client(form['client_id'], enabled=active, title=form['title'], ip_address=form['ip_address'], site_url=form['site_url'], public_url=form['public_url'], ) client.users_group = users_group client.inbox_group = inbox_group session.add(client) # create the admin user in the ogds if he not exist # and add it to the specified user_group # so we avoid a constraintError in the choice fields if session.query(User).filter_by(userid=ADMIN_USER_ID).count() == 0: og_admin_user = User(ADMIN_USER_ID, firstname='OG', lastname='Administrator', active=True) session.add(og_admin_user) else: og_admin_user = session.query(User).filter_by( userid=ADMIN_USER_ID).first() og_admin_user.active = True users_group = session.query(Group).filter_by( groupid=form['group']).first() if og_admin_user not in users_group.users: users_group.users.append(og_admin_user) # set the client id in the registry client_id = form['client_id'].decode('utf-8') registry = getUtility(IRegistry) proxy = registry.forInterface(IClientConfiguration) proxy.client_id = form['client_id'].decode('utf-8') # set the mail domain in the registry registry = getUtility(IRegistry) proxy = registry.forInterface(IMailSettings) proxy.mail_domain = form['mail_domain'].decode('utf-8') mail_from_address = self.get_mail_from_address() site.manage_changeProperties({'email_from_address': mail_from_address, 'email_from_name': client_id}) # set global Member role for the client users group site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['group']) # set global Member role for readers group if form['reader_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['reader_group']) # set Role Manager role for rolemanager group if form['rolemanager_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Role Manager', form['rolemanager_group']) # provide the repository root for opengever.setup:default repository_root = config.get('repository_root', None) if repository_root: self.request.set('repository_root', repository_root) # import the defaul generic setup profiles if needed stool = getToolByName(site, 'portal_setup') for profile in config.get('additional_profiles', ()): stool.runAllImportStepsFromProfile('profile-%s' % profile) # set the site title site.manage_changeProperties(title=form['title']) # REALLY set the language - the plone4 addPloneSite is really # buggy with languages. langCP = getAdapter(site, ILanguageSelectionSchema) langCP.default_language = 'de-ch' # the og_admin_user is not longer used so we set him to inactive og_admin_user.active = False return 'ok'
def bang(event): is_bigbang_active = os.getenv("ACTIVE_BIGBANG", False) if is_bigbang_active == "True": app = Zope2.app() app = makerequest(app) app.REQUEST["PARENTS"] = [app] setRequest(app.REQUEST) container = app.unrestrictedTraverse("/") site_id = os.getenv("SITE_ID", "Plone") oids = container.objectIds() if site_id not in oids and "/" not in site_id: acl_users = app.acl_users user = acl_users.getUser("admin") if user: user = user.__of__(acl_users) newSecurityManager(None, user) logger.info("Retrieved the admin user") else: logger.error("No admin user") return # install Plone site extension_ids = tuple( [ extension.strip() for extension in os.getenv( "PLONE_EXTENSION_IDS", _default_packages_for_plone_version() ).split(",") ] ) default_language = os.getenv("DEFAULT_LANGUAGE", "en") addPloneSite( container, site_id, title="{0} site".format(site_id), profile_id=_DEFAULT_PROFILE, extension_ids=extension_ids, setup_content=True, default_language=default_language, ) plone = getattr(container, site_id) setSite(plone) noSecurityManager() transaction.commit() logger.info("Plone Site created") else: logger.info( "A Plone Site '{0}' already exists and will not be replaced".format( site_id ) ) admin_password = os.getenv("ADMIN_PASSWORD", None) if admin_password and hasattr(app.acl_users, 'users'): # update zope admin password users = app.acl_users.users users.updateUserPassword("admin", admin_password) transaction.commit() logger.info("Admin password updated") try: plone = app.unrestrictedTraverse(site_id) notify(DarwinStartedEvent(plone)) except KeyError as err: logger.info("Site not found at path " + site_id)
admin_pw = grampg.PasswordGenerator().of().between( 100, 200, 'letters').done().generate() uf = app.acl_users user = uf.getUser('admin') #uf._doChangeUser('admin', admin_pw, ('Manager',), ()) newSecurityManager(None, user.__of__(uf)) if 'xml-director' in app.objectIds(): app.manage_delObjects('xml-director') addPloneSite(app, 'xml-director', create_userfolder=True, extension_ids=[ 'plonetheme.sunburst:default', 'xmldirector.plonecore:democontent', 'pp.client.plone:default' ]) site = app['xml-director'] site.manage_delObjects(['events', 'news', 'Members']) pr = site.portal_registration pr.addMember('demo', 'demo', roles=('Site Administrator', )) registry = getUtility(IRegistry) settings = registry.forInterface(IWebdavSettings) settings.webdav_url = webdav_url settings.webdav_username = u'admin' settings.webdav_password = u'admin' settings = registry.forInterface(IPPClientPloneSettings)
from zope.component.hooks import setSite from Products.CMFPlone.factory import addPloneSite import transaction ADMIN_USER = '******' ADMIN_PASSWD = 'admin' app.acl_users._doAddUser(ADMIN_USER, ADMIN_PASSWD, ['Manager'], []) if 'Plone' not in app.objectIds(): site_id = 'Plone' addPloneSite(app, site_id) plone = getattr(app, site_id) setSite(plone) stool = plone.portal_setup for profile in [ 'profile-plone.app.contenttypes:default', 'profile-plonetheme.barceloneta:default', 'profile-plone.restapi:default', ]: try: stool.runAllImportStepsFromProfile( profile, dependency_strategy='reapply') except: stool.runAllImportStepsFromProfile(profile) transaction.commit()
def setupSite(self, with_content=False): portal_id = 'et-%s' % DateTime().strftime('%d.%m.%y-%H%M%S') profiles = ['plonetheme.sunburst:default', 'eteaching.policy:default'] addPloneSite(self.context, portal_id, create_userfolder=True, extension_ids=profiles) site = self.context[portal_id] self.request.response.redirect(self.context.getId() + '/' + portal_id)
def __call__(self): form = self.request.form session = create_session() policy_id = form['policy'] client_registry = getUtility(IClientConfigurationRegistry) config = client_registry.get_policy(policy_id) # drop sql tables if form.get('first', False) and config.get('purge_sql', False): self.drop_sql_tables(session) ext_profiles = list(EXTENSION_PROFILES) if config.get('base_profile', None): ext_profiles.append(config.get('base_profile')) # create plone site site = addPloneSite( self.context, form['client_id'], title=form['title'], profile_id=_DEFAULT_PROFILE, extension_ids=ext_profiles, setup_content=False, default_language=config.get('language', 'de-ch'), ) # ldap stool = getToolByName(site, 'portal_setup') if form.get('ldap', False): stool = getToolByName(site, 'portal_setup') stool.runAllImportStepsFromProfile('profile-%s' % form.get('ldap')) # Configure credentials from JSON file at # ~/.opengever/ldap/{hostname}.json configure_ldap_credentials(site) acl_users = getToolByName(site, 'acl_users') plugins = acl_users.plugins # disable source_groups when using ldap for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'source_groups') except KeyError: pass # deactivate recursive groups for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'recursive_groups') except KeyError: pass # move ldap up plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) if form.get('first', False) and form.get('import_users', False): print '===== SYNC LDAP ====' class Object(object): pass # Import LDAP users and groups options = Object() options.site_root = '/' + form['client_id'] options.update_syncstamp = False sync_ldap.run_import(self.context, options) if form.get('configsql'): # register the client in the ogds # is the client already configured? -> delete it clients = session.query(Client).filter_by( client_id=form['client_id']).all() if clients: session.delete(clients[0]) # groups must exist users_groups = session.query(Group).filter_by( groupid=form['group']) inbox_groups = session.query(Group).filter_by( groupid=form['inbox_group']) try: users_group = users_groups[0] except IndexError: raise SetupError("User group '%s' could not be found." % form['group']) try: inbox_group = inbox_groups[0] except IndexError: raise SetupError("Inbox group '%s' could not be found." % form['inbox_group']) active = bool(form.get('active', False)) client = Client( form['client_id'], enabled=active, title=form['title'], ip_address=form['ip_address'], site_url=form['site_url'], public_url=form['public_url'], ) client.users_group = users_group client.inbox_group = inbox_group session.add(client) # create the admin user in the ogds if he not exist # and add it to the specified user_group # so we avoid a constraintError in the choice fields if session.query(User).filter_by(userid=ADMIN_USER_ID).count() == 0: og_admin_user = User(ADMIN_USER_ID, firstname='OG', lastname='Administrator', active=True) session.add(og_admin_user) else: og_admin_user = session.query(User).filter_by( userid=ADMIN_USER_ID).first() og_admin_user.active = True users_group = session.query(Group).filter_by( groupid=form['group']).first() if og_admin_user not in users_group.users: users_group.users.append(og_admin_user) # set the client id in the registry client_id = form['client_id'].decode('utf-8') registry = getUtility(IRegistry) proxy = registry.forInterface(IClientConfiguration) proxy.client_id = form['client_id'].decode('utf-8') # set the mail domain in the registry registry = getUtility(IRegistry) proxy = registry.forInterface(IMailSettings) proxy.mail_domain = form['mail_domain'].decode('utf-8') mail_from_address = self.get_mail_from_address() site.manage_changeProperties({ 'email_from_address': mail_from_address, 'email_from_name': client_id }) # set global Member role for the client users group site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['group']) # set global Member role for readers group if form['reader_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['reader_group']) # set Role Manager role for rolemanager group if form['rolemanager_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Role Manager', form['rolemanager_group']) # provide the repository root for opengever.setup:default repository_root = config.get('repository_root', None) if repository_root: self.request.set('repository_root', repository_root) # import the defaul generic setup profiles if needed stool = getToolByName(site, 'portal_setup') for profile in config.get('additional_profiles', ()): stool.runAllImportStepsFromProfile('profile-%s' % profile) # set the site title site.manage_changeProperties(title=form['title']) # REALLY set the language - the plone4 addPloneSite is really # buggy with languages. langCP = getAdapter(site, ILanguageSelectionSchema) langCP.default_language = 'de-ch' # the og_admin_user is not longer used so we set him to inactive og_admin_user.active = False return 'ok'
from plone import namedfile from plone.registry.interfaces import IRegistry from plone.app.textfield.value import RichTextValue from zope.component import getUtility from plone.registry.interfaces import IRegistry from Products.CMFPlone.factory import addPloneSite from AccessControl.SecurityManagement import newSecurityManager uf = app.acl_users user = uf.getUser('admin') newSecurityManager(None, user.__of__(uf)) if 'plone' in app.objectIds(): app.manage_delObjects(['plone']) addPloneSite(app, 'plone', extension_ids=['plonetheme.barceloneta:default', 'zopyx.ipsumplone:default', 'Products.PloneFormGen:default', 'plone.app.multilingual:default', 'plone.app.multilingual:default', 'Products.PloneFormGen:default', 'zopyx.plone.smashdocs:default']) plone.api.user.create(username='******', password='******', roles=('Member', 'Editor'), email="*****@*****.**") plone.api.user.create(username='******', password='******', roles=('Member', 'Reader'), email="*****@*****.**") plone.api.user.create(username='******', password='******', roles=('Member', 'Manager'), email="*****@*****.**") plone.api.user.create(username='******', password='******', roles=('Member', 'Site Administrator'), email="*****@*****.**") site = app['plone'] site.restrictedTraverse('@@demo-content')() fp = site['front-page'] fp.setTitle(u'Plone 5 demo site') fp.setDescription(u'Welcome to the Plone 5 demo website - provided by ZOPYX. Feel free to play around with Plone 5!') with open('data/frontpage.html', 'rb') as handle: fp.text = RichTextValue(unicode(handle.read(), 'utf8'), 'text/html', 'text/html') fp.reindexObject()
def create_target_site(app, name): return addPloneSite(app, name, extension_ids=(POLICY, ))
from plone import api from plone.dexterity.interfaces import IDexterityFTI from Products.CMFPlone.factory import addPloneSite from zope.component import queryUtility import transaction default_extension_profiles = ( 'plone.app.caching:default', 'plonetheme.barceloneta:default', 'collective.folderishtypes.dx:default', 'plone.restapi:default', 'kitconcept.voltodemo:default' ) addPloneSite(app, 'Plone', extension_ids=default_extension_profiles) # Remove non-folder types from navigation api.portal.set_registry_record(name="plone.nonfolderish_tabs", value=False) # Add Tiles behavior to Document FTI fti = queryUtility(IDexterityFTI, name='Document', context=app['Plone']) behavior_list = [a for a in fti.behaviors] behavior_list.append('plone.tiles') fti.behaviors = tuple(behavior_list) transaction.commit()