Exemple #1
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 and group:
        raise InvalidParameterError

    if groupname:
        group_tool = getToolByName(portal.get(), "portal_groups")
        group = group_tool.getGroupById(groupname)
        if not group:
            # XXX This should raise a custom plone.api exception
            raise ValueError

    portal_membership = getToolByName(portal.get(), "portal_membership")

    if group:
        return group.getGroupMembers()
    else:
        return portal_membership.listMembers()
Exemple #2
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
    :Example: :ref:`group_get_all_groups_example`,
        :ref:`group_get_users_groups_example`
    """
    if username and user:
        raise ValueError

    if username:
        membership = getToolByName(portal.get(), 'portal_membership')
        user = membership.getMemberById(username)
        if not user:
            raise ValueError

    group_tool = getToolByName(portal.get(), 'portal_groups')

    if user:
        groups = group_tool.getGroupsForPrincipal(user)
        return [get(groupname=group) for group in groups]
    else:
        return group_tool.listGroups()
Exemple #3
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 and group:
        raise ValueError

    if groupname:
        group_tool = getToolByName(portal.get(), 'portal_groups')
        group = group_tool.getGroupById(groupname)
        if not group:
            raise ValueError

    portal_membership = getToolByName(portal.get(), 'portal_membership')

    if group:
        return group.getGroupMembers()
    else:
        return portal_membership.listMembers()
Exemple #4
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 username and user:
        raise InvalidParameterError

    if obj is None:
        obj = portal.get()

    # holds the initial security context
    current_security_manager = getSecurityManager()

    portal_membership = getToolByName(portal.get(), "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:
        # XXX This needs a custom plone.api error
        raise ValueError
    newSecurityManager(getRequest(), user)

    permissions = (p[0] for p in getPermissions())
    d = {}
    for permission in permissions:
        d[permission] = bool(user.checkPermission(permission, obj))

    # restore the initial security context
    setSecurityManager(current_security_manager)

    return d
Exemple #5
0
def delete(groupname=None, group=None):
    """Delete a group.

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

    :param groupname: Name of the group to be deleted.
    :type groupname: string
    :param group: Group object to be deleted.
    :type group: GroupData object
    :raises:
        ValueError
    :Example: :ref:`group_delete_example`
    """
    if not groupname and not group:
        raise ValueError

    if groupname and group:
        raise ValueError

    group_tool = getToolByName(portal.get(), 'portal_groups')

    if group:
        groupname = group.id

    return group_tool.removeGroup(groupname)
Exemple #6
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`
    """
    if not groupname:
        raise ValueError('You have to pass the groupname parameter!')

    group_tool = getToolByName(portal.get(), 'portal_groups')

    group_tool.addGroup(
        groupname, roles, groups, title=title,
        description=description)
    return group_tool.getGroupById(groupname)
