Example #1
0
    def test_get_tool(self):
        """ Test to validate the tool name """

        self.assertEqual(portal.get_tool(name='portal_catalog'),
                         getToolByName(self.portal, 'portal_catalog'))
        self.assertEqual(portal.get_tool(name='portal_membership'),
                         getToolByName(self.portal, 'portal_membership'))
Example #2
0
def get_users(groupname=None, group=None):
    """Get all users or all users filtered by group.

    Arguments ``group`` and ``groupname`` are mutually exclusive.
    You can either set one or the other, but not both.

    :param groupname: Groupname of the group of which to return users. If set,
        only return users that are member of this group.
    :type username: string
    :param group: Group of which to return users.
        If set, only return users that are member of this group.
    :type group: GroupData object
    :returns: All users (optionally filtered by group)
    :rtype: List of MemberData objects
    :Example: :ref:`user_get_all_users_example`,
        :ref:`user_get_groups_users_example`
    """
    if groupname:
        group_tool = portal.get_tool('portal_groups')
        group = group_tool.getGroupById(groupname)
        if not group:
            raise GroupNotFoundError

    portal_membership = portal.get_tool('portal_membership')

    if group:
        return group.getGroupMembers()
    else:
        return portal_membership.listMembers()
Example #3
0
    def test_get_tool_constraints(self):
        """Test the constraints for getting a tool."""

        # When no parameters are given an error is raised
        from plone.api.exc import MissingParameterError
        with self.assertRaises(MissingParameterError):
            portal.get_tool()
Example #4
0
def get_users(groupname=None, group=None):
    """Get all users or all users filtered by group.

    Arguments ``group`` and ``groupname`` are mutually exclusive.
    You can either set one or the other, but not both.

    :param groupname: Groupname of the group of which to return users. If set,
        only return users that are member of this group.
    :type username: string
    :param group: Group of which to return users.
        If set, only return users that are member of this group.
    :type group: GroupData object
    :returns: All users (optionlly filtered by group)
    :rtype: List of MemberData objects
    :Example: :ref:`user_get_all_users_example`,
        :ref:`user_get_groups_users_example`
    """
    if groupname:
        group_tool = portal.get_tool('portal_groups')
        group = group_tool.getGroupById(groupname)
        if not group:
            raise GroupNotFoundError

    portal_membership = portal.get_tool('portal_membership')

    if group:
        return group.getGroupMembers()
    else:
        return portal_membership.listMembers()
Example #5
0
def analyses_creation_date_recover():
    """
    This function walks over all Analysis Request objects, obtains their
    associate analyses and checks if their creation date is older than the
    Analysis Request one. If this condition is met, the system sets the
    analyses creation date with the Analysis Request one.
    :return: Boolean. True if the process succeed, and False otherwise.
    """

    ar_catalog = get_tool(CATALOG_ANALYSIS_REQUEST_LISTING)
    ans_catalog = get_tool(CATALOG_ANALYSIS_LISTING)
    # Getting all analysis requests to walk through
    ar_brains = ar_catalog()
    total_ars = len(ar_brains)
    total_iterated = 0
    logger.info("Analysis Requests to walk over: {}".format(total_ars))
    total_modified = 0
    for ar_brain in ar_brains:
        ans_brains = ans_catalog({"getAnalysisRequestUID": ar_brain.UID})
        analyses_modified = set_correct_created_date(ar_brain.created,
                                                     ans_brains)
        total_modified += analyses_modified
        total_iterated = commit_action(total_ars, total_iterated,
                                       total_modified)
    transaction.commit()
    logger.info("Analyses creation date sanitized.")
    return True
Example #6
0
def analyses_creation_date_recover():
    """
    This function walks over all Analysis Request objects, obtains their
    associate analyses and checks if their creation date is older than the
    Analysis Request one. If this condition is met, the system sets the
    analyses creation date with the Analysis Request one.
    :return: Boolean. True if the process succeed, and False otherwise.
    """

    ar_catalog = get_tool(CATALOG_ANALYSIS_REQUEST_LISTING)
    ans_catalog = get_tool(CATALOG_ANALYSIS_LISTING)
    # Getting all analysis requests to walk through
    ar_brains = ar_catalog()
    total_ars = len(ar_brains)
    total_iterated = 0
    logger.info("Analysis Requests to walk over: {}".format(total_ars))
    total_modified = 0
    for ar_brain in ar_brains:
        ans_brains = ans_catalog({"getRequestUID": ar_brain.UID})
        analyses_modified = set_correct_created_date(
            ar_brain.created, ans_brains)
        total_modified += analyses_modified
        total_iterated = commit_action(
            total_ars, total_iterated, total_modified)
    transaction.commit()
    logger.info("Analyses creation date sanitized.")
    return True
Example #7
0
    def test_get_tool_constraints(self):
        """Test the constraints for getting a tool."""

        # When no parameters are given an error is raised
        from plone.api.exc import MissingParameterError
        with self.assertRaises(MissingParameterError):
            portal.get_tool()
Example #8
0
    def test_get_tool_tool_not_found(self):
        """Test that error msg lists available tools if a tool is not found."""

        with self.assertRaises(InvalidParameterError) as cm:
            portal.get_tool('portal_foo')

        self.maxDiff = None  # to see assert diff
        self.assertMultiLineEqual(
            cm.exception.message,
            "Cannot find a tool with name 'portal_foo'.\n"
            "Available tools are:\n"
            "portal_setup\n"
            "portal_actionicons\n"
            "portal_actions\n"
            "portal_atct\n"
            "portal_calendar\n"
            "portal_catalog\n"
            "portal_controlpanel\n"
            "portal_css\n"
            "portal_diff\n"
            "portal_factory\n"
            "portal_groupdata\n"
            "portal_groups\n"
            "portal_interface\n"
            "portal_javascripts\n"
            "portal_kss\n"
            "portal_memberdata\n"
            "portal_membership\n"
            "portal_metadata\n"
            "portal_migration\n"
            "portal_password_reset\n"
            "portal_properties\n"
            "portal_quickinstaller\n"
            "portal_registration\n"
            "portal_skins\n"
            "portal_syndication\n"
            "portal_types\n"
            "portal_uidannotation\n"
            "portal_uidgenerator\n"
            "portal_uidhandler\n"
            "portal_undo\n"
            "portal_url\n"
            "portal_view_customizations\n"
            "portal_workflow\n"
            "portal_form_controller\n"
            "portal_transforms\n"
            "portal_archivist\n"
            "portal_historiesstorage\n"
            "portal_historyidhandler\n"
            "portal_modifier\n"
            "portal_purgepolicy\n"
            "portal_referencefactories\n"
            "portal_repository\n"
            "portal_languages\n"
            "portal_tinymce\n"
            "portal_registry\n"
            "portal_discussion"
        )
