BP_REST_Group_Membership_Endpoint::create_item_permissions_check( WP_REST_Request $request )

Checks if a given request has access to join a group.

Description

Parameters

$request

(Required) Full details about the request.

Return

(bool|WP_Error)

Source

File: bp-groups/classes/class-bp-rest-group-membership-endpoint.php

	public function create_item_permissions_check( $request ) {
		$retval = true;

		if ( ! is_user_logged_in() ) {
			$retval = new WP_Error(
				'bp_rest_authorization_required',
				__( 'Sorry, you need to be logged in to join a group.', 'buddyboss' ),
				array(
					'status' => rest_authorization_required_code(),
				)
			);
		}

		$user = bp_rest_get_user( $request['user_id'] );

		if ( true === $retval && ! $user instanceof WP_User ) {
			$retval = new WP_Error(
				'bp_rest_group_member_invalid_id',
				__( 'Invalid group member ID.', 'buddyboss' ),
				array(
					'status' => 404,
				)
			);
		}

		$group = $this->groups_endpoint->get_group_object( $request['group_id'] );
		if ( true === $retval && ! $group instanceof BP_Groups_Group ) {
			$retval = new WP_Error(
				'bp_rest_group_invalid_id',
				__( 'Invalid group ID.', 'buddyboss' ),
				array(
					'status' => 404,
				)
			);
		}

		// Site administrators can do anything.
		if ( true === $retval && bp_current_user_can( 'bp_moderate' ) ) {
			$retval = true;
		} else {

			$loggedin_user_id = bp_loggedin_user_id();

			// Users may only freely join public groups.
			if ( true === $retval && (
					! bp_current_user_can( 'groups_join_group', array( 'group_id' => $group->id ) )
					|| groups_is_user_member( $loggedin_user_id, $group->id ) // As soon as they are not already members.
					|| groups_is_user_banned( $loggedin_user_id, $group->id ) // And as soon as they are not banned from it.
					|| $loggedin_user_id !== $user->ID // You can only add yourself to a group.
				) ) {
				$retval = new WP_Error(
					'bp_rest_group_member_failed_to_join',
					__( 'Could not join the group.', 'buddyboss' ),
					array(
						'status' => 500,
					)
				);
			}
		}

		/**
		 * Filter the group members `create_item` permissions check.
		 *
		 * @param bool|WP_Error $retval Returned value.
		 * @param WP_REST_Request $request The request sent to the API.
		 *
		 * @since 0.1.0
		 */
		return apply_filters( 'bp_rest_group_members_create_item_permissions_check', $retval, $request );
	}

Changelog

Changelog
Version Description
0.1.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.