def set_allowed_and_addable_types(self):
        """ Folder restrictions and addable types """
        def modify_types(types):
            old2new = {"Topic": "Collection"}

            types_tool = plone.api.portal.get_tool("portal_types")
            available_types = types_tool.objectIds()

            # replace old types with new types
            types = [old2new.get(t, t) for t in types]
            # filter out non existing types
            types = [t for t in types if t in available_types]
            return types

        data = json.loads(self.request.BODY)
        addable_types = data.get("addable_types", ())
        addable_types = modify_types(addable_types)
        allowed_types = data.get("allowed_types", ())
        allowed_types = modify_types(allowed_types)
        constrain_types_mode = data.get("constrain_types_mode", -1)

        if constrain_types_mode == -1:  # AQUIRE
            return

        constrains = ISelectableConstrainTypes(self.context)
        if allowed_types:
            constrains.setLocallyAllowedTypes(allowed_types)
        if addable_types:
            constrains.setImmediatelyAddableTypes(addable_types)
        constrains.setConstrainTypesMode(constrain_types_mode)
        self.request.response.setStatus(204)
예제 #2
0
 def migrate_annex(self):
     qi = self.context.portal_quickinstaller
     if not qi.isProductInstalled('imio.annex'):
         qi.installProduct('imio.annex')
     self.runProfileSteps('imio.project.pst', steps=['typeinfo'], run_dependencies=False)
     brains = self.catalog(object_provides=IProjectSpace.__identifier__)
     for brain in brains:
         pst_obj = brain.getObject()
         behaviour = ISelectableConstrainTypes(pst_obj)
         behaviour.setConstrainTypesMode(1)
         behaviour.setLocallyAllowedTypes(['strategicobjective', 'annex', ])
         behaviour.setImmediatelyAddableTypes(['strategicobjective', 'annex', ])
     portal = api.portal.get()
     configure_iconified_category(portal)
     annexTypeId = calculate_category_id(portal.categorization.annexes.get('annexes-pst'))
     brains = self.catalog(object_provides=IFile.__identifier__)
     for brain in brains:
         file_obj = brain.getObject()
         parent = file_obj.aq_parent
         if parent.portal_type in ['pstprojectspace', 'strategicobjective', 'operationalobjective',
                                   'pstaction', 'pstsubaction', 'task']:
             annexId = file_obj.id
             api.content.delete(obj=parent[annexId])
             api.content.create(
                 container=parent,
                 type='annex',
                 id=annexId,
                 title=file_obj.Title(),
                 description=file_obj.Description(),
                 content_category=annexTypeId,
                 file=file_obj.file,
             )
             transaction.commit()
예제 #3
0
def to_1500(context):
    """ This upgrade handles that a type "Bando" is now  addmitted by default
    inside the folder "Documenti e Dati".
    This method just ADD THE CONTENT TYPE to the current list of types that you
    can add inside that folder only if it's not already there.
    tp#17807
    """

    doc_brains = api.content.find(portal_type="Document")
    doc_e_dati_list = [x for x in doc_brains if x.Title == "Documenti e dati"]
    if len(doc_e_dati_list) == 1:
        doc_e_dati = doc_e_dati_list[0].getObject()

        constraints = ISelectableConstrainTypes(doc_e_dati)
        allowed_types = constraints.getLocallyAllowedTypes()
        if "Bando" not in allowed_types:
            allowed_types.append("Bando")
            constraints.setLocallyAllowedTypes(allowed_types)

            logger.info("Enabled 'Bando' inside 'Ducumenti e dati' folder.")
        else:
            logger.info("'Bando' already enabled in 'Ducumenti e dati' folder,"
                        " not changes needed.")
    else:
        logger.warning("More than one Document with title 'Documenti e dati'. "
                       "Type 'Bando' inside 'Ducumenti e dati' folder not "
                       "enabled.")