Example #9
0
    def test_get_tool_tool_not_found(self):
        """Test that error msg lists available tools if a tool is not found."""

        with self.assertRaises(InvalidParameterError) as cm:
            portal.get_tool('portal_foo')

        self.maxDiff = None  # to see assert diff
        self.assertMultiLineEqual(
            cm.exception.message,
            "Cannot find a tool with name 'portal_foo'. \n"
            "Available tools are:\n"
            "portal_setup\n"
            "portal_actionicons\n"
            "portal_actions\n"
            "portal_atct\n"
            "portal_calendar\n"
            "portal_catalog\n"
            "portal_controlpanel\n"
            "portal_css\n"
            "portal_diff\n"
            "portal_factory\n"
            "portal_groupdata\n"
            "portal_groups\n"
            "portal_interface\n"
            "portal_javascripts\n"
            "portal_kss\n"
            "portal_memberdata\n"
            "portal_membership\n"
            "portal_metadata\n"
            "portal_migration\n"
            "portal_password_reset\n"
            "portal_properties\n"
            "portal_quickinstaller\n"
            "portal_registration\n"
            "portal_skins\n"
            "portal_syndication\n"
            "portal_types\n"
            "portal_uidannotation\n"
            "portal_uidgenerator\n"
            "portal_uidhandler\n"
            "portal_undo\n"
            "portal_url\n"
            "portal_view_customizations\n"
            "portal_workflow\n"
            "portal_form_controller\n"
            "portal_transforms\n"
            "portal_archivist\n"
            "portal_historiesstorage\n"
            "portal_historyidhandler\n"
            "portal_modifier\n"
            "portal_purgepolicy\n"
            "portal_referencefactories\n"
            "portal_repository\n"
            "portal_languages\n"
            "portal_tinymce\n"
            "portal_registry\n"
            "portal_discussion")
Example #10
0
def get_roles(username=None, user=None, obj=None, inherit=True):
    """Get user's site-wide or local roles.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the currently authenticated member will be used.

    :param username: Username of the user for which to get roles.
    :type username: string
    :param user: User object for which to get roles.
    :type user: MemberData object
    :param obj: If obj is set then return local roles on this context.
        If obj is not given, the site root local roles will be returned.
    :type obj: content object
    :param inherit: if obj is set and inherit is False, only return
        local roles
    :type inherit: bool
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_roles_example`
    """
    portal_membership = portal.get_tool('portal_membership')

    if username is None:
        if user is None:
            username = portal_membership.getAuthenticatedMember().getId()
        else:
            username = user.getId()

    if username is None and user is None:
        user = portal_membership.getAuthenticatedMember()
    else:
        user = portal_membership.getMemberById(username)

    if user is None:
        raise UserNotFoundError

    if obj is not None:
        if inherit:
            return user.getRolesInContext(obj)
        else:
            # Include roles inherited from being the member of a group
            # and from adapters granting local roles
            plone_user = user.getUser()
            principal_ids = list(plone_user.getGroups())
            principal_ids.insert(0, plone_user.getId())
            roles = set([])
            pas = portal.get_tool('acl_users')
            for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
                for adapter in lrmanager._getAdapters(obj):
                    for pid in principal_ids:
                        roles.update(adapter.getRoles(pid))
            return list(roles)
    else:
        return user.getRoles()
Example #11
0
def get_roles(username=None, user=None, obj=None, inherit=True):
    """Get user's site-wide or local roles.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the currently authenticated member will be used.

    :param username: Username of the user for which to get roles.
    :type username: string
    :param user: User object for which to get roles.
    :type user: MemberData object
    :param obj: If obj is set then return local roles on this context.
        If obj is not given, the site root local roles will be returned.
    :type obj: content object
    :param inherit: if obj is set and inherit is False, only return
        local roles
    :type inherit: bool
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_roles_example`
    """
    portal_membership = portal.get_tool('portal_membership')

    if username is None:
        if user is None:
            username = portal_membership.getAuthenticatedMember().getId()
        else:
            username = user.getId()

    if username is None and user is None:
        user = portal_membership.getAuthenticatedMember()
    else:
        user = portal_membership.getMemberById(username)

    if user is None:
        raise UserNotFoundError

    if obj is not None:
        if inherit:
            return user.getRolesInContext(obj)
        else:
            # Include roles inherited from being the member of a group
            # and from adapters granting local roles
            plone_user = user.getUser()
            principal_ids = list(plone_user.getGroups())
            principal_ids.insert(0, plone_user.getId())
            roles = set()
            pas = portal.get_tool('acl_users')
            for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
                for adapter in lrmanager._getAdapters(obj):
                    for principal_id in principal_ids:
                        roles.update(adapter.getRoles(principal_id))
            return list(roles)
    else:
        return user.getRoles()
Example #12
0
    def test_get_tool(self):
        """Test to validate the tool name."""

        self.assertEqual(
            portal.get_tool(name='portal_catalog'),
            getToolByName(self.portal, 'portal_catalog'),
        )
        self.assertEqual(
            portal.get_tool(name='portal_membership'),
            getToolByName(self.portal, 'portal_membership'),
        )