Exemple #7
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 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:
        ValueError
    :Example: :ref:`user_get_roles_example`
    """

    if username and user:
        raise ValueError

    portal_membership = getToolByName(portal.get(), 'portal_membership')

    if username:
        user = portal_membership.getMemberById(username)
    elif not user:
        user = portal_membership.getAuthenticatedMember()

    if obj is None:
        return user.getRoles()
    else:
        return user.getRolesInContext(obj)
Exemple #8
0
def adopt_user(username=None, user=None):
    """Context manager for temporarily switching user inside a block.

    :param user: User object to switch to inside block.
    :type user: user object from acl_users.getUser() or api.user.get().

    :param username: username of user to switch to inside block.
    :type username: string
    """

    if username is None:
        username = user.getId()

    # Grab the user object out of acl_users because this function
    # accepts 'user' objects that are actually things like MemberData
    # objects, which AccessControl isn't so keen on.
    acl_users = portal.get().acl_users
    unwrapped = acl_users.getUser(username)
    if unwrapped is None:
        raise UserNotFoundError

    # ZopeSecurityPolicy appears to strongly expect the user object to
    # be Acquisition-wrapped in the acl_users from which it was taken.
    user = unwrapped.__of__(acl_users)

    return _adopt_user(user)
Exemple #9
0
def get(path=None, UID=None):
    """Get an object.

    :param path: Path to the object we want to get, relative to
        the portal root.
    :type path: string
    :param UID: UID of the object we want to get.
    :type UID: string
    :returns: Content object
    :raises:
        ValueError,
    :Example: :ref:`content_get_example`
    """
    if path and UID:
        raise ValueError('When getting an object combining path and UID '
                         'attribute is not allowed')

    if not path and not UID:
        raise ValueError('When getting an object path or UID attribute is '
                         'required')

    if path:
        site = portal.get()
        site_id = site.getId()
        if not path.startswith('/{0}'.format(site_id)):
            path = '/{0}{1}'.format(site_id, path)

        try:
            return site.restrictedTraverse(path)
        except KeyError:
            return None  # When no object is found don't raise an error

    elif UID:
        return uuidToObject(UID)
Exemple #10
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)

    with context:
        adopted_user = get_current()
        permissions = (p[0] for p in getPermissions())
        d = {}
        for permission in permissions:
            d[permission] = bool(adopted_user.checkPermission(permission, obj))

    return d
    def __call__(self):
        # get the surf theme objects
        themes = self.load_objects_from_rdf()

        self.default_language = get_default_language()

        self.available_languages = get_available_languages_iso()
        self.available_languages_title = get_available_languages_title()

        # map the properties
        self.mapping = {
            'dct_title': 'skos_prefLabel',
            'skos_inScheme': 'skos_inScheme',
            'dc_identifier': 'dc_identifier',
        }
        self.count = 0
        for theme in themes:
            self.update(theme)

        msg = _('Imported ${count} concepts items.',
                mapping={
                    'count': self.count,
                })
        msg = translate(msg, context=self.request)
        portal.show_message(message=msg, request=self.request)
        url = '/'.join([
            portal.get().absolute_url(),
            FOLDER_CONCEPTS,
        ])
        self.request.response.redirect(url)
        return u''
Exemple #12
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)
Exemple #13
0
 def list_contents(self):
     site = portal.get()
     storage = IGarbageStorage(site)
     contents = [i for i in storage.garbagecan_contents()]
     return sorted(contents,
                   key=lambda n: n[1].garbagecan_date,
                   reverse=True)
Exemple #14
0
def get_groups(username=None, user=None):
    """Get a list of groups that this user is a member of.

    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.
    :type username: string
    :param user: User for which to return groups.
    :type user: MemberData object
    :returns: List of names of groups this user is a member of.
    :rtype: List of strings
    :raises:
        ValueError
    :Example: :ref:`get_groups_for_user_example`
    """
    if not username and not user:
        raise ValueError

    if username and user:
        raise ValueError

    site = portal.get()

    if username:
        user = getToolByName(site, "portal_membership").getMemberById(username)
    return getToolByName(site, "portal_groups").getGroupsForPrincipal(user)
Exemple #15
0
    def list(self):
        res = {'description': '', 'items': []}

        url = self.request["ACTUAL_URL"]
        category = url.split("/")[-1]

        catalog = api.portal.get_tool("portal_catalog")
        brains = catalog.searchResults(
            portal_type='eea.climateadapt.c3sindicator',
            c3s_theme=category.capitalize())

        items = {}
        for brain in brains:
            obj = brain.getObject()
            items[obj.title] = brain.getURL()

        site = portal.get()
        base_folder = site["knowledge"]["european-climate-data-explorer"]
        datastore = IAnnotations(base_folder).get('c3s_json_data', {})
        res['description'] = datastore['data']['themes'][category][
            'description']
        for indicator in datastore['data']['themes'][category]['apps']:
            if indicator['title'] in items:
                res['items'].append({
                    'title': indicator['title'],
                    'url': items[indicator['title']],
                })

        return res
Exemple #16
0
def has_permission(permission, username=None, user=None, obj=None):
    """Check whether this user has the given permission.

    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:
        return bool(getSecurityManager().checkPermission(permission, obj))