예제 #4
0
def notiziaCreateHandler(notizia, event):
    """
    Complete content type notizia setup on added event, generating
    missing folders, fields, etc.

    @param notizia: Content item

    @param event: Event that triggers the method (onAdded event)
    """

    if "multimedia" not in notizia.keys():
        multimedia = api.content.create(type="Document",
                                        title="Multimedia",
                                        container=notizia)
        create_default_blocks(context=multimedia)
        constraintsMultimedia = ISelectableConstrainTypes(multimedia)
        constraintsMultimedia.setConstrainTypesMode(1)
        constraintsMultimedia.setLocallyAllowedTypes(("Link", "Image"))

    if "documenti-allegati" not in notizia.keys():
        documenti = api.content.create(type="Document",
                                       title="Documenti allegati",
                                       container=notizia)
        create_default_blocks(context=documenti)
        constraintsDocumenti = ISelectableConstrainTypes(documenti)
        constraintsDocumenti.setConstrainTypesMode(1)
        constraintsDocumenti.setLocallyAllowedTypes(("File", "Image"))
def servizioCreateHandler(servizio, event):
    """
    Complete content type Servizio setup on added event, generating
    missing folders, fields, etc.

    @param servizio: Content item

    @param event: Event that triggers the method (onAdded event)
    """

    for folder in [
        {
            "id": "modulistica",
            "title": "Modulistica",
            "contains": ("File", "Link")
        },
        {
            "id": "allegati",
            "title": "Allegati",
            "contains": ("File", "Link")
        },
    ]:
        if folder["id"] not in servizio.keys():
            child = api.content.create(type="Document",
                                       title=folder["title"],
                                       container=servizio)
            create_default_blocks(context=child)

            childConstraints = ISelectableConstrainTypes(child)
            childConstraints.setConstrainTypesMode(1)
            childConstraints.setLocallyAllowedTypes(folder["contains"])
예제 #6
0
 def testNonStructualFolderShowsParent(self):
     self.folder.invokeFactory('Folder', 'folder1')
     directlyProvides(self.folder.folder1, INonStructuralFolder)
     constraints = ISelectableConstrainTypes(self.folder.folder1)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder.folder1, self.request)
     self.assertEqual(len(actions), 0)
예제 #7
0
 def testNonStructualFolderShowsParent(self):
     self.folder.invokeFactory('Folder', 'folder1')
     directlyProvides(self.folder.folder1, INonStructuralFolder)
     constraints = ISelectableConstrainTypes(self.folder.folder1)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', ))
     constraints.setImmediatelyAddableTypes(('Document', ))
     actions = self.menu.getMenuItems(self.folder.folder1, self.request)
     self.assertEqual(len(actions), 0)
예제 #8
0
 def testMoreNotIncludedWhenNotNecessary(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder, self.request)
     self.assertEqual(len(actions), 2)
     self.assertEqual(actions[0]['extra']['id'], 'document')
     self.assertEqual(actions[1]['extra']['id'], 'settings')
예제 #9
0
 def testMoreNotIncludedWhenNotNecessary(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder, self.request)
     self.assertEqual(len(actions), 2)
     self.assertEqual(actions[0]['extra']['id'], 'document')
     self.assertEqual(actions[1]['extra']['id'], 'plone-contentmenu-settings')
예제 #10
0
 def testNonStructualFolderShowsParent(self):
     self.folder.invokeFactory('Folder', 'folder1')
     directlyProvides(self.folder.folder1, INonStructuralFolder)
     constraints = ISelectableConstrainTypes(self.folder.folder1)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder.folder1, self.request)
     action_ids = [a['extra']['id'] for a in actions]
     self.assertTrue('event' in action_ids)