Example #13
0
    def setUp(self):
        """Shared test environment set-up, ran before every test."""
        self.portal = self.layer['portal']

        # Mock the mail host so we can test sending the email
        mockmailhost = MockMailHost('MailHost')

        if not getattr(mockmailhost, 'smtp_host', None):
            mockmailhost.smtp_host = 'localhost'

        self.portal.MailHost = mockmailhost
        sm = self.portal.getSiteManager()
        sm.registerUtility(component=mockmailhost, provided=IMailHost)

        self.mailhost = portal.get_tool('MailHost')
        if HAS_PLONE5:
            portal.set_registry_record(
                'plone.email_from_name',
                u'Portal Owner',
            )
            portal.set_registry_record(
                'plone.email_from_address',
                '*****@*****.**',
            )
        else:
            self.portal._updateProperty(
                'email_from_name',
                'Portal Owner',
            )
            self.portal._updateProperty(
                'email_from_address',
                '*****@*****.**',
            )
Example #14
0
def get_roles(username=None, user=None, obj=None):
    """Get user's site-wide or local roles.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the currently authenticated member will be used.

    :param username: Username of the user for which to get roles.
    :type username: string
    :param user: User object for which to get roles.
    :type user: MemberData object
    :param obj: If obj is set then return local roles on this context.
        If obj is not given, the site root local roles will be returned.
    :type obj: content object
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_roles_example`
    """
    portal_membership = portal.get_tool('portal_membership')

    if username is None:
        if user is None:
            username = portal_membership.getAuthenticatedMember().getId()
        else:
            username = user.getId()

    user = portal_membership.getMemberById(username)
    if user is None:
        raise UserNotFoundError

    return user.getRolesInContext(obj) if obj is not None else user.getRoles()
Example #15
0
def get_uid(value):
    """Takes a brain or object and returns a valid UID.
    In this case, the object may come from portal_archivist, so we will
    need to do a catalog query to get the UID of the current version
    """
    if not value:
        return ''
    # Is value a brain?
    if ICatalogBrain.providedBy(value):
        value = value.getObject()
    # validate UID
    uid = value.UID()
    uc = get_tool('uid_catalog')
    if uc(UID=uid):
        # The object is valid
        return uid
    # Otherwise the object is an old version
    brains = uc(portal_type=value.portal_type, Title=value.Title())
    if not brains:
        # Cannot find UID
        raise RuntimeError('The UID for %s/%s cannot be found!' %
                           (value.portal_type, value.Title()))
    if len(brains) > 1:
        # Found multiple objects, this is a failure
        raise RuntimeError('Searching for %s/%s returned multiple objects.' %
                           (value.portal_type, value.Title()))
    return brains[0].UID
Example #16
0
def has_permission(permission, username=None, user=None, obj=None):
    """Check whether this user has the given permssion.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the authenticated member will be used.

    :param permission: The permission you wish to check
    :type permission: string
    :param username: Username of the user for which you want to check
        the permission.
    :type username: string
    :param user: User object for which you want to check the permission.
    :type user: MemberData object
    :param obj: If obj is set then check the permission on this context.
        If obj is not given, the site root will be used.
    :type obj: content object
    :raises:
        InvalidParameterError
    :returns: True if the user has the permission, False otherwise.
    :rtype: bool
    """
    if obj is None:
        obj = portal.get()

    if username is None and user is None:
        context = _nop_context_manager()
    else:
        context = env.adopt_user(username, user)

    with context:
        portal_membership = portal.get_tool('portal_membership')
        return bool(portal_membership.checkPermission(permission, obj))
Example #17
0
def catalog_setup(context):
    """
    Setup plone.app.event's indices in the catalog.
    """
    # check if we are meant or called for other migration
    if context.readDataFile('pkan-various.txt') is None:
        # Not we self so exit
        return

    catalog = portal.get_tool('portal_catalog')
    # Get fields from the different models to build an index for
    content_type_extras = [
        DCATCatalog,
        DCATCollectionCatalog,
        DCATDataset,
        DCATDistribution,
        FOAFAgent,
    ]

    field_idxs = []
    # iterate over all content_type_extra classes
    for content_type_extra in content_type_extras:
        # collect the index_fields
        field_idxs += content_type_extra._index_fields
        """build IIndexer adapters to handle the indexing and prevent
        useless indexing by stopping aquisition from working on all
        other content_types
        """
        for field in content_type_extra._index_fields:
            indexer_for_field_and_ct(field, content_type_extra.content_schema)

    indexes = catalog.Indexes
    for name in field_idxs:
        if name not in indexes:
            catalog.addIndex(name, 'FieldIndex')
Example #18
0
    def setUp(self):
        """Shared test environment set-up, ran before every test."""
        self.portal = self.layer['portal']

        # Mock the mail host so we can test sending the email
        mockmailhost = MockMailHost('MailHost')

        if not getattr(mockmailhost, 'smtp_host', None):
            mockmailhost.smtp_host = 'localhost'

        self.portal.MailHost = mockmailhost
        sm = self.portal.getSiteManager()
        sm.registerUtility(component=mockmailhost, provided=IMailHost)

        self.mailhost = portal.get_tool('MailHost')
        if HAS_PLONE5:
            portal.set_registry_record(
                'plone.email_from_name', u'Portal Owner'
            )
            portal.set_registry_record(
                'plone.email_from_address',
                '*****@*****.**'
            )
        else:
            self.portal._updateProperty('email_from_name', 'Portal Owner')
            self.portal._updateProperty(
                'email_from_address', '*****@*****.**'
            )
Example #19
0
 def __call__(self, context):
     mtool = get_tool('portal_membership')
     users = mtool.searchForMembers(roles=self.roles)
     items = [(item.getProperty('fullname'), item.getId()) for item in users]
     items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))
     items = [SimpleTerm(i[1], i[1], i[0]) for i in items]
     return SimpleVocabulary(items)
Example #20
0
def get_permissions(username=None, user=None, obj=None):
    """Get user's site-wide or local permissions.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the authenticated member will be used.

    :param username: Username of the user for which you want to check
        the permissions.
    :type username: string
    :param user: User object for which you want to check the permissions.
    :type user: MemberData object
    :param obj: If obj is set then check the permissions on this context.
        If obj is not given, the site root will be used.
    :type obj: content object
    :raises:
        InvalidParameterError
    :Example: :ref:`user_get_permissions_example`
    """
    if obj is None:
        obj = portal.get()

    if username is None and user is None:
        context = _nop_context_manager()
    else:
        context = env.adopt_user(username, user)

    result = {}
    with context:
        portal_membership = portal.get_tool("portal_membership")
        permissions = (p[0] for p in getPermissions())
        for permission in permissions:
            result[permission] = bool(portal_membership.checkPermission(permission, obj))

    return result
