示例#1
0
    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 test_form_bad_save(self):
        aspect = ISelectableConstrainTypes(self.folder)
        constraint_before = aspect.getConstrainTypesMode()
        assert constraint_before != 1, ("Default constraint should not be 1. "
                                        "Test is outdated.")

        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()
        ctrl = lambda name: self.browser.getControl(name=name)
        self.browser.getControl("Type restrictions").value = ['1']
        ctrl("form.widgets.allowed_types:list").value = ["Document"]
        ctrl("form.widgets.secondary_types:list").value = ["Document", "Folder"]
        self.browser.getControl("Save").click()
        self.assertEqual(constraint_before, aspect.getConstrainTypesMode())
        self.assertTrue('Error' in self.browser.contents)
    def test_foo_folder_constraintypes(self):
        foo = self.portal.get('foo')

        if IS_PLONE_5 or IS_PLONE_APP_MULTILINGUAL_2:
            constrains = ISelectableConstrainTypes(foo)
            self.assertEqual(constrains.getConstrainTypesMode(),
                             constraintypes.ENABLED,
                             'Constraint types are not enabled on folder foo')

            self.assertItemsEqual(constrains.getImmediatelyAddableTypes(),
                                  ['Folder'],
                                  'Immediately addable types are not configured well')

            self.assertItemsEqual(constrains.getLocallyAllowedTypes(),
                                  ['Folder', 'Document'],
                                  'Locally addable types are not configured well')

        else:
            self.assertEqual(foo.getConstrainTypesMode(),
                             constraintypes.ENABLED,
                             'Constraint types are not enabled on folder foo')

            self.assertEqual(foo.getImmediatelyAddableTypes(),
                             ('Folder',),
                             'Immediately addable types are not configured well')

            self.assertEqual(foo.getLocallyAllowedTypes(),
                             ('Folder', 'Document'),
                             'Locally addable types are not configured well')
示例#4
0
    def test_form_bad_save(self):
        aspect = ISelectableConstrainTypes(self.folder)
        constraint_before = aspect.getConstrainTypesMode()
        assert constraint_before != 1, ("Default constraint should not be 1. "
                                        "Test is outdated.")

        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()
        ctrl = lambda name: self.browser.getControl(name=name)
        self.browser.getControl("Type restrictions").value = ['1']
        ctrl("form.widgets.allowed_types:list").value = ["Document"]
        ctrl("form.widgets.secondary_types:list").value = [
            "Document", "Folder"
        ]
        self.browser.getControl("Save").click()
        self.assertEqual(constraint_before, aspect.getConstrainTypesMode())
        self.assertTrue('Error' in self.browser.contents)
示例#5
0
    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
示例#6
0
 def export_constraints(self, item, obj):
     constrains = ISelectableConstrainTypes(obj, None)
     if constrains is None:
         return item
     if constrains.getConstrainTypesMode() == ENABLED:
         key = "exportimport.constrains"
         item[key] = {
             "locally_allowed_types": constrains.getLocallyAllowedTypes(),
             "immediately_addable_types": constrains.getImmediatelyAddableTypes(),
         }
     return item
示例#7
0
    def test_form_bad_save(self):
        aspect = ISelectableConstrainTypes(self.folder)
        constraint_before = aspect.getConstrainTypesMode()
        assert constraint_before != 1, ('Default constraint should not be 1. '
                                        'Test is outdated.')

        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()

        def ctrl(name):
            return self.browser.getControl(name=name)

        self.browser.getControl('Type restrictions').value = ['1']
        ctrl('form.widgets.allowed_types:list').value = ['Document']
        ctrl('form.widgets.secondary_types:list').value = [
            'Document', 'Folder'
        ]
        self.browser.getControl('Save').click()
        self.assertEqual(constraint_before, aspect.getConstrainTypesMode())
        self.assertTrue('Error' in self.browser.contents)
