def configura_servicos(portal): folder = portal.servicos behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(constrains.ENABLED) # Permitimos apenas links behavior.setImmediatelyAddableTypes(['Link']) folder.setLayout('summary_view')
def __iter__(self): for item in self.previous: pathkey = self.pathkey(*item.keys())[0] constrainkey = self.constrainkey(*item.keys())[0] if not pathkey or not constrainkey or \ constrainkey not in item: # not enough info yield item continue obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None) if obj is None: # path doesn't exist yield item continue constr = ISelectableConstrainTypes(obj, None) if constr is not None: constrain_dict = item[constrainkey] mode = constrain_dict['mode'] allowedtypes = constrain_dict['locallyallowedtypes'] addabletypes = constrain_dict['immediatelyaddabletypes'] if mode not in (constrains.ACQUIRE, constrains.DISABLED, constrains.ENABLED): # mode not valid [-1, 0, 1] yield item continue constr.setConstrainTypesMode(mode) if allowedtypes: constr.setLocallyAllowedTypes(allowedtypes) if addabletypes: constr.setImmediatelyAddableTypes(addabletypes) yield item
def createFolderAndContents(folder_directori, folder_data): # Create folder folder_props = { 'title': folder_data[0], 'checkConstraints': False, 'exclude_from_nav': folder_data[2], 'allow_discussion': folder_data[3] } if folder_data[5] is not None: folder_props['layout'] = folder_data[5] folder = createContentInContainer(folder_directori, folder_data[1], **folder_props) behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(folder_data[4]) behavior.setImmediatelyAddableTypes(folder_data[4]) folder.reindexObject() # Create a contents for folder_content in folder_data[7]: createContentInFolder(folder, folder_content) if folder_data[6] is not None: folder.setDefaultPage(folder_data[6])
def configura_menu_relevancia(portal): folder = portal['menu-de-relevancia'] behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(constrains.ENABLED) # Permitimos apenas links behavior.setImmediatelyAddableTypes(['Link']) folder.setLayout('summary_view')
def configura_menu_apoio(portal): folder = portal["menu-de-apoio"] behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(constrains.ENABLED) # Permitimos apenas links behavior.setImmediatelyAddableTypes(["Link"]) folder.setLayout("folder_summary_view")
def post_install(context): """Post install script""" #if context.readDataFile('polklibraryslider_default.txt') is None: # return print "Running Post Install" # Add Group plone.app.portlets.ManagePortlets # plone.api.group.create(groupname='slider_image_editor', title='Slider Image Editor', description='Can edit and manage slider content') # Add Slider Folder site = api.portal.get() obj = api.content.create( type='Folder', title='Slider Images', description= 'This folder contains all the banner sliding images of your site. DO NOT DELETE, MOVE OR RENAME!', container=site) api.content.transition(obj, 'publish') obj.exclude_from_nav = True behavior = ISelectableConstrainTypes(obj) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setLocallyAllowedTypes(('linkable_image', )) behavior.setImmediatelyAddableTypes(('linkable_image', )) obj.reindexObject()
def _createObjects(parent, new_object): LOG.info("Creating %s in %s" % (new_object, parent)) existing = parent.objectIds() if new_object['id'] in existing: LOG.info("%s exists, skipping" % new_object['id']) else: _createObjectByType( new_object['type'], parent, id=new_object['id'], title=new_object['title'] ) LOG.info("Now to modify the new_object...") obj = parent.get(new_object['id'], None) if obj is None: msg = "can't get new_object %s to modify it!" % new_object['id'] LOG.info(msg) else: if obj.Type() != new_object['type']: LOG.info("types don't match!") else: if 'layout' in new_object: obj.setLayout(new_object['layout']) if 'exclude_from_nav' in new_object: obj.setExcludeFromNav(new_object['exclude_from_nav']) obj.reindexObject() aspect = ISelectableConstrainTypes(obj) addable = aspect.getImmediatelyAddableTypes() if "collective.history.useraction" not in addable: aspect.setConstrainTypesMode(1) # select manually aspect.setImmediatelyAddableTypes(["collective.history.useraction"])
def render(self): pc = api.portal.get_tool(name='portal_catalog') communities = pc.searchResults(portal_type='ulearn.community') for community in communities: community = community.getObject() if 'discussion' not in community.objectIds(): # Create the default discussion container and set title discussion = createContentInContainer(community, 'Folder', title='discussion', checkConstraints=False) discussion.setTitle(community.translate(_(u'Discussion'))) discussion.setLayout('discussion_folder_view') alsoProvides(discussion, IDiscussionFolder) behavior = ISelectableConstrainTypes(discussion) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(('ulearn.discussion', 'Folder')) behavior.setImmediatelyAddableTypes(('ulearn.discussion', 'Folder')) # Blacklist the right column portlets on discussion right_manager = queryUtility(IPortletManager, name=u'plone.rightcolumn') blacklist = getMultiAdapter((discussion, right_manager), ILocalPortletAssignmentManager) blacklist.setBlacklistStatus(CONTEXT_CATEGORY, True) discussion.reindexObject() logger.info('Created discussion folder in {}'.format(community.absolute_url())) return 'Done.'
def render(self): try: from plone.protect.interfaces import IDisableCSRFProtection alsoProvides(self.request, IDisableCSRFProtection) except: pass portal = api.portal.get() pc = api.portal.get_tool(name='portal_catalog') communities = pc.searchResults(portal_type='ulearn.community') text = [] for community_brain in communities: # We assume that there will be only communities in Portal Site Root community = portal[community_brain.id] # Set on them the allowable content types behavior = ISelectableConstrainTypes(community['documents']) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes( ('Document', 'File', 'Folder', 'Link', 'Image', 'privateFolder', 'ulearn.video', 'ulearn.video_embed')) behavior.setImmediatelyAddableTypes( ('Document', 'File', 'Folder', 'Link', 'Image', 'privateFolder', 'ulearn.video', 'ulearn.video_embed')) community.reindexObject() text.append('Migrated types community {}\n'.format( community.absolute_url())) return ''.join(text) + '\nDone!'
def test_immediatelyAllowedTypesInvalidValuesGetFiltered(self): behavior = ISelectableConstrainTypes(self.folder) behavior.setConstrainTypesMode(constrains.ENABLED) self.folder.immediately_addable_types = self.types_id_subset + \ ['invalid'] self.assertEqual(self.types_id_subset, behavior.getImmediatelyAddableTypes())
def render(self): try: from plone.protect.interfaces import IDisableCSRFProtection alsoProvides(self.request, IDisableCSRFProtection) except: pass portal = api.portal.get() pc = api.portal.get_tool(name='portal_catalog') communities = pc.searchResults(portal_type='ulearn.community') text = [] for community_brain in communities: # We assume that there will be only communities in Portal Site Root community = portal[community_brain.id] # Set on them the allowable content types behavior = ISelectableConstrainTypes(community['documents']) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(('Document', 'File', 'Folder', 'Link', 'Image', 'privateFolder', 'ulearn.video', 'ulearn.video_embed')) behavior.setImmediatelyAddableTypes(('Document', 'File', 'Folder', 'Link', 'Image', 'privateFolder', 'ulearn.video', 'ulearn.video_embed')) community.reindexObject() text.append('Migrated types community {}\n'.format(community.absolute_url())) return ''.join(text) + '\nDone!'
def test_immediatelyAllowedTypesInvalidValuesGetFiltered(self): behavior = ISelectableConstrainTypes(self.folder) behavior.setConstrainTypesMode(constrains.ENABLED) self.folder.immediately_addable_types = self.types_id_subset + \ ['invalid'] self.assertEqual( self.types_id_subset, behavior.getImmediatelyAddableTypes())
def createContentInFolder(folder_directori, folder_content): # Create content if folder_content[1] != "Folder": content_props = { 'title': folder_content[0], 'checkConstraints': False, 'exclude_from_nav': folder_content[2], 'allow_discussion': folder_content[3] } if folder_content[6] is not None: content_props['description'] = folder_content[6] if folder_content[7] is not None: content_props['text'] = IRichText['text'].fromUnicode( folder_content[7]) if folder_content[5] is not None: content_props['layout'] = folder_content[5] content = createContentInContainer(folder_directori, folder_content[1], **content_props) if folder_content[4] is not None: behavior = ISelectableConstrainTypes(content) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(folder_content[4]) behavior.setImmediatelyAddableTypes(folder_content[4]) else: createFolderAndContents(folder_directori, folder_content)
def configura_imagens(portal): folder = portal.imagens behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(constrains.ENABLED) # Permitimos apenas imagens behavior.setImmediatelyAddableTypes(['Image']) folder.setLayout('summary_view')
def set_constraintypes_config(self, obj, config): self.assertEquals({'mode', 'locally allowed', 'immediately addable'}, set(config)) ctypes = ISelectableConstrainTypes(obj) ctypes.setConstrainTypesMode(config['mode']) ctypes.setLocallyAllowedTypes(config['locally allowed']) ctypes.setImmediatelyAddableTypes(config['immediately addable'])
def set_constraintypes_config(self, obj, config): self.assertEquals( {'mode', 'locally allowed', 'immediately addable'}, set(config)) ctypes = ISelectableConstrainTypes(obj) ctypes.setConstrainTypesMode(config['mode']) ctypes.setLocallyAllowedTypes(config['locally allowed']) ctypes.setImmediatelyAddableTypes(config['immediately addable'])
def initialize_servei(serveitic, event): # Configure portlets assignments = get_portlet_assignments( serveitic, 'plone.leftcolumn') assignments['banners_global'] = BannersAssignment(banner_type=u"Global") assignments['banners_local'] = BannersAssignment(banner_type=u"Local") assignments = get_portlet_assignments( serveitic, 'genweb.portlets.HomePortletManager3') assignments['notificacions'] = NotificacionsAssignment() assignments = get_portlet_assignments( serveitic, 'genweb.portlets.HomePortletManager4') assignments['problemes'] = ProblemesAssignment() assignments = get_portlet_assignments( serveitic, 'genweb.portlets.HomePortletManager5') assignments['indicadors'] = IndicadorsAssignment() # Create folder structure for folder_data in folder_structure: folder_props = { 'title': folder_data[0], 'checkConstraints': False, 'exclude_from_nav': folder_data[2], 'allow_discussion': folder_data[3]} if folder_data[5] is not None: folder_props['layout'] = folder_data[5] folder = createContentInContainer( serveitic, folder_data[1], **folder_props) for folder_content in folder_data[6]: content_props = { 'title': folder_content[0], 'checkConstraints': False, 'exclude_from_nav': folder_content[2], 'allow_discussion': folder_content[3]} if folder_content[5] is not None: content_props['layout'] = folder_content[5] content = createContentInContainer( folder, folder_content[1], **content_props) if folder_content[4] is not None: behavior = ISelectableConstrainTypes(content) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(folder_content[4]) behavior.setImmediatelyAddableTypes(folder_content[4]) behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(folder_data[4]) behavior.setImmediatelyAddableTypes(folder_data[4]) folder.reindexObject() # Mark ServeiTIC as initialized to prevent previous folder creations from # triggering the modify event alsoProvides(serveitic, IInitializedServeiTIC)
def onEventsFolderCreate(context, event, sample=True): # restrict what this folder can contain behavior = ISelectableConstrainTypes(context) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setImmediatelyAddableTypes(['Event']) behavior.setLocallyAllowedTypes(['Event', 'Collection']) # Create sample event and set publishing date to 01-01-YYYY if sample: # Calculate dates now = DateTime() start_date = DateTime() + 30 end_date = start_date + 1.0 / 24 item = createContentInContainer(context, "Event", id="sample", title="Sample Event", description="This is a sample Event", checkConstraints=False) item.text = RichTextValue(raw='<p>You may delete this item</p>', mimeType=u'text/html', outputMimeType='text/x-html-safe') item.setEffectiveDate(now) acc = IEventAccessor(item) acc.start = localize(start_date) acc.end = localize(end_date) # create 'upcoming' collection if 'upcoming' not in context.objectIds(): item = createContentInContainer( context, "Collection", id="upcoming", title='Upcoming Events', ) item.setQuery([{ u'i': u'path', u'o': u'plone.app.querystring.operation.string.absolutePath', u'v': u'%s::1' % context.UID() }, { u'i': u'portal_type', u'o': u'plone.app.querystring.operation.selection.any', u'v': [u'Event'] }]) item.setSort_on('start') # Set default page to the latest news collection context.setDefaultPage('upcoming')
def test_allowedContentTypesExit2(self): """ Constrains are acquired, parent folder is Plone Site """ behavior = ISelectableConstrainTypes(self.folder) types = behavior._getAddableTypesFor(self.portal, self.folder) behavior.setConstrainTypesMode(constrains.ACQUIRE) self.assertEqual(types, behavior.allowedContentTypes())
def test_allowedContentTypesExit1(self): """ Constrains are disabled, use the portal ones """ behavior = ISelectableConstrainTypes(self.folder) types = behavior._getAddableTypesFor(self.portal, self.folder) behavior.setConstrainTypesMode(constrains.DISABLED) self.assertEqual(types, behavior.allowedContentTypes())
def get_dashboard(self): write = False with api.env.adopt_roles(['Manager']): if 'dashboards' not in self.context.objectIds(): write = True api.content.create(type='Folder', title='Dashboards', id='dashboards', container=self.context, exclude_from_nav=True) dashboards = self.context['dashboards'] if not IHideFromBreadcrumbs.providedBy(dashboards): alsoProvides(dashboards, IHideFromBreadcrumbs) if api.content.get_state( obj=dashboards, default='Unknown') not in ('published', 'publish_internally'): write = True publish_content(dashboards) member = api.user.get_current() user_id = member.getId() if user_id not in dashboards.objectIds(): with api.env.adopt_roles(['Manager']): write = True # first make sure it is in allowed types... pts = api.portal.get_tool('portal_types') Folder = pts['Folder'] if 'Dashboard' not in Folder.allowed_content_types: allowed = list(Folder.allowed_content_types) allowed.append('Dashboard') Folder.allowed_content_types = tuple(allowed) aspect = ISelectableConstrainTypes(dashboards) if (aspect.getConstrainTypesMode() != 1 or ['Dashboard'] != aspect.getImmediatelyAddableTypes()): aspect.setConstrainTypesMode(1) aspect.setImmediatelyAddableTypes(['Dashboard']) api.content.create(type='Dashboard', title='Dashboard', id=user_id, container=dashboards, exclude_from_nav=True) dashboard = dashboards[user_id] if dashboard.getOwner().getId() != user_id: with api.env.adopt_roles(['Manager']): write = True dashboard.changeOwnership(member.getUser(), recursive=False) dashboard.reindexObjectSecurity() if write: alsoProvides(self.request, IDisableCSRFProtection) return dashboard
def create_folder(container, id, title, addable_types): folder = createContentInContainer( container, "Folder", id=id, title=title, exclude_from_nav=True) folder_constraints = ISelectableConstrainTypes(folder) folder_constraints.setConstrainTypesMode(1) folder_constraints.setLocallyAllowedTypes(addable_types) folder_constraints.setImmediatelyAddableTypes(addable_types)
def test_allowedContentTypesExit4(self): """ Constrains are enabled """ behavior = ISelectableConstrainTypes(self.folder) behavior.setLocallyAllowedTypes(self.types_id_subset) behavior.setConstrainTypesMode(constrains.ENABLED) self.assertEqual(self.types_id_subset, [x.getId() for x in behavior.allowedContentTypes()])
def test_constrainTypesAcquireDoesNotMatchParent(self): """ The inner folder should return constrains.ACQUIRE and not the actual value of its parent """ behavior1 = ISelectableConstrainTypes(self.folder) behavior2 = ISelectableConstrainTypes(self.inner_folder) behavior1.setConstrainTypesMode(constrains.DISABLED) self.assertEqual(constrains.ACQUIRE, behavior2.getConstrainTypesMode()) behavior1.setConstrainTypesMode(constrains.ENABLED) self.assertEqual(constrains.ACQUIRE, behavior2.getConstrainTypesMode())
def import_constrains(self, obj, item): if not item.get("exportimport.constrains"): return constrains = ISelectableConstrainTypes(obj, None) if constrains is None: return constrains.setConstrainTypesMode(ENABLED) locally_allowed_types = item["exportimport.constrains"][ "locally_allowed_types"] constrains.setLocallyAllowedTypes(locally_allowed_types) immediately_addable_types = item["exportimport.constrains"][ "immediately_addable_types"] constrains.setImmediatelyAddableTypes(immediately_addable_types)
def set_up_content(site): """Create and configure some initial content""" if "talks" in site: return talks = api.content.create(container=site, type="Folder", id="talks", title="Talks") api.content.transition(talks, "publish") api.group.grant_roles(groupname="AuthenticatedUsers", roles=["Contributor"], obj=talks) # Enable constraining behavior = ISelectableConstrainTypes(talks) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setLocallyAllowedTypes(["talk"]) behavior.setImmediatelyAddableTypes(["talk"]) logger.info("Created and configured %s" % talks.absolute_url())
def test_allowedContentTypesExit3(self): """ Constrains are acquired, parent folder is of same type """ outer_behavior = ISelectableConstrainTypes(self.folder) assert len(outer_behavior.getLocallyAllowedTypes()) > 2 outer_behavior.setLocallyAllowedTypes(self.types_id_subset) outer_behavior.setConstrainTypesMode(constrains.ENABLED) behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ACQUIRE) self.assertEqual(self.types_id_subset, [x.getId() for x in behavior.allowedContentTypes()])
def test_template_not_addable(self): # Normal folder => image is allowed to add self._create_templates([{'id': 'i1', 'type': 'Image', 'title': 'Image1'}]) self._open_url("%s/create_from_template" % self.folder.absolute_url()) self.assertIn('>Image1</label>', self.browser.contents) # Image is not allowed anymore in this folder constrain = ISelectableConstrainTypes(self.folder) constrain.setConstrainTypesMode(constraintypes.ENABLED) constrain.setImmediatelyAddableTypes([self.folder_type]) transaction.commit() self._open_url("%s/create_from_template" % self.folder.absolute_url()) self.assertIn('No templates', self.browser.contents)
def test_allowedContentTypesExit3(self): """ Constrains are acquired, parent folder is of same type """ outer_behavior = ISelectableConstrainTypes(self.folder) assert len(outer_behavior.getLocallyAllowedTypes()) > 2 outer_behavior.setLocallyAllowedTypes(self.types_id_subset) outer_behavior.setConstrainTypesMode(constrains.ENABLED) behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ACQUIRE) self.assertEquals(self.types_id_subset, [x.getId() for x in behavior.allowedContentTypes()])
def create_event_event(obj, event): if IRegistration.providedBy(obj.aq_parent): parent = obj.aq_parent parent.setDefaultPage(obj.id) create_registration_form(parent) behavior = ISelectableConstrainTypes(parent) behavior.setConstrainTypesMode(1) behavior.setImmediatelyAddableTypes(("period", )) request = getattr(event.object, "REQUEST", getRequest()) link_translations(request, parent) url = obj.aq_parent.absolute_url() obj.REQUEST.RESPONSE.redirect(url)
def test_immediatelyAllowedTypesDefaultWhenEnabled(self): """ Constrain Mode enabled We get the set constrains, independent of what our parent folder defined """ behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setImmediatelyAddableTypes(self.types_id_subset) outer_behavior = ISelectableConstrainTypes(self.folder) outer_behavior.setConstrainTypesMode(constrains.ENABLED) outer_behavior.setImmediatelyAddableTypes([]) types = self.types_id_subset self.assertEqual(types, behavior.getImmediatelyAddableTypes())
def various_update(self): # replace front-page frontpage = getattr(self.portal, 'front-page') frontpage.title = _translate("front_page_title") frontpage.description = _translate("front_page_descr") frontpage.text = richtextval(_translate("front_page_text")) transitions(frontpage, ('retract', 'publish_internally')) frontpage.reindexObject() self.portal.templates.layout = 'dg-templates-listing' # plonegroup-organization pgo = get_own_organization() behaviour = ISelectableConstrainTypes(pgo) behaviour.setConstrainTypesMode(1) behaviour.setLocallyAllowedTypes([]) behaviour.setImmediatelyAddableTypes([]) ISelectableConstrainTypes(pgo['echevins']).setConstrainTypesMode(0) ISelectableConstrainTypes(pgo['services']).setConstrainTypesMode(0)
def test_immediatelyAllowedTypesDefaultWhenDisabled(self): """ Constrain Mode Disabled. We get the default addables, independent of what our parent folder or we ourselves defined """ behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.DISABLED) behavior.setImmediatelyAddableTypes([]) outer_behavior = ISelectableConstrainTypes(self.folder) outer_behavior.setConstrainTypesMode(constrains.ENABLED) outer_behavior.setImmediatelyAddableTypes([]) types = [t.getId() for t in self.default_types] self.assertEqual(types, behavior.getImmediatelyAddableTypes())
def updateContainer(container, layout, ptypes): container.unindexObject() container.setLayout(layout) if IExcludeFromNavigation.providedBy(container): container.exclude_from_nav = True else: container.setExcludeFromNav(True) aspect = ISelectableConstrainTypes(container) addable = aspect.getImmediatelyAddableTypes() for ptype in ptypes: if ptype not in addable: aspect.setConstrainTypesMode(1) # select manually if IDexterityContainer.providedBy(container): #bypass check for available types container.immediately_addable_types = ptypes else: aspect.setImmediatelyAddableTypes(ptypes)
def updateHistoryContainer(obj): obj.unindexObject() obj.setLayout("collective_history_view") if IExcludeFromNavigation.providedBy(obj): obj.exclude_from_nav = True else: obj.setExcludeFromNav(True) aspect = ISelectableConstrainTypes(obj) addable = aspect.getImmediatelyAddableTypes() if "collective.history.useraction" not in addable: aspect.setConstrainTypesMode(1) # select manually types = ["collective.history.useraction"] if IDexterityContainer.providedBy(obj): #bypass check for available types obj.immediately_addable_types = types else: aspect.setImmediatelyAddableTypes(types)
def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] self.request = self.layer['request'] self.browser = Browser(self.app) # Create default GW directories setupview = getMultiAdapter((self.portal, self.request), name='setup-view') setupview.apply_default_language_settings() setupview.setup_multilingual() setupview.createContent('n4') # Enable the possibility to add Organs folder from Products.CMFPlone.interfaces.constrains import ISelectableConstrainTypes behavior = ISelectableConstrainTypes(self.portal['ca']) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(['genweb.organs.organsfolder']) behavior.setImmediatelyAddableTypes(['genweb.organs.organsfolder']) # Create Base folder to create base test folders try: api.content.delete(obj=self.portal['ca']['testingfolder'], check_linkintegrity=False) except: pass # Create default Organs Test Folder og_unit = api.content.create(type='genweb.organs.organsfolder', id='testingfolder', title='Organ Tests', container=self.portal['ca']) tools.create_organ_content(og_unit, 'open_organ', 'OG.OPEN', 'Organ TEST Obert', 'obert') tools.create_organ_content(og_unit, 'restricted_to_affected_organ', 'OG.AFFECTED', 'Organ TEST restringit a AFECTATS', 'afectats') tools.create_organ_content(og_unit, 'restricted_to_members_organ', 'OG.MEMBERS', 'Organ TEST restringit a MEMBRES', 'membres') logout()
def add_container(container, type, title, allowed_types=None, exclude_from_nav=False): folder_id = getUtility(IIDNormalizer).normalize(title) if folder_id not in container: folder = api.content.create(type=type, id=folder_id, title=title, container=container) api.content.transition(obj=folder, transition='publish') if allowed_types: behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(allowed_types) behavior.setImmediatelyAddableTypes(allowed_types) folder.exclude_from_nav = exclude_from_nav return container[folder_id]
def add_container(container, type, title, allowed_types=None, exclude_from_nav=False): folder_id = getUtility(IIDNormalizer).normalize(title) if folder_id not in container: folder = api.content.create( type=type, id=folder_id, title=title, container=container) api.content.transition( obj=folder, transition='publish') if allowed_types: behavior = ISelectableConstrainTypes(folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(allowed_types) behavior.setImmediatelyAddableTypes(allowed_types) folder.exclude_from_nav = exclude_from_nav return container[folder_id]
def render(self): pc = api.portal.get_tool(name='portal_catalog') communities = pc.searchResults(portal_type='ulearn.community') text = [] for community in communities: community = community.getObject() media_folder = community.media behavior = ISelectableConstrainTypes(media_folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(('Image', 'ulearn.video', 'Folder')) behavior.setImmediatelyAddableTypes(('Image', 'ulearn.video', 'Folder')) if media_folder.title != 'Media': media_folder.setTitle(community.translate(_(u'Media'))) text.append('Added type video to {}\n'.format(community.absolute_url())) return ''.join(text)
def _addFileTypeToProjectSpaceConstrainedTypes(self): """We want to be able to add 'Files' in the 'pst' projectspace.""" logger.info( "Adding 'File' to constrained types of projectspace 'pst'...") projectspace = self.portal.pst # we do not publish because, in published state, editors cannot more modify # do_transitions(projectspace, transitions=['publish_internally'], logger=logger) # set locally allowed types behaviour = ISelectableConstrainTypes(projectspace) behaviour.setConstrainTypesMode(1) behaviour.setLocallyAllowedTypes([ 'strategicobjective', 'File', ]) behaviour.setImmediatelyAddableTypes([ 'strategicobjective', 'File', ]) logger.info('Done.')
def migrate(self, old, new): new_path = "/".join(new.getPhysicalPath()) for iface in interfaces: if iface.providedBy(old): alsoProvides(new, iface) logger.warn("{0} also provides {1}".format(new_path, str(iface))) if old.getConstrainTypesMode() != 0: behaviour = ISelectableConstrainTypes(new) behaviour.setConstrainTypesMode(1) if old.getConstrainTypesMode() == 1: behaviour.setLocallyAllowedTypes(old.getLocallyAllowedTypes()) behaviour.setImmediatelyAddableTypes(old.getImmediatelyAddableTypes()) if IFacetedNavigable.providedBy(old): criteria = Criteria(new) criteria._update(ICriteria(old).criteria) IFacetedLayout(new).update_layout('faceted-table-items') logger.warn("Added faceted criteria and layout to {0}".format(new_path))
def test_locallyAllowedTypesDefaultWhenEnabled(self): """ Constrain Mode enabled We get the set constrains, independent of what our parent folder defined """ behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setLocallyAllowedTypes(self.types_id_subset) outer_behavior = ISelectableConstrainTypes(self.folder) outer_behavior.setConstrainTypesMode(constrains.ENABLED) outer_behavior.setLocallyAllowedTypes([]) types = [t for t in self.default_types if t.getId() in self.types_id_subset] type_ids = self.types_id_subset self.assertEqual(types, behavior.allowedContentTypes()) self.assertEqual(type_ids, behavior.getLocallyAllowedTypes())
def _updateFolder(obj, types=None, view=None, authenticated_roles=None): if view is not None: obj.setLayout(view) if types is not None: aspect = ISelectableConstrainTypes(obj) addable = aspect.getLocallyAllowedTypes() if types != addable: aspect.setConstrainTypesMode(1) # Need to be globally allowed in order to be set as locally allowed # or to create a custom folderish content type with # "allowed_content_types" # Only a blacklist, not a whitelist setattr(obj, 'locally_allowed_types', types) setattr(obj, 'immediately_addable_types', types) if authenticated_roles is not None: obj.manage_setLocalRoles('AuthenticatedUsers', authenticated_roles) # Move view permission from Anonymous to Member obj.manage_permission(View, acquire=False, roles=('Authenticated', 'Member', 'Manager', 'Site Administrator'))
def set_up_content(site): """Create and configure some initial content""" if 'talks' in site: return talks = api.content.create( container=site, type='Folder', id='talks', title='Talks') api.content.transition(talks, 'publish') api.group.grant_roles( groupname='AuthenticatedUsers', roles=['Contributor'], obj=talks) # Enable constraining behavior = ISelectableConstrainTypes(talks) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setLocallyAllowedTypes(['talk']) behavior.setImmediatelyAddableTypes(['talk']) logger.info("Created and configured %s" % talks.absolute_url())
def test_contextual_constrains(self): content = api.content.create( container=self.portal, id="images", type="Folder", title="Image Bank", ) # Enable the ISelectableConstrainTypes behavior behavior = ISelectableConstrainTypes(content) behavior.setConstrainTypesMode(constrains.ENABLED) # Allow only Image and File to be added behavior.setLocallyAllowedTypes(["Image", "File"]) # Only Images are immediately addable behavior.setImmediatelyAddableTypes(["Image"]) transaction.commit() # response = self.api_session.get("/images/@types") response = response.json() self.assertEqual(len([a for a in response if a["immediately_addable"]]), 1) self.assertEqual(len([a for a in response if a["addable"]]), 2)
def update(self, obj, data): if IS_PLONE_5 or IS_PLONE_APP_MULTILINGUAL_2: constrains = ISelectableConstrainTypes(obj) if constrains: constrains.setConstrainTypesMode(constraintypes.ENABLED) immediately = tuple(data['immediately']) constrains.setImmediatelyAddableTypes(immediately) locally = tuple(data['locally']) constrains.setLocallyAllowedTypes(locally) else: if base_hasattr(obj, 'getConstrainTypesMode'): obj.setConstrainTypesMode(constraintypes.ENABLED) immediately = tuple(data['immediately']) obj.setImmediatelyAddableTypes(immediately) locally = tuple(data['locally']) obj.setLocallyAllowedTypes(locally)
def test_locallyAllowedTypesDefaultWhenEnabled(self): """ Constrain Mode enabled We get the set constrains, independent of what our parent folder defined """ behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ENABLED) behavior.setLocallyAllowedTypes(self.types_id_subset) outer_behavior = ISelectableConstrainTypes(self.folder) outer_behavior.setConstrainTypesMode(constrains.ENABLED) outer_behavior.setLocallyAllowedTypes([]) types = [ t for t in self.default_types if t.getId() in self.types_id_subset ] type_ids = self.types_id_subset self.assertEqual(types, behavior.allowedContentTypes()) self.assertEqual(type_ids, behavior.getLocallyAllowedTypes())
def render(self): portal = getSite() gestion = self.newPrivateFolder(portal, 'gestion', u'Gestión') gestion.exclude_from_nav = False gestion.setLayout('folder_listing') behavior = ISelectableConstrainTypes(gestion) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(('Folder', 'privateFolder',)) behavior.setImmediatelyAddableTypes(('Folder', 'privateFolder',)) enlaces_cabecera = self.newPrivateFolder(gestion, 'menu', u'Menu') enlaces_cabecera.exclude_from_nav = False enlaces_cabecera.reindexObject() for language in portal['portal_languages'].getSupportedLanguages(): language_folder = self.newPrivateFolder(enlaces_cabecera, language, language) language_folder.exclude_from_nav = False language_folder.reindexObject() behavior = ISelectableConstrainTypes(language_folder) behavior.setConstrainTypesMode(1) behavior.setLocallyAllowedTypes(('Folder', 'privateFolder', 'Link',)) behavior.setImmediatelyAddableTypes(('Folder', 'privateFolder', 'Link',))
def test_immediatelyAllowedTypesDefaultWhenAcquired(self): """ Constrain Mode set to ACQUIRE Try to acquire the constrains, if that fails, use the defaults """ behavior = ISelectableConstrainTypes(self.inner_folder) behavior.setConstrainTypesMode(constrains.ACQUIRE) behavior.setImmediatelyAddableTypes([]) outer_behavior = ISelectableConstrainTypes(self.folder) outer_behavior.setConstrainTypesMode(constrains.ENABLED) outer_behavior.setImmediatelyAddableTypes(self.types_id_subset) types = self.types_id_subset self.assertEqual(types, behavior.getImmediatelyAddableTypes()) outer_behavior.setConstrainTypesMode(constrains.ACQUIRE) types = [t.getId() for t in self.default_types] self.assertEqual(types, outer_behavior.getImmediatelyAddableTypes())