Example #21
0
def add_user(groupname=None, group=None, username=None, user=None):
    """Add the user to a group.

    Arguments ``groupname`` and ``group`` are mutually exclusive. You can
    either set one or the other, but not both.

    Arguments ``username`` and ``user`` are mutually exclusive. You can
    either set one or the other, but not both.

    :param groupname: Name of the group to which to add the user.
    :type groupname: string
    :param group: Group to which to add the user.
    :type group: GroupData object
    :param username: Username of the user to add to the group.
    :type username: string
    :param user: User to add to the group.
    :type user: MemberData object
    :raises:
        ValueError
    :Example: :ref:`group_add_user_example`

    """
    user_id = username or user.id
    group_id = groupname or group.id
    portal_groups = portal.get_tool('portal_groups')
    portal_groups.addPrincipalToGroup(user_id, group_id)
Example #22
0
    def test_get_localized_time(self):
        """Test getting the localized time."""
        from plone.api.exc import InvalidParameterError

        # set the expected localized date format
        name_root = "Products.CMFPlone.i18nl10n.override_dateformat."
        try:
            portal.set_registry_record(name=name_root + "Enabled", value=True)
            portal.set_registry_record(name=name_root + "date_format_long", value="%b %d, %Y %I:%M %p")
            portal.set_registry_record(name=name_root + "time_format", value="%I:%M %p")
            portal.set_registry_record(name=name_root + "date_format_short", value="%b %d, %Y")
        except InvalidParameterError:
            # before Plone 4.3, date formats were stored in portal_properties
            properties = portal.get_tool("portal_properties")
            properties.localLongTimeFormat = "%b %d, %Y %I:%M %p"
            properties.localTimeOnlyFormat = "%I:%M %p"
            properties.localTimeFormat = "%b %d, %Y"

        # tests
        result = portal.get_localized_time(datetime=DateTime(1999, 12, 31, 23, 59), long_format=True)
        self.assertEqual(result, "Dec 31, 1999 11:59 PM")

        result = portal.get_localized_time(datetime=DateTime(1999, 12, 31, 23, 59), time_only=True)
        self.assertEqual(result, "11:59 PM")

        result = portal.get_localized_time(datetime=DateTime(1999, 12, 31, 23, 59))
        self.assertEqual(result, "Dec 31, 1999")
Example #23
0
def get_roles(username=None, user=None, obj=None):
    """Get user's site-wide or local roles.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the currently authenticated member will be used.

    :param username: Username of the user for which to get roles.
    :type username: string
    :param user: User object for which to get roles.
    :type user: MemberData object
    :param obj: If obj is set then return local roles on this context.
        If obj is not given, the site root local roles will be returned.
    :type obj: content object
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_roles_example`
    """
    portal_membership = portal.get_tool('portal_membership')

    if username is None:
        if user is None:
            username = portal_membership.getAuthenticatedMember().getId()
        else:
            username = user.getId()

    user = portal_membership.getMemberById(username)
    if user is None:
        raise UserNotFoundError

    return user.getRolesInContext(obj) if obj is not None else user.getRoles()
Example #24
0
    def _set_localization_date_format(self):
        """Set the expected localized date format."""
        from plone.api.exc import InvalidParameterError

        name_root = 'Products.CMFPlone.i18nl10n.override_dateformat.'
        try:
            portal.set_registry_record(
                name=name_root + 'Enabled',
                value=True,
            )
            portal.set_registry_record(
                name=name_root + 'date_format_long',
                value='%b %d, %Y %I:%M %p',
            )
            portal.set_registry_record(
                name=name_root + 'time_format',
                value='%I:%M %p',
            )
            portal.set_registry_record(
                name=name_root + 'date_format_short',
                value='%b %d, %Y',
            )
        except InvalidParameterError:
            # before Plone 4.3, date formats were stored in portal_properties
            properties = portal.get_tool('portal_properties')
            properties.localLongTimeFormat = '%b %d, %Y %I:%M %p'
            properties.localTimeOnlyFormat = '%I:%M %p'
            properties.localTimeFormat = '%b %d, %Y'
Example #25
0
def transition(obj=None, transition=None):
    """Perform a workflow transition for the object.

    :param obj: [required] Object for which we want to perform the workflow
        transition.
    :type obj: Content object
    :param transition: [required] Name of the workflow transition.
    :type transition: string
    :raises:
        :class:`~plone.api.exc.MissingParameterError`,
        :class:`~plone.api.exc.InvalidParameterError`
    :Example: :ref:`content_transition_example`
    """
    workflow = portal.get_tool('portal_workflow')
    try:
        workflow.doActionFor(obj, transition)
    except WorkflowException:
        transitions = [
            action['id'] for action in workflow.listActions(object=obj)
        ]

        raise InvalidParameterError("Invalid transition '{0}'.\n"
                                    "Valid transitions are:\n"
                                    "{1}".format(
                                        transition,
                                        '\n'.join(sorted(transitions))))
Example #26
0
    def _reg_desc_folder(self):
        portal_catalog = get_tool('portal_catalog')
        brains = portal_catalog.searchResults(
            object_provides=IRegionalDescriptorsFolder.__identifier__)
        nat_desc_folder = brains[0].getObject()

        return nat_desc_folder
Example #27
0
def update_to_35(context):
    """ Migrate layer id from website to gis_layer_id field
    """

    return
    catalog = portal.get_tool(name='portal_catalog')
    query = {
        'portal_type': [
            'eea.climateadapt.mapgraphdataset',
        ]
    }
    results = catalog.searchResults(**query)

    for brain in results:
        obj = brain.getObject()
        websites = obj.websites

        if isinstance(websites, (list, tuple)):
            for layer_id in websites:
                if check_layer_id(layer_id):
                    obj.gis_layer_id = layer_id
                    obj.websites = [i for i in websites if i != layer_id]
                    obj.reindexObject()
                    obj._p_changed = True
                    logger.info("Migrated layer for %s", obj.absolute_url())
        elif isinstance(websites, str):
            if check_layer_id(layer_id):
                obj.gis_layer_id = websites
                obj.websites = ""
                obj.reindexObject()
                obj._p_changed = True
                logger.info("Migrated layer for %s", obj.absolute_url())
    logger.info("Finished the layer ids migration %s", obj.absolute_url())