示例#8
0
    def test_form_bad_save(self):
        aspect = ISelectableConstrainTypes(self.folder)
        constraint_before = aspect.getConstrainTypesMode()
        assert constraint_before != 1, ('Default constraint should not be 1. '
                                        'Test is outdated.')

        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()

        def ctrl(name):
            return self.browser.getControl(name=name)

        self.browser.getControl('Type restrictions').value = ['1']
        ctrl('form.widgets.allowed_types:list').value = ['Document']
        ctrl('form.widgets.secondary_types:list').value = [
            'Document',
            'Folder'
        ]
        self.browser.getControl('Save').click()
        self.assertEqual(constraint_before, aspect.getConstrainTypesMode())
        self.assertTrue('Error' in self.browser.contents)
示例#9
0
 def test_form_save_restrictions(self):
     self.browser.open(self.folder_url)
     self.browser.getLink('Restrictions').click()
     ctrl = lambda name: self.browser.getControl(name=name)
     self.browser.getControl("Type restrictions").value = ['1']
     ctrl("form.widgets.allowed_types:list").value = ["Document", "Folder"]
     ctrl("form.widgets.secondary_types:list").value = ["Document"]
     self.browser.getControl("Save").click()
     aspect = ISelectableConstrainTypes(self.folder)
     self.assertEqual(1, aspect.getConstrainTypesMode())
     self.assertEqual(["Document", "Folder"],
                      aspect.getLocallyAllowedTypes())
     self.assertEqual(["Folder"], aspect.getImmediatelyAddableTypes())
 def test_form_save_restrictions(self):
     self.browser.open(self.folder_url)
     self.browser.getLink('Restrictions').click()
     ctrl = lambda name: self.browser.getControl(name=name)
     self.browser.getControl("Type restrictions").value = ['1']
     ctrl("form.widgets.allowed_types:list").value = ["Document", "Folder"]
     ctrl("form.widgets.secondary_types:list").value = ["Document"]
     self.browser.getControl("Save").click()
     aspect = ISelectableConstrainTypes(self.folder)
     self.assertEqual(1, aspect.getConstrainTypesMode())
     self.assertEqual(["Document", "Folder"],
                       aspect.getLocallyAllowedTypes())
     self.assertEqual(["Folder"], aspect.getImmediatelyAddableTypes())
示例#11
0
    def test_form_save_restrictions(self):
        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()

        def ctrl(name):
            return self.browser.getControl(name=name)

        self.browser.getControl('Type restrictions').value = ['1']
        ctrl('form.widgets.allowed_types:list').value = ['Document', 'Folder']
        ctrl('form.widgets.secondary_types:list').value = ['Document']
        self.browser.getControl('Save').click()
        aspect = ISelectableConstrainTypes(self.folder)
        self.assertEqual(1, aspect.getConstrainTypesMode())
        self.assertEqual(['Document', 'Folder'],
                         aspect.getLocallyAllowedTypes())
        self.assertEqual(['Folder'], aspect.getImmediatelyAddableTypes())
示例#12
0
    def test_form_save_restrictions(self):
        self.browser.open(self.folder_url)
        self.browser.getLink('Restrictions').click()

        def ctrl(name):
            return self.browser.getControl(name=name)

        self.browser.getControl('Type restrictions').value = ['1']
        ctrl('form.widgets.allowed_types:list').value = ['Document', 'Folder']
        ctrl('form.widgets.secondary_types:list').value = ['Document']
        self.browser.getControl('Save').click()
        aspect = ISelectableConstrainTypes(self.folder)
        self.assertEqual(1, aspect.getConstrainTypesMode())
        self.assertEqual(
            ['Document', 'Folder'],
            aspect.getLocallyAllowedTypes()
        )
        self.assertEqual(['Folder'], aspect.getImmediatelyAddableTypes())
 def test_constrainTypesModeValidSet(self):
     behavior = ISelectableConstrainTypes(self.folder)
     behavior.setConstrainTypesMode(constrains.ENABLED)
     self.assertEqual(constrains.ENABLED, behavior.getConstrainTypesMode())
 def test_constrainTypesModeDefault(self):
     behavior1 = ISelectableConstrainTypes(self.folder)
     behavior2 = ISelectableConstrainTypes(self.inner_folder)
     self.assertEqual(constrains.DISABLED,
                      behavior1.getConstrainTypesMode())
     self.assertEqual(constrains.ACQUIRE, behavior2.getConstrainTypesMode())