Exemple #17
0
def get(path=None, UID=None):
    """Get an object.

    :param path: Path to the object we want to get, relative to
        the portal root.
    :type path: string
    :param UID: UID of the object we want to get.
    :type UID: string
    :returns: Content object
    :raises:
        ValueError,
    :Example: :ref:`content_get_example`
    """
    if path:
        site = portal.get()
        site_absolute_path = '/'.join(site.getPhysicalPath())
        if not path.startswith('{0}'.format(site_absolute_path)):
            path = '{0}{1}'.format(site_absolute_path, path)

        try:
            return site.restrictedTraverse(path)
        except (KeyError, AttributeError):
            return None  # When no object is found don't raise an error

    elif UID:
        return uuidToObject(UID)
Exemple #18
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`
    """
    if not obj or not transition:
        raise MissingParameterError('You have to provide the ``obj`` and the '
                                    '``transition`` parameters')

    workflow = getToolByName(portal.get(), 'portal_workflow')
    try:
        workflow.doActionFor(obj, transition)
    except WorkflowException:
        transitions = [action['id'] for action in workflow.listActions(object=obj)]

        raise InvalidParameterError(
            "Invalid transition '%s'. \n"
            "Valid transitions are:\n"
            "%s" % (transition, '\n'.join(sorted(transitions))))
Exemple #19
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)

    with context:
        sm = getSecurityManager()
        pms = (record[0] for record in getPermissions())
        result = {pm: bool(sm.checkPermission(pm, obj)) for pm in pms}
    return result
Exemple #20
0
 def get_glossary_table(self):
     site = portal.get()
     base_folder = site["knowledge"]["european-climate-data-explorer"]
     datastore = IAnnotations(base_folder).get('c3s_json_data', {})
     if 'glossary_table' in datastore['data']:
         return datastore['data']['glossary_table']
     return ''
Exemple #21
0
    def __call__(self):
        site = portal.get()
        sf = site.unrestrictedTraverse('marine/frontpage-slides')
        self.images = [o for o in sf.contentValues()
                       if content.get_state(o) == 'published']

        return self.index()
Exemple #22
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))
Exemple #23
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,
    )
Exemple #24
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`
    """
    if not groupname:
        raise ValueError('You have to pass the groupname parameter!')

    group_tool = getToolByName(portal.get(), 'portal_groups')

    group_tool.addGroup(
        groupname, roles, groups, title=title,
        description=description)
    return group_tool.getGroupById(groupname)
Exemple #25
0
    def __call__(self):
        site = portal.get()
        storage = IRecommendationStorage(site)
        storage_recom = storage.get(STORAGE_KEY, {})
        default = self.template(data='-')

        if not len(storage_recom.items()):
            return default

        subregions = set(self.available_subregions)
        recommendations = []

        for rec_code, recommendation in storage_recom.items():
            ms_region = set(recommendation.ms_region)

            if subregions.intersection(ms_region):
                recommendations.append(recommendation.data_to_list())

        if not recommendations:
            return default

        sorted_rec = sorted(recommendations, key=lambda i: i[0])

        recomm_table = RecommendationsTable(recommendations=sorted_rec,
                                            show_edit_buttons=False)
        res = recomm_table()

        return self.template(data=res)
Exemple #26
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 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:
        ValueError
    :Example: :ref:`user_get_roles_example`
    """

    if username and user:
        raise ValueError

    portal_membership = getToolByName(portal.get(), 'portal_membership')

    if username:
        user = portal_membership.getMemberById(username)
    elif not user:
        user = portal_membership.getAuthenticatedMember()

    if obj is None:
        return user.getRoles()
    else:
        return user.getRolesInContext(obj)