Example #28
0
def update_to_37(context):
    return
    logger.info("Upgrading to 37")
    logger.info("Setting the proper effective date for some aceprojects")

    catalog = portal.get_tool(name='portal_catalog')
    query = {
        'portal_type': 'eea.climateadapt.aceproject',
        'review_state': 'published'
    }
    brains = catalog.searchResults(**query)

    for brain in brains:
        obj = brain.getObject()

        if obj.effective_date is None:
            wf_history = obj.workflow_history.get('cca_items_workflow', [])

            for wf in wf_history:
                if wf.get('action', '') == 'publish':
                    obj.effective_date = wf.get('time', None)
                    obj.reindexObject()
                    obj._p_changed = True

                    continue
    logger.info("Finished modifying the effective dates for aceprojects")
Example #29
0
    def test_get_tool(self):
        """ Test to validate the tool name """

        self.assertEqual(
            portal.get_tool(name='portal_catalog'),
            getToolByName(self.portal, 'portal_catalog')
        )
        self.assertEqual(
            portal.get_tool(name='portal_membership'),
            getToolByName(self.portal, 'portal_membership')
        )
        self.assertRaises(
            AttributeError,
            portal.get_tool,
            name='non_existing'
        )
Example #30
0
def get(userid=None, username=None):
    """Get a user.

    Plone provides both a unique, unchanging identifier for a user (the
    userid) and a username, which is the value a user types into the login
    form. In many cases, the values for each will be the same, but under some
    circumstances they will differ. Known instances of this behavior include:

     * using content-based members via membrane
     * users changing their email address when using email as login is enabled

    We provide the ability to look up users by either.

    :param userid: Userid of the user we want to get.
    :type userid: string
    :param username: Username of the user we want to get.
    :type username: string
    :returns: User
    :rtype: MemberData object
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_example`
    """
    if userid is not None:
        portal_membership = portal.get_tool('portal_membership')
        return portal_membership.getMemberById(userid)

    return get_member_by_login_name(
        portal.get(),
        username,
        raise_exceptions=False,
    )
Example #31
0
    def __call__(self):
        cat = get_tool('portal_catalog')

        query = {
            'review_state': 'published'
        }
        results = cat.searchResults(query)

        logger.info("Found %s objects " % len(results))

        count = 0
        options = {}
        options['create'] = False
        options['service_to_ping'] = 'http://semantic.eea.europa.eu/ping'
        for res in results:
            context = res.getObject()
            url = res.getURL()
            options['obj_url'] = url + '/@@rdf'

            logger.info("Pinging: %s", url)
            ping_CRSDS(context, options)
            logger.info("Finished pinging: %s", url)

            count += 1
            if count % 100 == 0:
                logger.info('Went through %s brains' % count)

        logger.info('Finished pinging all brains')
        return 'Finished'
Example #32
0
def update_to_41(context):
    return
    logger.info("Upgrading to 41")
    logger.info("Setting the search type to CONTENT for News/Events/Links")

    catalog = portal.get_tool(name='portal_catalog')
    query = {'portal_type': ['News Item', 'Event', 'Link']}

    brains = catalog.searchResults(**query)
    logger.info('Got %s results.' % len(brains))
    items_count = 0

    for b in brains:
        obj = b.getObject()

        items_count += 1

        if items_count % 100 == 0:
            logger.info('Went through %s brains' % items_count)

        if not hasattr(obj, 'search_type'):
            setattr(obj, 'search_type', 'CONTENT')
            obj._p_changed = True
            obj.reindexObject()
            logger.info('Reindexing object %s' % obj.absolute_url())
Example #33
0
 def get_object(self, context, value):
     """Resolve a UID to an object.
     
     :param context: context is the object containing the field's schema.  
     :type context: BaseContent
     :param value: A UID.
     :type value: string
     :return: Returns a Content object.
     :rtype: BaseContent
     """
     if not value:
         return None
     elif is_at_content(value):
         return value
     else:
         try:
             uc = getToolByName(context, 'uid_catalog')
         except AttributeError:
             # Sometimes an object doesn't have an acquisition chain,
             # in these cases we just hope that get_tool's call to
             # getSite doesn't f**k up.
             uc = get_tool('uid_catalog')
         brains = uc(UID=value)
         if brains:
             return brains[0].getObject()
         logger.error(
             "{}.{}: Resolving UIDReference failed for {}.  No object will "
             "be returned.".format(context, self.getName(), value))
Example #34
0
def handle_measure_added(obj, event):
    """Assign a new measureid to this AceMeasure"""

    catalog = get_tool(name="portal_catalog")
    ids = sorted(filter(None, catalog.uniqueValuesFor("acemeasure_id")))
    obj._acemeasure_id = ids[-1] + 1
    obj.reindexObject(idxs=["acemeasure_id"])
Example #35
0
def transition(obj=None, transition=None):
    """Perform a workflow transition for the object.

    :param obj: [required] Object for which we want to perform the workflow
        transition.
    :type obj: Content object
    :param transition: [required] Name of the workflow transition.
    :type transition: string
    :raises:
        :class:`~plone.api.exc.MissingParameterError`,
        :class:`~plone.api.exc.InvalidParameterError`
    :Example: :ref:`content_transition_example`
    """
    workflow = portal.get_tool('portal_workflow')
    try:
        workflow.doActionFor(obj, transition)
    except WorkflowException:
        transitions = [
            action['id'] for action in workflow.listActions(object=obj)
        ]

        raise InvalidParameterError(
            "Invalid transition '{0}'.\n"
            "Valid transitions are:\n"
            "{1}".format(transition, '\n'.join(sorted(transitions)))
        )