示例#15
0
    def import_object(self, filepath, container=None):
        fi = open(filepath)
        file_read = fi.read()
        fi.close()
        try:
            data = mjson.loads(file_read)
        except Exception:
            print("Skipping {}; Unable to read JSON data".format(filepath))
            return
        if filepath.endswith('__folder__'):
            filepath = '/'.join(filepath.split('/')[:-1])

        skipped = False
        if data['portal_type'] in skip_types:
            print('Skipping omitted type {type}'.format(
                type=data['portal_type']))
            skipped = True
        if only_types and data['portal_type'] not in only_types:
            print("Skipping {type} at {path}, not in only_types.".format(
                type=data['portal_type'], path=filepath))
            skipped = True
        if import_paths:
            do_import = False
            for import_path in import_paths:
                if filepath.startswith('{}/{}'.format(args.export_directory,
                                                      import_path)):
                    do_import = True
                if import_path.startswith(
                        filepath[len(args.export_directory):].lstrip('/') +
                        '/'):
                    # Don't skip folders on the way to import_paths
                    do_import = True
            if not do_import:
                print("Skipping {path}, not in import_paths".format(
                    path=filepath))
                skipped = True
        if skip_paths:
            for skip_path in skip_paths:
                if filepath.lower().startswith('{}/{}'.format(
                        args.export_directory, skip_path)):
                    print(
                        "Skipping {path}, in skip_paths".format(path=filepath))
                    skipped = True
        if skipped:
            if os.path.isdir(filepath) and len(os.listdir(filepath)):
                logger.warn('{path} contains additional content that will be '
                            'skipped.'.format(path=filepath))
            return

        original_path = filepath[len(args.export_directory):]
        if retain_paths:
            importtype = get_import_type(data, original_path, 'retain_paths')
        else:
            importtype = get_import_type(data, original_path)
        path = importtype.get_path()

        if container is None:
            logger.warn(
                'Skipped {} because of creation error'.format(filepath))
            return
        _id = path.split('/')[-1]

        create = True
        if _id in container.objectIds():
            if args.overwrite:
                existing = container[_id]
                if IFolder.providedBy(existing):
                    if len(existing.objectIds()):
                        print("OVERWRITE: Deleting non-empty container {path}".
                              format(path=path))
                else:
                    print("OVERWRITE: Deleting content item at {path}".format(
                        path=path))
                api.content.delete(container[_id])
            else:
                create = False

        creation_data = importtype.get_data()
        pc_data = importtype.get_post_creation_data()
        creation_data['container'] = container

        aspect = ISelectableConstrainTypes(container, None)
        if aspect:
            if (aspect.getConstrainTypesMode() != 1 or [creation_data['type']]
                    != aspect.getImmediatelyAddableTypes()):
                aspect.setConstrainTypesMode(1)
                aspect.setImmediatelyAddableTypes([creation_data['type']])
        if create:
            if ignore_uuids and '_plone.uuid' in creation_data:
                del creation_data['_plone.uuid']

            obj = None
            if not args.overwrite and (_id in container.objectIds()):
                print('Skipping {path}, already exists. Use --overwrite to'
                      ' create anyway.'.format(path=path))
                return
            elif (not ignore_uuids
                  and api.content.get(UID=creation_data['_plone.uuid'])
                  is not None):
                logger.warn(
                    'Skipping {path}, content with its UUID already exists.'
                    'Use --ignore-uuids to create anyway.'.format(path=path))
                return
            else:
                try:
                    obj = api.content.create(safe_id=True, **creation_data)
                    print('Created {path}'.format(path=path))
                    self.imported_count += 1
                    if self.imported_count % 50 == 0:
                        print('%i processed, committing' % self.imported_count)
                        transaction.commit()
                except api.exc.InvalidParameterError:
                    if stop_if_exception:
                        logger.error(
                            'Error creating content {}'.format(filepath),
                            exc_info=True)
                        if pdb_if_exception:
                            pdb.set_trace()
                        raise
                    logger.error('Error creating content {}'.format(filepath),
                                 exc_info=True)
                    return

    # TODO check default folder pages came over as folder with rich text tile
    # TODO any folder pages without default page should have content listing tile
        else:
            obj = container[_id]
            for key, value in creation_data.items():
                if key not in ('id', 'type'):
                    setattr(obj, key, value)

        if obj is not None:
            if path != original_path:
                storage = getUtility(IRedirectionStorage)
                rpath = os.path.join('/'.join(site.getPhysicalPath()),
                                     original_path.strip('/'))
                storage.add(rpath, "/".join(obj.getPhysicalPath()))

            obj.contentLayout = importtype.layout
            importtype.post_creation(obj, post_creation_data=pc_data)
            if not args.skip_transitioning and data['state']:
                # transition item only if it needs it
                state = api.content.get_state(obj=obj)
                if state != data['state']:
                    try:
                        print('Transitioning %s to %s' %
                              (obj.id, data['state']))
                        api.content.transition(obj, to_state=data['state'])
                    except Exception:
                        logger.error(
                            "Error transitioning %s to %s, maybe workflows"
                            " don't match up" % (obj.id, data['state']))
                        # pass
                        if stop_if_exception:
                            if pdb_if_exception:
                                pdb.set_trace()
                            raise

            # set workflow / review history
            if 'review_history' in data:
                review_history = data['review_history']
                wtool = api.portal.get_tool(name='portal_workflow')
                # loop over all workflow chains (usually only 1)
                for workflow_id in wtool.getChainFor(obj):
                    obj.workflow_history[workflow_id] = review_history
            else:
                logger.warn('No review history on {obj}'.format(obj=obj))

            fix_html_images(obj)
            obj.reindexObject()
            try:
                modification_date = data['data']['modification_date']
                obj.setModificationDate(modification_date)
                obj.reindexObject(idxs=['modified'])
                logger.info('    set modification date to %s' %
                            modification_date)
            except Exception:
                logger.info(
                    'Could not set modification date on {obj}'.format(obj=obj))
            return obj
 def test_constrainTypesModeDefault(self):
     behavior1 = ISelectableConstrainTypes(self.folder)
     behavior2 = ISelectableConstrainTypes(self.inner_folder)
     self.assertEqual(
         constrains.DISABLED, behavior1.getConstrainTypesMode())
     self.assertEqual(constrains.ACQUIRE, behavior2.getConstrainTypesMode())