Exemple #27
0
def get(path=None, UID=None):
    """Get an object.

    :param path: Path to the object we want to get, relative to
        the portal root.
    :type path: string
    :param UID: UID of the object we want to get.
    :type UID: string
    :returns: Content object
    :raises:
        ValueError,
    :Example: :ref:`content_get_example`
    """
    if path and UID:
        raise ValueError('When getting an object combining path and UID '
                         'attribute is not allowed')

    if not path and not UID:
        raise ValueError('When getting an object path or UID attribute is '
                         'required')

    if path:
        site = portal.get()
        site_id = site.getId()
        if not path.startswith('/{0}'.format(site_id)):
            path = '/{0}{1}'.format(site_id, path)

        try:
            return site.restrictedTraverse(path)
        except KeyError:
            return None  # When no object is found don't raise an error

    elif UID:
        return uuidToObject(UID)
Exemple #28
0
    def __call__(self):
        labels = get_indicator_labels().values()
        site = portal.get()
        storage = ITranslationsStorage(site)

        count = 0

        for label in labels:
            lang = get_detected_lang(label)

            if (not lang) or (lang == 'en'):
                continue

            lang = lang.upper()

            langstore = storage.get(lang, None)

            if langstore is None:
                continue

            if label not in langstore:
                langstore[label] = u''
                logger.info('Added %r to translation store for lang %s', label,
                            lang)
                count = +1

        return "Added %s labels" % count