Example #36
0
def remove_user(groupname=None, group=None, username=None, user=None):
    """Remove the user from a group.

    Arguments ``groupname`` and ``group`` are mutually exclusive. You can
    either set one or the other, but not both.

    Arguments ``username`` and ``user`` are mutually exclusive. You can either
    set one or the other, but not both.

    :param groupname: Name of the group to remove the user from.
    :type groupname: string
    :param group: Group to remove the user from.
    :type group: GroupData object
    :param username: Username of the user to delete from the group.
    :type username: string
    :param user: User to delete from the group.
    :type user: MemberData object
    :raises:
        ValueError
        UserNotFoundError
    :Example: :ref:`group_remove_user_example`
    """
    if username:
        user = user_get(username=username)
        if not user:
            raise UserNotFoundError
    user_id = user.id
    group_id = groupname or group.id
    portal_groups = portal.get_tool('portal_groups')
    portal_groups.removePrincipalFromGroup(user_id, group_id)
Example #37
0
def get_uid(value):
    """Takes a brain or object and returns a valid UID.
    In this case, the object may come from portal_archivist, so we will
    need to do a catalog query to get the UID of the current version
    """
    if not value:
        return ''
    # Is value a brain?
    if ICatalogBrain.providedBy(value):
        value = value.getObject()
    # validate UID
    uid = value.UID()
    uc = get_tool('uid_catalog')
    if uc(UID=uid):
        # The object is valid
        return uid
    # Otherwise the object is an old version
    brains = uc(portal_type=value.portal_type, Title=value.Title())
    if not brains:
        # Cannot find UID
        raise RuntimeError('The UID for %s/%s cannot be found!' %
                           (value.portal_type, value.Title()))
    if len(brains) > 1:
        # Found multiple objects, this is a failure
        raise RuntimeError('Searching for %s/%s returned multiple objects.' %
                           (value.portal_type, value.Title()))
    return brains[0].UID
Example #38
0
def _get_aceitem_description(object):
    """Simplify the long description rich text in a simple 2 paragraphs
    "summary"
    """
    v = object.Description()

    if v:
        return v

    if not object.long_description:
        return ""

    text = object.long_description.raw
    portal_transforms = get_tool(name="portal_transforms")

    # Output here is a single <p> which contains <br /> for newline
    data = portal_transforms.convertTo("text/plain",
                                       text,
                                       mimetype="text/html")
    text = data.getData().strip()

    # the following is a very bad algorithm. Needs to use nltk.tokenize
    pars = text.split(".")

    return ".".join(pars[:2])

    return text
Example #39
0
    def __call__(self):
        cat = get_tool('portal_catalog')

        query = {
            'review_state': ['published', 'archived', 'private']
        }
        results = cat.searchResults(query)

        logger.info("Found %s objects " % len(results))

        count = 0
        options = {}
        options['create'] = False
        options['service_to_ping'] = 'http://semantic.eea.europa.eu/ping'
        for res in results:
            context = res.getObject()
            url = res.getURL()

            if 'https' in url:
                url = url.replace('https', 'http')

            options['obj_url'] = url + '/@@rdf'
            logger.info("Pinging: %s", url)
            ping_CRSDS(context, options)
            logger.info("Finished pinging: %s", url)

            count += 1
            if count % 100 == 0:
                logger.info('Went through %s brains' % count)

        logger.info('Finished pinging all brains')
        return 'Finished'
Example #40
0
def has_permission(permission, username=None, user=None, obj=None):
    """Check whether this user has the given permssion.

    Arguments ``username`` and ``user`` are mutually exclusive. You
    can either set one or the other, but not both. if ``username`` and
    ``user`` are not given, the authenticated member will be used.

    :param permission: The permission you wish to check
    :type permission: string
    :param username: Username of the user for which you want to check
        the permission.
    :type username: string
    :param user: User object for which you want to check the permission.
    :type user: MemberData object
    :param obj: If obj is set then check the permission on this context.
        If obj is not given, the site root will be used.
    :type obj: content object
    :raises:
        InvalidParameterError
    :returns: True if the user has the permission, False otherwise.
    :rtype: bool
    """
    if obj is None:
        obj = portal.get()

    if username is None and user is None:
        context = _nop_context_manager()
    else:
        context = env.adopt_user(username, user)

    with context:
        portal_membership = portal.get_tool('portal_membership')
        return bool(portal_membership.checkPermission(permission, obj))
Example #41
0
def get_groups(username=None, user=None):
    """Get all groups or all groups filtered by user.

    Arguments ``username`` and ``user`` are mutually exclusive. You can either
    set one or the other, but not both.

    :param username: Username of the user for which to return groups. If set,
        only return groups that this user is member of.
    :type username: string
    :param user: User for which to return groups. If set, only return groups
        that this user is member of.
    :type user: MemberData object
    :returns: All groups (optionlly filtered by user)
    :rtype: List of GroupData objects
    :raises: UserNotFoundError
    :Example: :ref:`group_get_all_groups_example`,
        :ref:`group_get_users_groups_example`
    """
    if username:
        user = user_get(username=username)
        if not user:
            raise UserNotFoundError

    group_tool = portal.get_tool('portal_groups')

    if user:
        groups = group_tool.getGroupsForPrincipal(user)
        return [get(groupname=group) for group in groups]

    return group_tool.listGroups()
Example #42
0
 def updateIndexes(self):
     if not getattr(self, 'audit_lexicon', None):
         # installing, add lexicon, indexes and metadata
         self.addIndex('last_audited_date', 'DateIndex')
         self.addIndex('audited_action', 'KeywordIndex')
         self.addColumn('Title')
         self.addColumn('id')
         self.addColumn('UID')
         self.addColumn('last_audited_date')
         self.addColumn('audited_action')
         l = PLexicon('audit_lexicon', '', HTMLWordSplitter(),
                      CaseNormalizer(), StopWordRemover())
         self._setObject('audit_lexicon', l)
     catalog = portal_api.get_tool('portal_catalog')
     indexes = catalog._catalog.indexes
     for name, index in indexes.items():
         if name in self._catalog.indexes.keys():
             continue
         if index.meta_type == 'DateRecurringIndex':
             continue
         elif index.meta_type == 'ZCTextIndex':
             extras = Empty()
             extras.doc_attr = name
             extras.index_type = 'Okapi BM25 Rank'
             extras.lexicon_id = 'audit_lexicon'
             self.addIndex(name, index.meta_type, extras)
         else:
             self.addIndex(name, index.meta_type)