示例#17
0
def import_object(filepath, count):
    fi = open(filepath)
    data = mjson.loads(fi.read())
    fi.close()
    if filepath.endswith('__folder__'):
        filepath = '/'.join(filepath.split('/')[:-1])

    if data['portal_type'] in ('Topic', 'Collection', 'PressRoom'):
        return

    original_path = filepath[len(args.export_directory):]
    importtype = get_import_type(data, original_path, _read_phase)
    path = importtype.get_path()
    folder = recursive_create_path('/'.join(path.split('/')[:-1]))
    if folder is None:
        print('Skipped {} because of creation error'.format(filepath))
    _id = path.split('/')[-1]

    create = True
    if _id in folder.objectIds():
        if args.overwrite:
            if data['portal_type'] == 'Folder':
                cnt = folder[_id]
                if len(folder.objectIds()) == 1 or len(cnt.objectIds()) == 0:
                    api.content.delete(folder[_id])
            else:
                api.content.delete(folder[_id])
        else:
            create = False

    print('import path: %s' % path)
    creation_data = importtype.get_data()
    creation_data['container'] = folder

    aspect = ISelectableConstrainTypes(folder, None)
    if aspect:
        if (aspect.getConstrainTypesMode() != 1 or
            [creation_data['type']] != aspect.getImmediatelyAddableTypes()):
            aspect.setConstrainTypesMode(1)
            aspect.setImmediatelyAddableTypes([creation_data['type']])

    if create:
        try:
            obj = api.content.create(**creation_data)
        except api.exc.InvalidParameterError:
            return logger.error('Error creating content {}'.format(filepath),
                                exc_info=True)
    else:
        obj = folder[_id]
        for key, value in creation_data.items():
            if key not in ('id', 'type'):
                setattr(obj, key, value)

    if path != original_path:
        storage = getUtility(IRedirectionStorage)
        rpath = os.path.join('/'.join(site.getPhysicalPath()),
                             original_path.strip('/'))
        storage.add(rpath, "/".join(obj.getPhysicalPath()))

    importtype.post_creation(obj)
    if data['state']:
        try:
            api.content.transition(obj, to_state=data['state'])
        except:
            # maybe workflows do not match up
            pass

    fix_html_images(obj)
    obj.reindexObject()

    if count % 50 == 0:
        print('%i processed, committing' % count)
        transaction.commit()
        app._p_jar.invalidateCache()  # noqa
        transaction.begin()
        app._p_jar.sync()  # noqa
 def test_constrainTypesModeValidSet(self):
     behavior = ISelectableConstrainTypes(self.folder)
     behavior.setConstrainTypesMode(constrains.ENABLED)
     self.assertEqual(constrains.ENABLED, behavior.getConstrainTypesMode())