예제 #11
0
 def testMoreIncluded(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', 'Image',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder, self.request)
     self.failIf('image' in [a['extra']['id'] for a in actions])
     self.failUnless('document' in [a['extra']['id'] for a in actions])
     self.failUnless('plone-contentmenu-more' in [a['extra']['id'] for a in actions])
     self.failUnless('plone-contentmenu-settings' in [a['extra']['id'] for a in actions])
예제 #12
0
    def test_cant_paste_with_filter_set(self):
        self.folder._verifyObjectPaste(self.document)

        constraints = ISelectableConstrainTypes(self.folder)
        constraints.setConstrainTypesMode(1)
        constraints.setLocallyAllowedTypes(("News Item", ))

        self.assertRaises(ValueError, self.folder._verifyObjectPaste,
                          self.document)
        self.folder._verifyObjectPaste(self.news)
예제 #13
0
 def testNonStructualFolderShowsParent(self):
     self.folder.invokeFactory('Folder', 'folder1')
     directlyProvides(self.folder.folder1, INonStructuralFolder)
     constraints = ISelectableConstrainTypes(self.folder.folder1)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', ))
     constraints.setImmediatelyAddableTypes(('Document', ))
     actions = self.menu.getMenuItems(self.folder.folder1, self.request)
     action_ids = [a['extra']['id'] for a in actions]
     self.assertTrue('event' in action_ids)
예제 #14
0
 def testMoreIncluded(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', 'Image',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder, self.request)
     self.failIf('image' in [a['extra']['id'] for a in actions])
     self.failUnless('document' in [a['extra']['id'] for a in actions])
     self.failUnless('more' in [a['extra']['id'] for a in actions])
     self.failUnless('settings' in [a['extra']['id'] for a in actions])
예제 #15
0
 def testAddMenuWithNothingToAddButWithAvailableConstrainSettings(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(())
     constraints.setImmediatelyAddableTypes(())
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [
         i for i in items if
         i['extra']['id'] == 'plone-contentmenu-factories'][0]
     self.assertEqual(len(factoriesMenuItem['submenu']), 1)
     self.assertEqual(factoriesMenuItem['submenu'][0]['extra']['id'],
                      'plone-contentmenu-settings')
예제 #16
0
 def testAddMenuWithNothingToAddButWithAvailableConstrainSettings(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(())
     constraints.setImmediatelyAddableTypes(())
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [
         i for i in items if
         i['extra']['id'] == 'plone-contentmenu-factories'][0]
     self.assertEqual(len(factoriesMenuItem['submenu']), 1)
     self.assertEqual(factoriesMenuItem['submenu'][0]['extra']['id'],
                      'plone-contentmenu-settings')
예제 #17
0
def onSetupColeccion(colectObj, event):
    """ """
    workflowTool = getToolByName(colectObj, "portal_workflow")
    flag=0
    if event.action == 'setUp':
        #event.object.setLayout('publish_view')
        for carpeta in carpetasDict:
            newId="%s_%s" %(colectObj.id,carpeta["id"])

            if not hasattr(colectObj,newId):
                oid=colectObj.invokeFactory(carpeta["tipo"], id=newId)
                transaction.savepoint(optimistic=True)
                new_obj = colectObj[oid]
                new_obj.setTitle(carpeta["titulo"])
                new_obj.setDescription(carpeta["titulo"])

                #
                # Habilita el filtrado de tipos de contenidos
                #
                ENABLED = 1
              

                try:
                    workflowTool.doActionFor(new_obj, "publish")
                    logger.info("Estado cambiado!")
                except WorkflowException:
                    # a workflow exception is risen if the state transition is not available
                    # (the sampleProperty content is in a workflow state which
                    # does not have a "submit" transition)
                    logger.info("Could not publish:" + str(new_obj.getId()) + " already published?")
                    pass
                    
                new_obj.reindexObject()
                
                if shasattr(new_obj, 'canSetConstrainTypes'):
                    new_obj.setConstrainTypesMode(constraintypes.ENABLED)
                    # Types for which we perform Unauthorized check
                    new_obj.setLocallyAllowedTypes(carpeta["constraint"])
                    # Add new... menu  listing
                    new_obj.setImmediatelyAddableTypes(carpeta["constraint"])
                else:
                    from Products.CMFPlone.interfaces import ISelectableConstrainTypes
                    constraints = ISelectableConstrainTypes(new_obj)
                    constraints.setConstrainTypesMode(ENABLED)
                    constraints.setLocallyAllowedTypes(carpeta["constraint"])
                    
                    
                flag=flag+1
            else:
                print "la carpeta estaba creada"
    else:
        print "la accion no es SetUp"
예제 #18
0
    def handleSave(self, action):
        data, errors = self.extractData()

        if errors:
            return

        immediately_addable_types = [t for t in data['current_prefer']
                                     if t not in data['current_allow']]
        locally_allowed_types = data['current_prefer']
        aspect = ISelectableConstrainTypes(self.context)
        aspect.setConstrainTypesMode(data['constrain_types_mode'])
        aspect.setLocallyAllowedTypes(locally_allowed_types)
        aspect.setImmediatelyAddableTypes(immediately_addable_types)
예제 #19
0
 def testAddMenuWithNothingToAddButWithAvailableMorePage(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(())
     self.folder.manage_permission('Modify constrain types', ('Manager',))
     setRoles(self.portal, TEST_USER_ID, ['Contributor'])
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [i for i in items if
         i['extra']['id'] == 'plone-contentmenu-factories'][0]
     self.assertEqual(len(factoriesMenuItem['submenu']), 1)
     self.assertEqual(factoriesMenuItem['submenu'][0]['extra']['id'],
                      'plone-contentmenu-more')
예제 #20
0
    def handleSave(self, action):
        data, errors = self.extractData()

        if errors:
            return

        immediately_addable_types = [t for t in data['current_prefer']
                                     if t not in data['current_allow']]
        locally_allowed_types = data['current_prefer']
        aspect = ISelectableConstrainTypes(self.context)
        aspect.setConstrainTypesMode(data['constrain_types_mode'])
        aspect.setLocallyAllowedTypes(locally_allowed_types)
        aspect.setImmediatelyAddableTypes(immediately_addable_types)
예제 #21
0
 def testMoreIncluded(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', 'Image',))
     constraints.setImmediatelyAddableTypes(('Document',))
     actions = self.menu.getMenuItems(self.folder, self.request)
     self.assertFalse('image' in [a['extra']['id'] for a in actions])
     self.assertTrue('document' in [a['extra']['id'] for a in actions])
     self.assertTrue(
         'plone-contentmenu-more' in [a['extra']['id'] for a in actions]
     )
     self.assertTrue(
         'plone-contentmenu-settings' in [a['extra']['id'] for a in actions]
     )
def documentCreateHandler(document, event):
    """
    @param document: Content item

    @param event: Event that triggers the method (onAdded event)

    Se viene creato dentro ad una cartella modulistica, allora al suo interno
    si possono creare solo Documenti.
    """

    if event.newParent.portal_type == "CartellaModulistica":
        documentConstraints = ISelectableConstrainTypes(document)
        documentConstraints.setConstrainTypesMode(1)
        documentConstraints.setLocallyAllowedTypes(("Documento", ))
예제 #23
0
def handleAddedEvaluable(obj, event):
    with api.env.adopt_roles(roles='Manager'):
        constraints = ISelectableConstrainTypes(obj)
        constraints.setConstrainTypesMode(constrains.DISABLED)
        document = api.content.create(type='Document', title='Carta', container=obj)
        api.group.grant_roles(groupname='evaluators', roles=['Editor'], obj=document)
        constraints.setLocallyAllowedTypes(['Pdf File'])
        constraints.setImmediatelyAddableTypes(['Pdf File'])
        constraints.setConstrainTypesMode(constrains.ENABLED)

        for member in api.user.get_users(groupname='evaluators'):
            api.user.grant_roles(username=member.id, roles=['Reader'], obj=obj)

        api.content.disable_roles_acquisition(obj=obj)
        api.group.grant_roles(groupname='Reviewers', roles=['Reader'], obj=obj)
예제 #24
0
 def testAddMenuWithNothingToAddButWithAvailableMorePage(self):
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document', ))
     constraints.setImmediatelyAddableTypes(())
     self.folder.manage_permission('Modify constrain types', ('Manager', ))
     setRoles(self.portal, TEST_USER_ID, ['Contributor'])
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [
         i for i in items
         if i['extra']['id'] == 'plone-contentmenu-factories'
     ][0]
     self.assertEqual(len(factoriesMenuItem['submenu']), 1)
     self.assertEqual(factoriesMenuItem['submenu'][0]['extra']['id'],
                      'plone-contentmenu-more')
예제 #25
0
 def testAddMenuWithAddViewExpr(self):
     # we need a dummy to test this - should test that if the item does not
     # support constrain types and there is
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     self.folder.manage_permission('Modify constrain types', ('Manager',))
     self.portal.portal_types['Document']._setPropValue(
         'add_view_expr', 'string:custom_expr')
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [
         i for i in items if
         i['extra']['id'] == 'plone-contentmenu-factories'][0]
     self.assertEqual(factoriesMenuItem['submenu'][0]['action'],
                      'custom_expr')
예제 #26
0
 def testAddMenuWithAddViewExpr(self):
     # we need a dummy to test this - should test that if the item does not
     # support constrain types and there is
     constraints = ISelectableConstrainTypes(self.folder)
     constraints.setConstrainTypesMode(1)
     constraints.setLocallyAllowedTypes(('Document',))
     constraints.setImmediatelyAddableTypes(('Document',))
     self.folder.manage_permission('Modify constrain types', ('Manager',))
     self.portal.portal_types['Document']._setPropValue(
         'add_view_expr', 'string:custom_expr')
     items = self.menu.getMenuItems(self.folder, self.request)
     factoriesMenuItem = [
         i for i in items if
         i['extra']['id'] == 'plone-contentmenu-factories'][0]
     self.assertEqual(factoriesMenuItem['submenu'][0]['action'],
                      'custom_expr')
예제 #27
0
    def __call__(self):

        if hasattr(self.context.aq_base, CAROUSEL_ID):
            carousel = getattr(self.context, CAROUSEL_ID)
        else:
            pt = getToolByName(self.context, 'portal_types')
            newid = pt.constructContent(
                            type_name='Folder',
                            container=self.context,
                            id='carousel',
                            title='Carousel Banners'
                        )
            carousel = getattr(self.context, newid)

            # exclude the (Archetypes or Dexterity) folder from navigation
            if hasattr(aq_base(carousel), 'setExcludeFromNav'):
                carousel.setExcludeFromNav(True)
            elif hasattr(aq_base(carousel), 'exclude_from_nav'):
                carousel.exclude_from_nav = True

            # mark the new folder as a Carousel folder
            alsoProvides(carousel, ICarouselFolder)

            # make sure Carousel banners are addable within the new folder
            addPermissionsForRole(carousel, 'Manager',
                                  ('Carousel: Add Carousel Banner',))
            addPermissionsForRole(carousel, 'Site Administrator',
                                  ('Carousel: Add Carousel Banner',))
            addPermissionsForRole(carousel, 'Owner',
                                  ('Carousel: Add Carousel Banner',))
            addPermissionsForRole(carousel, 'Contributor',
                                  ('Carousel: Add Carousel Banner',))
            addPermissionsForRole(carousel, 'Editor',
                                  ('Carousel: Add Carousel Banner',))
            

            # make sure *only* Carousel banners are addable
            aspect = ISelectableConstrainTypes(carousel)
            aspect.setConstrainTypesMode(1)
            aspect.setLocallyAllowedTypes(['Carousel Banner'])
            aspect.setImmediatelyAddableTypes(['Carousel Banner'])

            carousel.reindexObject()

        self.request.RESPONSE.redirect(
            carousel.absolute_url() + '/@@edit-carousel'
        )
예제 #28
0
def praticaCreateHandler(pratica, event):
    """
    Complete content type Pratica setup on added event, generating
    missing folders, fields, etc.

    @param pratica: Content item

    @param event: Event that triggers the method (onAdded event)
    """

    allegati = api.content.create(type="Folder",
                                  title="Allegati",
                                  container=pratica)

    allegatiConstraints = ISelectableConstrainTypes(allegati)
    allegatiConstraints.setConstrainTypesMode(1)
    allegatiConstraints.setLocallyAllowedTypes(("File", ))
예제 #29
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        allowed_types = data['allowed_types']
        immediately_addable = [
            t for t in allowed_types
            if t not in data['secondary_types']]

        aspect = ISelectableConstrainTypes(self.context)
        aspect.setConstrainTypesMode(data['constrain_types_mode'])
        aspect.setLocallyAllowedTypes(allowed_types)
        aspect.setImmediatelyAddableTypes(immediately_addable)
        contextURL = self.context.absolute_url()
        self.request.response.redirect(contextURL)
예제 #30
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        allowed_types = data['allowed_types']
        immediately_addable = [
            t for t in allowed_types
            if t not in data['secondary_types']]

        aspect = ISelectableConstrainTypes(self.context)
        aspect.setConstrainTypesMode(data['constrain_types_mode'])
        aspect.setLocallyAllowedTypes(allowed_types)
        aspect.setImmediatelyAddableTypes(immediately_addable)
        contextURL = self.context.absolute_url()
        self.request.response.redirect(contextURL)
예제 #31
0
def luogoCreateHandler(luogo, event):
    """
    Complete content type luogo setup on added event, generating
    missing folders, fields, etc.

    @param luogo: Content item

    @param event: Event that triggers the method (onAdded event)
    """
    folder_id = "multimedia"
    if folder_id in luogo:
        return
    folder = _createObjectByType("Folder", luogo, "multimedia")
    folder.title = "Multimedia"
    folder.reindexObject(idxs=["Title"])
    constraints = ISelectableConstrainTypes(folder)
    constraints.setConstrainTypesMode(1)
    constraints.setLocallyAllowedTypes((
        "Image",
        "Link",
    ))
def documentoCreateHandler(documento, event):
    """
    Complete content type Documento setup on added event, generating
    missing folders, fields, etc.

    @param documento: Content item

    @param event: Event that triggers the method (onAdded event)
    """
    if "multimedia" in documento.keys():
        # we are copying or moving it
        return

    documentoConstraints = ISelectableConstrainTypes(documento)
    documentoConstraints.setConstrainTypesMode(1)
    documentoConstraints.setLocallyAllowedTypes(("Document",))

    # create support folder
    multimedia = api.content.create(
        type="Document", title="Multimedia", container=documento
    )
    create_default_blocks(context=multimedia)

    multimediaConstraints = ISelectableConstrainTypes(multimedia)
    multimediaConstraints.setConstrainTypesMode(1)
    multimediaConstraints.setLocallyAllowedTypes(("Image",))

    documentoConstraints = ISelectableConstrainTypes(documento)
    documentoConstraints.setConstrainTypesMode(1)
    documentoConstraints.setLocallyAllowedTypes(("Modulo", "Link"))
예제 #33
0
def eventoCreateHandler(evento, event):
    """
    Complete content type evento setup on added event, generating
    missing folders, fields, etc.

    @param evento: Content item

    @param event: Event that triggers the method (onAdded event)
    """
    if not IDesignPloneContenttypesLayer.providedBy(evento.REQUEST):
        return
    if "multimedia" not in evento.keys():
        galleria = api.content.create(
            container=evento,
            type="Document",
            title="Multimedia",
            id="multimedia",
        )
        create_default_blocks(context=galleria)

        # select  constraints
        constraintsGalleria = ISelectableConstrainTypes(galleria)
        constraintsGalleria.setConstrainTypesMode(1)
        constraintsGalleria.setLocallyAllowedTypes(("Image", "Link"))

        with api.env.adopt_roles(["Reviewer"]):
            api.content.transition(obj=galleria, transition="publish")

    if "sponsor_evento" not in evento.keys():
        sponsor = api.content.create(
            container=evento,
            type="Document",
            title="Sponsor Evento",
            id="sponsor_evento",
        )
        create_default_blocks(context=sponsor)

        constraintsSponsor = ISelectableConstrainTypes(sponsor)
        constraintsSponsor.setConstrainTypesMode(1)
        constraintsSponsor.setLocallyAllowedTypes(("Link", ))

        with api.env.adopt_roles(["Reviewer"]):
            api.content.transition(obj=sponsor, transition="publish")

    if "documenti" not in evento.keys():
        documenti = api.content.create(
            container=evento,
            type="Document",
            title="Documenti",
            id="documenti",
        )
        create_default_blocks(context=documenti)

        constraintsDocumenti = ISelectableConstrainTypes(documenti)
        constraintsDocumenti.setConstrainTypesMode(1)
        constraintsDocumenti.setLocallyAllowedTypes(("File", ))

        with api.env.adopt_roles(["Reviewer"]):
            api.content.transition(obj=documenti, transition="publish")
예제 #34
0
    def __call__(self):

        if hasattr(self.context.aq_base, CAROUSEL_ID):
            carousel = getattr(self.context, CAROUSEL_ID)
        else:
            pt = getToolByName(self.context, 'portal_types')
            newid = pt.constructContent(type_name='Folder',
                                        container=self.context,
                                        id='carousel',
                                        title='Carousel Banners')
            carousel = getattr(self.context, newid)

            # exclude the (Archetypes or Dexterity) folder from navigation
            if hasattr(aq_base(carousel), 'setExcludeFromNav'):
                carousel.setExcludeFromNav(True)
            elif hasattr(aq_base(carousel), 'exclude_from_nav'):
                carousel.exclude_from_nav = True

            # mark the new folder as a Carousel folder
            alsoProvides(carousel, ICarouselFolder)

            # make sure Carousel banners are addable within the new folder
            addPermissionsForRole(carousel, 'Manager',
                                  ('Carousel: Add Carousel Banner', ))
            addPermissionsForRole(carousel, 'Site Administrator',
                                  ('Carousel: Add Carousel Banner', ))

            # make sure *only* Carousel banners are addable
            aspect = ISelectableConstrainTypes(carousel)
            aspect.setConstrainTypesMode(1)
            aspect.setLocallyAllowedTypes(['Carousel Banner'])
            aspect.setImmediatelyAddableTypes(['Carousel Banner'])

            carousel.reindexObject()

        self.request.RESPONSE.redirect(carousel.absolute_url() +
                                       '/@@edit-carousel')
예제 #35
0
def unitaOrganizzativaCreateHandler(unitaOrganizzativa, event):
    """
    Complete content type UnitaOrganizzativa setup on added event, generating
    missing folders, fields, etc.

    @param unitaOrganizzativa: Content item

    @param event: Event that triggers the method (onAdded event)
    """
    if "allegati" in unitaOrganizzativa.keys():
        return
    try:
        allegati = api.content.create(type="Document",
                                      title="Allegati",
                                      container=unitaOrganizzativa)
    except AttributeError as e:
        # problems with tests in design.plone.policy
        logger.exception(e)
        return

    create_default_blocks(context=allegati)
    allegatiConstraints = ISelectableConstrainTypes(allegati)
    allegatiConstraints.setConstrainTypesMode(1)
    allegatiConstraints.setLocallyAllowedTypes(("File", ))
 def migrate_typerestriction(self):
     constraints = ISelectableConstrainTypes(self.new)
     constraints.setConstrainTypesMode(ENABLED)
     constraints.setImmediatelyAddableTypes(self.new_allowed)
     constraints.setLocallyAllowedTypes(self.new_allowed)
예제 #37
0
def personaCreateHandler(persona, event):
    """
    Complete content type Persona setup on added event, generating
    missing folders, fields, etc.

    @param persona: Content item

    @param event: Event that triggers the method (onAdded event)
    """

    FOLDERS = [
        {
            "id": "foto-e-attivita-politica",
            "title": "Foto e attività politica",
            "contains": ("Image", ),
        },
        {
            "id": "curriculum-vitae",
            "title": "Curriculum vitae",
            "contains": ("File", )
        },
        {
            "id": "compensi",
            "title": "Compensi",
            "contains": ("File", )
        },
        {
            "id": "importi-di-viaggio-e-o-servizi",
            "title": "Importi di viaggio e/o servizi",
            "contains": ("File", ),
        },
        {
            "id": "situazione-patrimoniale",
            "title": "Situazione patrimoniale",
            "contains": ("File", ),
        },
        {
            "id": "dichiarazione-dei-redditi",
            "title": "Dichiarazione dei redditi",
            "contains": ("File", ),
        },
        {
            "id": "spese-elettorali",
            "title": "Spese elettorali",
            "contains": ("File", ),
        },
        {
            "id": "variazione-situazione-patrimoniale",
            "title": "Variazione situazione patrimoniale",
            "contains": ("File", ),
        },
        {
            "id": "altre-cariche",
            "title": "Altre cariche",
            "contains": ("File", ),
        },
    ]
    for folder in FOLDERS:
        if folder["id"] in persona:
            continue
        suboject = api.content.create(type="Document",
                                      id=folder["id"],
                                      title=folder["title"],
                                      container=persona)
        create_default_blocks(context=suboject)
        subobjectConstraints = ISelectableConstrainTypes(suboject)
        subobjectConstraints.setConstrainTypesMode(1)
        subobjectConstraints.setLocallyAllowedTypes(folder["contains"])
예제 #38
0
def restrict_types(context, types):
    constraints = ISelectableConstrainTypes(context)
    constraints.setConstrainTypesMode(1)
    constraints.setLocallyAllowedTypes(types)
예제 #39
0
 def test_create_of_constrained_content_type_raises_unauthorized(self):
     constrains = ISelectableConstrainTypes(self.folder)
     constrains.setConstrainTypesMode(1)
     constrains.setLocallyAllowedTypes(["File"])
     with self.assertRaises(Unauthorized):
         create(self.folder, "Document", "my-document")
def constrain_types(folder, ftis):
    aspect = ISelectableConstrainTypes(folder)
    aspect.setConstrainTypesMode(1)
    aspect.setLocallyAllowedTypes(ftis)
    aspect.setImmediatelyAddableTypes(ftis)
예제 #41
0
    def test_create_constraints(self):
        """Test the constraints when creating content."""
        from plone.api.exc import InvalidParameterError
        from plone.api.exc import MissingParameterError

        # This will definitely fail
        with self.assertRaises(MissingParameterError):
            api.content.create()

        # Check the constraints for the type container
        with self.assertRaises(MissingParameterError):
            api.content.create(
                type='Document',
                id='test-doc',
            )

        # Check the constraints for the type parameter
        container = mock.Mock()
        with self.assertRaises(MissingParameterError):
            api.content.create(
                container=container,
                id='test-doc',
            )

        # Check the constraints for id and title parameters
        with self.assertRaises(MissingParameterError):
            api.content.create(
                container=container,
                type='Document',
            )

        # Check the constraints for allowed types in the container
        container = self.events
        with self.assertRaises(InvalidParameterError):
            api.content.create(
                container=container,
                type='foo',
                id='test-foo',
            )

        # Check the constraints for allowed types in the container if
        # the container is the portal
        container = self.portal
        with self.assertRaises(InvalidParameterError) as cm:
            api.content.create(
                container=container,
                type='foo',
                id='test-foo',
            )

        # Check if the underlying error message is included
        # in the InvalidParameterError message
        self.assertIn(
            'No such content type: foo',
            str(cm.exception),
        )

        # Check the constraints for allowed types in the container
        # Create a folder
        folder = api.content.create(
            container=container,
            type='Folder',
            id='test-folder',
        )
        assert folder

        # Constraint the allowed types
        ENABLED = 1
        if getattr(aq_base(folder), 'setConstrainTypesMode', None):  # AT
            folder.setConstrainTypesMode(ENABLED)
            folder.setLocallyAllowedTypes(('News Item', ))
        else:  # DX
            from Products.CMFPlone.interfaces import ISelectableConstrainTypes
            constraints = ISelectableConstrainTypes(folder)
            constraints.setConstrainTypesMode(ENABLED)
            constraints.setLocallyAllowedTypes(('News Item', ))

        with self.assertRaises(InvalidParameterError):
            api.content.create(
                container=folder,
                type='Document',
                id='test-doc',
            )
예제 #42
0
    def test_create_constraints(self):
        """Test the constraints when creating content."""
        from plone.api.exc import InvalidParameterError
        from plone.api.exc import MissingParameterError

        # This will definitely fail
        with self.assertRaises(MissingParameterError):
            api.content.create()

        # Check the constraints for the type container
        with self.assertRaises(MissingParameterError):
            api.content.create(
                type='Document',
                id='test-doc',
            )

        # Check the constraints for the type parameter
        container = mock.Mock()
        with self.assertRaises(MissingParameterError):
            api.content.create(
                container=container,
                id='test-doc',
            )

        # Check the constraints for id and title parameters
        with self.assertRaises(MissingParameterError):
            api.content.create(container=container, type='Document')

        # Check the constraints for allowed types in the container
        container = self.events
        with self.assertRaises(InvalidParameterError):
            api.content.create(
                container=container,
                type='foo',
                id='test-foo',
            )

        # Check the constraints for allowed types in the container if
        # the container is the portal
        container = self.portal
        with self.assertRaises(InvalidParameterError) as cm:
            api.content.create(container=container, type='foo', id='test-foo')

        # Check if the underlying error message is included
        # in the InvalidParameterError message
        self.assertIn('No such content type: foo', cm.exception.message)

        # Check the constraints for allowed types in the container
        # Create a folder
        folder = api.content.create(container=container,
                                    type='Folder',
                                    id='test-folder')
        assert folder

        # Constraint the allowed types
        ENABLED = 1
        if getattr(aq_base(folder), 'setConstrainTypesMode', None):  # AT
            folder.setConstrainTypesMode(ENABLED)
            folder.setLocallyAllowedTypes(('News Item', ))
        else:  # DX
            from Products.CMFPlone.interfaces import ISelectableConstrainTypes
            constraints = ISelectableConstrainTypes(folder)
            constraints.setConstrainTypesMode(ENABLED)
            constraints.setLocallyAllowedTypes(('News Item', ))

        with self.assertRaises(InvalidParameterError):
            api.content.create(container=folder,
                               type='Document',
                               id='test-doc')
예제 #43
0
 def migrate_typerestriction(self):
     constraints = ISelectableConstrainTypes(self.new)
     constraints.setConstrainTypesMode(ENABLED)
     constraints.setImmediatelyAddableTypes(self.new_allowed)
     constraints.setLocallyAllowedTypes(self.new_allowed)