Example #43
0
def transition(obj=None, transition=None, to_state=None):
    """Perform a workflow transition for the object or attempt to perform
    workflow transitions on the object to reach the given state.
    The later will not guarantee that transition guards conditions can be met.

    :param obj: [required] Object for which we want to perform the workflow
        transition.
    :type obj: Content object
    :param transition: Name of the workflow transition.
    :type transition: string
    :param to_state: Name of the workflow state.
    :type to_state: string
    :raises:
        :class:`~plone.api.exc.MissingParameterError`,
        :class:`~plone.api.exc.InvalidParameterError`
    :Example: :ref:`content_transition_example`
    """
    workflow = portal.get_tool('portal_workflow')
    if transition is not None:
        try:
            workflow.doActionFor(obj, transition)
        except WorkflowException:
            transitions = [
                action['id'] for action in workflow.listActions(object=obj)
            ]

            raise InvalidParameterError("Invalid transition '{0}'.\n"
                                        "Valid transitions are:\n"
                                        "{1}".format(
                                            transition,
                                            '\n'.join(sorted(transitions))))
    else:
        # move from the current state to the given state
        # via any route we can find
        for wf in workflow.getWorkflowsFor(obj):
            status = workflow.getStatusOf(wf.getId(), obj)
            if not status or not status.get('review_state'):
                continue
            if status['review_state'] == to_state:
                return

            transitions = _wf_transitions_for(
                wf,
                status['review_state'],
                to_state,
            )
            if not transitions:
                continue

            for transition in transitions:
                workflow.doActionFor(obj, transition)

            break

        if workflow.getInfoFor(obj, 'review_state') != to_state:
            raise InvalidParameterError(
                "Could not find workflow to set state to {0} on {1}".format(
                    to_state,
                    obj,
                ))
Example #44
0
    def _set_localization_date_format(self):
        """Set the expected localized date format."""
        from plone.api.exc import InvalidParameterError

        name_root = 'Products.CMFPlone.i18nl10n.override_dateformat.'
        try:
            portal.set_registry_record(
                name=name_root + 'Enabled',
                value=True,
            )
            portal.set_registry_record(
                name=name_root + 'date_format_long',
                value='%b %d, %Y %I:%M %p',
            )
            portal.set_registry_record(
                name=name_root + 'time_format',
                value='%I:%M %p',
            )
            portal.set_registry_record(
                name=name_root + 'date_format_short',
                value='%b %d, %Y',
            )
        except InvalidParameterError:
            # before Plone 4.3, date formats were stored in portal_properties
            properties = portal.get_tool('portal_properties')
            properties.localLongTimeFormat = '%b %d, %Y %I:%M %p'
            properties.localTimeOnlyFormat = '%I:%M %p'
            properties.localTimeFormat = '%b %d, %Y'
Example #45
0
def get(userid=None, username=None):
    """Get a user.

    Plone provides both a unique, unchanging identifier for a user (the
    userid) and a username, which is the value a user types into the login
    form. In many cases, the values for each will be the same, but under some
    circumstances they will differ. Known instances of this behavior include:

     * using content-based members via membrane
     * users changing their email address when using email as login is enabled

    We provide the ability to look up users by either.

    :param userid: Userid of the user we want to get.
    :type userid: string
    :param username: Username of the user we want to get.
    :type username: string
    :returns: User
    :rtype: MemberData object
    :raises:
        MissingParameterError
    :Example: :ref:`user_get_example`
    """
    if userid is not None:
        portal_membership = portal.get_tool('portal_membership')
        return portal_membership.getMemberById(userid)

    return get_member_by_login_name(portal.get(),
                                    username,
                                    raise_exceptions=False)
Example #46
0
def create(
    groupname=None,
    title=None,
    description=None,
    roles=[],
    groups=[]
):
    """Create a group.

    :param groupname: [required] Name of the new group.
    :type groupname: string
    :param title: Title of the new group
    :type title: string
    :param description: Description of the new group
    :type description: string
    :param roles: Roles to assign to this group
    :type roles: list
    :param groups: Groups that belong to this group
    :type groups: list
    :returns: Newly created group
    :rtype: GroupData object
    :raises:
        ValueError
    :Example: :ref:`group_create_example`
    """
    group_tool = portal.get_tool('portal_groups')
    group_tool.addGroup(
        groupname, roles, groups,
        title=title,
        description=description
    )
    return group_tool.getGroupById(groupname)
Example #47
0
def add_user(groupname=None, group=None, username=None, user=None):
    """Add the user to a group.

    Arguments ``groupname`` and ``group`` are mutually exclusive. You can
    either set one or the other, but not both.

    Arguments ``username`` and ``user`` are mutually exclusive. You can
    either set one or the other, but not both.

    :param groupname: Name of the group to which to add the user.
    :type groupname: string
    :param group: Group to which to add the user.
    :type group: GroupData object
    :param username: Username of the user to add to the group.
    :type username: string
    :param user: User to add to the group.
    :type user: MemberData object
    :raises:
        ValueError
    :Example: :ref:`group_add_user_example`

    """
    user_id = username or user.id
    group_id = groupname or group.id
    portal_groups = portal.get_tool('portal_groups')
    portal_groups.addPrincipalToGroup(user_id, group_id)
Example #48
0
    def test_get_tool_tool_not_found(self):
        """Test that error msg lists available tools if a tool is not found."""
        from plone.api.exc import InvalidParameterError
        with self.assertRaises(InvalidParameterError) as cm:
            portal.get_tool('portal_foo')

        self.assertTrue(
            str(cm.exception).startswith(
                "Cannot find a tool with name 'portal_foo'"))

        # A selection of portal tools which should exist in all plone versions
        should_be_theres = (
            "portal_setup",
            "portal_actionicons",
            "portal_actions",
            "portal_atct",
            "portal_calendar",
            "portal_catalog",
            "portal_controlpanel",
            "portal_css",
            "portal_diff",
            "portal_factory",
            "portal_groupdata",
            "portal_groups",
            "portal_interface",
            "portal_javascripts",
            "portal_memberdata",
            "portal_membership",
            "portal_metadata",
            "portal_migration",
            "portal_password_reset",
            "portal_properties",
            "portal_quickinstaller",
            "portal_registration",
            "portal_skins",
            "portal_types",
            "portal_uidannotation",
            "portal_uidgenerator",
            "portal_uidhandler",
            "portal_undo",
            "portal_url",
            "portal_view_customizations",
            "portal_workflow",
        )

        for should_be_there in should_be_theres:
            self.assertIn((should_be_there + '\n'), str(cm.exception))