Exemple #29
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`
    """
    if not obj or not transition:
        raise MissingParameterError('You have to provide the ``obj`` and the '
                                    '``transition`` parameters')

    workflow = getToolByName(portal.get(), 'portal_workflow')
    try:
        workflow.doActionFor(obj, transition)
    except WorkflowException:
        transitions = [
            action['id'] for action in workflow.listActions(object=obj)
        ]

        raise InvalidParameterError(
            "Invalid transition '%s'. \n"
            "Valid transitions are:\n"
            "%s" % (transition, '\n'.join(sorted(transitions))))
Exemple #30
0
def delete(groupname=None, group=None):
    """Delete a group.

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

    :param groupname: Name of the group to be deleted.
    :type groupname: string
    :param group: Group object to be deleted.
    :type group: GroupData object
    :raises:
        ValueError
    :Example: :ref:`group_delete_example`
    """
    if not groupname and not group:
        raise ValueError

    if groupname and group:
        raise ValueError

    group_tool = getToolByName(portal.get(), 'portal_groups')

    if group:
        groupname = group.id

    return group_tool.removeGroup(groupname)
Exemple #31
0
def get(path=None, UID=None):
    """Get an object.

    :param path: Path to the object we want to get, relative to
        the portal root.
    :type path: string
    :param UID: UID of the object we want to get.
    :type UID: string
    :returns: Content object
    :raises:
        ValueError,
    :Example: :ref:`content_get_example`
    """
    if path:
        site = portal.get()
        site_absolute_path = '/'.join(site.getPhysicalPath())
        if not path.startswith('{0}'.format(site_absolute_path)):
            path = '{0}{1}'.format(site_absolute_path, path)

        try:
            return site.restrictedTraverse(path)
        except (KeyError, AttributeError):
            return None  # When no object is found don't raise an error

    elif UID:
        return uuidToObject(UID)
Exemple #32
0
    def get_categories(self):
        site = portal.get()
        base_folder = site["knowledge"]["european-climate-data-explorer"]
        datastore = IAnnotations(base_folder).get('c3s_json_data', {})
        data_overview_page = datastore['data']['overview_page']

        response = []
        #hazard_type_order = data_overview_page['hazard_type_order']
        hazard_type_order = data_overview_page[
            'hazard_type_order_left'] + data_overview_page[
                'hazard_type_order_right']
        #hazard_type_order.append(['Other'])

        for index, main_category in enumerate(
                data_overview_page['category_order']):
            if main_category in data_overview_page['hazard_list']:
                category_data = data_overview_page['hazard_list'][
                    main_category]

                subcategories = hazard_type_order[index]
                res = []
                for subcategory in subcategories:
                    if subcategory in category_data:
                        res.append((subcategory, category_data[subcategory]))
                response.append({'name': main_category, 'data': res})

        return response
Exemple #33
0
def delete(username=None, user=None):
    """Delete a 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 to be deleted.
    :type username: string
    :param user: User object to be deleted.
    :type user: MemberData object
    :raises:
        MissingParameterError
        InvalidParameterError
    :Example: :ref:`user_delete_example`

    """
    if not username and not user:
        raise MissingParameterError

    if username and user:
        raise InvalidParameterError

    portal_membership = getToolByName(portal.get(), "portal_membership")
    user_id = username or user.id
    portal_membership.deleteMembers((user_id,))
Exemple #34
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.")

    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)
 def getAuthUrl(self):
     portal_url = portal.get().absolute_url()
     clientid = portal.get_registry_record(interface=IPFGSharePointConfig,
                                           name='clientid')
     auth_url = "https://login.microsoftonline.com/common"
     auth_url += '/adminconsent?client_id=' + clientid
     auth_url += '&redirect_uri=' + portal_url + '/@@sharepoint-permissions'
     return auth_url
Exemple #36
0
    def test_get_navigation_root(self):
        """Test to see if the navigation_root is returned."""

        navigation_root = portal.get_navigation_root(portal.get())
        self.assertTrue(INavigationRoot.providedBy(navigation_root))

        from plone.api.exc import MissingParameterError
        self.assertRaises(MissingParameterError, portal.get_navigation_root)
Exemple #37
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 getToolByName(portal.get(), "portal_membership").isAnonymousUser()
Exemple #38
0
def _get_navigation_root(context):
    """Find the correct navigation root."""
    documents = content.find(portal_type='Document', id='front-page')
    if len(documents) == 0:
        return portal.get()
    front_page = documents[0].getObject()

    return portal.get_navigation_root(front_page)
Exemple #39
0
    def report_data(self):

        site = portal.get()
        report = site.__annotations__.get('google-analytics-cache-data', {})

        reports = reversed(sorted(report.items(), key=lambda x: int(x[1])))

        return islice(reports, 0, 10)
Exemple #40
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 getToolByName(portal.get(), 'portal_membership').isAnonymousUser()
Exemple #41
0
    def test_get_navigation_root(self):
        """Test to see if the navigation_root is returned."""

        navigation_root = portal.get_navigation_root(portal.get())
        self.assertTrue(INavigationRoot.providedBy(navigation_root))

        from plone.api.exc import MissingParameterError
        self.assertRaises(MissingParameterError, portal.get_navigation_root)
Exemple #42
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)
Exemple #43
0
def get_all():
    """Get all groups.

    :returns: All groups
    :rtype: List of GroupData objects
    :Example: :ref:`groups_get_all_example`
    """
    group_tool = getToolByName(portal.get(), 'portal_groups')
    return group_tool.listGroups()
Exemple #44
0
    def icon_images(self):
        root = portal.get()

        if "tile_icons" not in root.objectIds():
            return []

        tile_icons = root["tile_icons"]

        return tile_icons.objectValues()
Exemple #45
0
def get_all():
    """Return all users.

    :returns: All users
    :rtype: List of MemberData objects
    :Example: :ref:`users_get_all_example`
    """
    portal_membership = getToolByName(portal.get(), "portal_membership")
    return portal_membership.listMembers()
Exemple #46
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 = getToolByName(portal.get(), "portal_membership")
    return portal_membership.getAuthenticatedMember()
Exemple #47
0
def get_current():
    """Get the currently logged-in user.

    :returns: Currently logged-in user
    :rtype: MemberData object
    :raises:
        ValueError
    :Example: :ref:`user_get_current_example`
    """
    portal_membership = getToolByName(portal.get(), 'portal_membership')
    return portal_membership.getAuthenticatedMember()
Exemple #48
0
def find(context=None, depth=None, **kwargs):
    """Find content in the portal.

    :param context: Context for the search
    :type obj: Content object
    :param depth: How far in the content tree we want to search from context
    :type obj: Content object
    :returns: Catalog brains
    :rtype: List
    :Example: :ref:`content_find_example`

    """
    query = {}
    query.update(**kwargs)

    # Save the original path to maybe restore it later.
    orig_path = query.get('path')
    if isinstance(orig_path, dict):
        orig_path = orig_path.get('query')

    # Passing a context or depth overrides the existing path query,
    # for now.
    if context or depth is not None:
        # Make the path a dictionary, unless it already is.
        if not isinstance(orig_path, dict):
            query['path'] = {}

    # Limit search depth
    if depth is not None:
        # If we don't have a context, we'll assume the portal root.
        if context is None and not orig_path:
            context = portal.get()
        else:
            # Restore the original path
            query['path']['query'] = orig_path
        query['path']['depth'] = depth

    if context is not None:
        query['path']['query'] = '/'.join(context.getPhysicalPath())

    # Convert interfaces to their identifiers and also allow to query
    # multiple values using {'query:[], 'operator':'and|or'}
    obj_provides = query.get('object_provides', [])
    if obj_provides:
        query['object_provides'] = _parse_object_provides_query(obj_provides)

    # Make sure we don't dump the whole catalog.
    catalog = portal.get_tool('portal_catalog')
    indexes = catalog.indexes()
    valid_indexes = [index for index in query if index in indexes]
    if not valid_indexes:
        return []

    return catalog(**query)
 def handle_join_success(self, data):
     super(RegistrationForm, self).handle_join_success(data)
     site = portal.get()
     allfields = [f for f in self.fields]
     customfields = [f for f in allfields if f not in BASE_FIELDS]
     execute_under_special_role(
         portal=site,
         role='Manager',
         function=add_member_profile,
         data=data,
         customfields=customfields
     )
 def load_workbook(self):
     io = StringIO()
     # Get the latest version of the form
     portal = get()
     docs = sorted(portal.documents['pp-007-04-test-forms'].objectValues())
     doc = docs[-1]
     io.write(doc.file.data)
     io.seek(0)
     fn = tempfile.mktemp(suffix='.xlsx')
     open(fn, 'wb').write(io.getvalue())
     wb = openpyxl.load_workbook(fn)
     os.unlink(fn)
     return wb
Exemple #51
0
def revoke_roles(groupname=None, group=None, roles=None, obj=None):
    """Revoke roles from a group.

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

    :param groupname: Name of the group to revoke roles to.
    :type groupname: string
    :param group: Group to revoke roles to.
    :type group: GroupData object
    :param roles: List of roles to revoke
    :type roles: list of strings
    :param obj: If obj is set then revoke local roles on this context.
    :type obj: content object
    :raises:
        ValueError
    :Example: :ref:`group_revoke_roles_example`

    """
    if not groupname and not group:
        raise ValueError

    if groupname and group:
        raise ValueError

    if not roles:
        raise ValueError

    if "Anonymous" in roles or "Authenticated" in roles:
        raise ValueError

    group_id = groupname or group.id

    actual_roles = get_roles(groupname=group_id, obj=obj)
    if actual_roles.count("Anonymous"):
        actual_roles.remove("Anonymous")
    if actual_roles.count("Authenticated"):
        actual_roles.remove("Authenticated")

    roles = list(set(actual_roles) - set(roles))
    portal_groups = getToolByName(portal.get(), "portal_groups")

    if obj is None:
        portal_groups.setRolesForGroup(group_id=group_id, roles=roles)
    elif roles:
        obj.manage_setLocalRoles(group_id, roles)
    else:
        obj.manage_delLocalRoles([group_id])
Exemple #52
0
def get(groupname=None):
    """Get a group.

    :param groupname: [required] Name of the group we want to get.
    :type groupname: string
    :returns: Group
    :rtype: GroupData object
    :raises:
        ValueError
    :Example: :ref:`group_get_example`
    """
    if not groupname:
        raise ValueError('You have to pass the groupname parameter!')

    group_tool = getToolByName(portal.get(), 'portal_groups')
    return group_tool.getGroupById(groupname)
Exemple #53
0
def get_state(obj=None):
    """Get the current workflow state of the object.

    :param obj: [required] Object that we want to get the state for.
    :type obj: Content object
    :returns: Object's current workflow state
    :rtype: string
    :raises:
        ValueError
    :Example: :ref:`content_get_state_example`
    """
    if not obj:
        raise ValueError

    workflow = getToolByName(portal.get(), 'portal_workflow')
    return workflow.getInfoFor(obj, 'review_state')
Exemple #54
0
def get(username=None):
    """Get a user.

    :param username: [required] Username of the user we want to get.
    :type username: string
    :returns: User
    :rtype: MemberData object
    :raises:
        ValueError
    :Example: :ref:`user_get_example`
    """
    if not username:
        raise ValueError

    portal_membership = getToolByName(portal.get(), "portal_membership")
    return portal_membership.getMemberById(username)
Exemple #55
0
    def test_get_with_sub_site(self):
        """Using getSite() alone is not enough to get the portal. It
        will return the closest site, which may return a sub site
        instead of the portal.

        Set a different local site manager and test that portal.get()
        still returns the portal.
        """
        a_site = content.create(container=self.portal, type="Folder", title="A Site")
        a_site.setSiteManager(LocalSiteManager(a_site))

        setSite(a_site)

        self.assertEqual(portal.get(), self.portal)

        # cleanup
        setSite(self.portal)
Exemple #56
0
    def get_site(self):
        """ Get site
        """
        site = portal.get()
        ldsite = self.context

        while not ILinkedDataHomepage.providedBy(ldsite):
            try:
                ldsite = ldsite.aq_parent
            except AttributeError:
                ldsite = None

                break

        if ldsite is None:
            return site

        return ldsite
def get_path_from_widget_start(widget):
    effective_path = ""
    if not callable(widget.start):
        start = widget.start
        if (start == "parent"):
            obj = aq_parent(widget.context)
            effective_path = '/'.join(obj.getPhysicalPath())
        elif (start == "navroot"):
            obj = portal.get_navigation_root(widget.context)
            effective_path = '/'.join(obj.getPhysicalPath())
        elif (start == "ploneroot"):
            obj = portal.get()
            effective_path = '/'.join(obj.getPhysicalPath())
        else:
            effective_path = widget.start
    else:
        effective_path = widget.start(widget)
    return effective_path
Exemple #58
0
def has_permission(permission=None, username=None, user=None, obj=None):
    """Check if the user has the specified permission on the given object.

    Arguments ``username`` and ``user`` are mutually exclusive. You can either
    set one or the other, but not both. If no ``username` or ``user`` are
    provided, check the permission for the currently logged-in user.

    :param permission: [required] Permission of the user to check for
    :type permission: string
    :param username: Username of the user that we are checking the permission
        for
    :type username: string
    :param user: User that we are checking the permission for
    :type user: MemberData object
    :param obj: Object that we are checking the permission for
    :type obj: object
    :returns: True if user has the specified permission, False otherwise.
    :rtype: bool
    :raises:
        ValueError
    :Example: :ref:`user_has_permission_example`
    """
    if not permission:
        ValueError

    if username and user:
        raise ValueError

    if not obj:
        raise ValueError

    portal_membership = getToolByName(portal.get(), "portal_membership")
    if username:
        user = portal_membership.getMemberById(username)

    if not user or user == portal_membership.getAuthenticatedMember():
        return portal_membership.checkPermission(permission, obj)
    else:
        roles = rolesForPermissionOn(permission, obj)
        return user.allowed(obj, roles)