示例#19
0
def castle(context):
    if not context.readDataFile('castle.cms.install.txt'):
        return
    site = context.getSite()

    # create feed folder
    folder = utils.recursive_create_path(site, '/feeds')
    try:
        if api.content.get_state(obj=folder) != 'published':
            api.content.transition(obj=folder, transition='publish')
    except WorkflowException:
        pass

    type_ = 'Collection'
    aspect = ISelectableConstrainTypes(folder, None)

    if (aspect and (aspect.getConstrainTypesMode() != 1
                    or [type_] != aspect.getImmediatelyAddableTypes())):
        aspect.setConstrainTypesMode(1)
        aspect.setImmediatelyAddableTypes([type_])
    if not getattr(folder, 'exclude_from_nav', False):
        folder.exclude_from_nav = True
        folder.reindexObject()

    if 'front-page' not in site:
        api.content.create(type='Document', id='front-page', container=site)
        site.setDefaultPage('front-page')

    front_page = site['front-page']

    front_page.title = u'Welcome to Castle'
    front_page.description = u'Congratulations! You have successfully installed Castle.'

    # enable syndication by default and modify some of the settings
    registry = getUtility(IRegistry)
    settings = registry.forInterface(ISiteSyndicationSettings)
    settings.allowed = True
    settings.default_enabled = False
    settings.show_author_info = False
    settings.search_rss_enabled = False

    utils.add_indexes(INDEXES)
    utils.delete_indexes(REMOVE_INDEXES)
    utils.add_metadata(METADATA)
    utils.delete_metadata(REMOVE_METADATA)

    # add some better defaults for documentviewer
    settings = DVGlobalSettings(site)
    settings.auto_layout_file_types = [
        'pdf', 'word', 'excel', 'ppt', 'rft', 'ps', 'photoshop', 'visio',
        'palm'
    ]

    # delete some records for mosaic tinymce toolbar
    for action_type in ('plone_app_z3cform_wysiwyg_widget_WysiwygWidget',
                        'plone_app_z3cform_wysiwyg_widget_WysiwygFieldWidget',
                        'plone_app_widgets_dx_RichTextWidget',
                        'plone_app_z3cform_widget_RichTextFieldWidget'):
        try:
            data = registry['plone.app.mosaic.widget_actions.%s.actions' %
                            action_type]
            _removeTinyMCEActions(data)
            registry['plone.app.mosaic.widget_actions.%s.actions' %
                     action_type] = data
        except KeyError:
            pass

    for key in (
            'plone.app.mosaic.structure_tiles.text.available_actions',
            'plone.app.mosaic.app_tiles.plone_app_standardtiles_rawhtml.available_actions'
    ):
        try:
            data = registry[key]
            _removeTinyMCEActions(data)
            registry[key] = data
        except KeyError:
            pass

    # password reset timeout interval...
    portal_password_reset = api.portal.get_tool('portal_password_reset')
    portal_password_reset.setExpirationTimeout(6)

    # update default session duration
    site.acl_users.session.timeout = 1 * 60 * 60  # 1 hr
    site.acl_users.session.refresh_interval = 5 * 60  # 5 minutes