Example #49
0
    def test_get_tool_tool_not_found(self):
        """Test that error msg lists available tools if a tool is not found."""
        from plone.api.exc import InvalidParameterError
        with self.assertRaises(InvalidParameterError) as cm:
            portal.get_tool('portal_foo')

        self.assertTrue(
            str(cm.exception).startswith(
                "Cannot find a tool with name 'portal_foo'"))

        # A selection of portal tools which should exist in all plone versions
        should_be_theres = (
            "portal_setup",
            "portal_actionicons",
            "portal_actions",
            "portal_atct",
            "portal_calendar",
            "portal_catalog",
            "portal_controlpanel",
            "portal_css",
            "portal_diff",
            "portal_factory",
            "portal_groupdata",
            "portal_groups",
            "portal_interface",
            "portal_javascripts",
            "portal_memberdata",
            "portal_membership",
            "portal_metadata",
            "portal_migration",
            "portal_password_reset",
            "portal_properties",
            "portal_quickinstaller",
            "portal_registration",
            "portal_skins",
            "portal_types",
            "portal_uidannotation",
            "portal_uidgenerator",
            "portal_uidhandler",
            "portal_undo",
            "portal_url",
            "portal_view_customizations",
            "portal_workflow",
        )

        for should_be_there in should_be_theres:
            self.assertIn((should_be_there + '\n'), str(cm.exception))
Example #50
0
def is_anonymous():
    """Check if the currently logged-in user is anonymous.

    :returns: True if the current user is anonymous, False otherwise.
    :rtype: bool
    :Example: :ref:`user_is_anonymous_example`
    """
    return bool(portal.get_tool('portal_membership').isAnonymousUser())
Example #51
0
def create(email=None, username=None, password=None, roles=("Member",), properties=None):
    """Create a user.

    :param email: [required] Email for the new user.
    :type email: string
    :param username: Username for the new user. This is required if email
        is not used as a username.
    :type username: string
    :param password: Password for the new user. If it's not set we generate
        a random 8-char alpha-numeric one.
    :type password: string
    :param properties: User properties to assign to the new user. The list of
        available properties is available in ``portal_memberdata`` through ZMI.
    :type properties: dict
    :returns: Newly created user
    :rtype: MemberData object
    :raises:
        MissingParameterError
        InvalidParameterError
    :Example: :ref:`user_create_example`
    """
    if properties is None:
        # Never use a dict as default for a keyword argument.
        properties = {}

    # it may happen that someone passes email in the properties dict, catch
    # that and set the email so the code below this works fine
    if not email and properties.get("email"):
        email = properties.get("email")

    if not email:
        raise MissingParameterError("You need to pass the new user's email.")

    try:
        use_email_as_username = portal.get_registry_record("plone.use_email_as_login")
    except InvalidParameterError:
        site = portal.get()
        props = site.portal_properties
        use_email_as_username = props.site_properties.use_email_as_login

    if not use_email_as_username and not username:
        raise InvalidParameterError(
            "The portal is configured to use username " "that is not email so you need to pass a username."
        )

    registration = portal.get_tool("portal_registration")
    user_id = use_email_as_username and email or username

    # Generate a random 8-char password
    if not password:
        chars = string.ascii_letters + string.digits
        password = "".join(random.choice(chars) for x in range(8))

    properties.update(username=user_id)
    properties.update(email=email)

    registration.addMember(user_id, password, roles, properties=properties)
    return get(username=user_id)
Example #52
0
def get_current():
    """Get the currently logged-in user.

    :returns: Currently logged-in user
    :rtype: MemberData object
    :Example: :ref:`user_get_current_example`
    """
    portal_membership = portal.get_tool('portal_membership')
    return portal_membership.getAuthenticatedMember()
Example #53
0
    def test_get_tool_tool_not_found(self):
        """Test that error msg lists available tools if a tool is not found."""
        from plone.api.exc import InvalidParameterError
        with self.assertRaises(InvalidParameterError) as cm:
            portal.get_tool('portal_foo')

        self.assertTrue(
            str(cm.exception).startswith(
                "Cannot find a tool with name 'portal_foo'"))

        # A selection of portal tools which should exist in all plone versions
        should_be_theres = (
            'portal_setup',
            'portal_catalog',
        )

        for should_be_there in should_be_theres:
            self.assertIn((should_be_there + '\n'), str(cm.exception))
Example #54
0
    def html_to_text(self, html):
        portal_transform = portal.get_tool(name='portal_transforms')

        data = portal_transform.convertTo(
            'text/plain', html, mimetype='text/html'
        )

        data = data.getData().strip()
        return data
Example #55
0
def migrate_refs(portal_type, relation, fieldname, pgthreshold=100):
    rc = get_tool(REFERENCE_CATALOG)
    uc = get_tool('uid_catalog')
    refs = rc(relationship=relation)
    # Be sure there are no Nones
    refs = filter(None, refs)
    if not refs:
        return

    logger.info('Migrating %s references of %s' % (len(refs), relation))
    for i, ref in enumerate(refs):
        obj = uc(UID=ref[1])
        if obj:
            obj = obj[0].getObject()
            if i and not divmod(i, pgthreshold)[1]:
                logger.info("%s/%s %s/%s" % (i, len(refs), obj, relation))
            touidref(obj, obj, relation, portal_type, fieldname)
            refs_to_remove.append(relation)
            objs_to_reindex.append(obj)
Example #56
0
 def __call__(self, context):
     # This is a local import
     from immunarray.lims.interfaces.solution import ISolution
     tt = get_tool('portal_types')
     all_portal_types = tt.objectValues()
     temp = []
     for pt in all_portal_types:
         if hasattr(pt, 'behaviors'):
             if ISolution.__identifier__ in pt.behaviors:
                 temp.append(pt.Title())
     return SimpleVocabulary.fromValues(temp)