/**
 * Checks if a user is allowed to be logged-in
 *
 * The transient related to the user is retrieved and the first cookie in the transient
 * is compared to the LOGGED_IN_COOKIE of the current user.
 *
 * The first cookie in the transient is the oldest, so it is the one that gets logged out
 *
 * We only log a user out if there are more than 2 users logged into the same account
 *
 * @access      private
 * @since       1.5
 * @return      void
*/

function rcp_can_user_be_logged_in() {
	if ( is_user_logged_in() && rcp_no_account_sharing() ) :

		$user_id = get_current_user_id();

		$already_logged_in = get_transient( 'rcp_user_logged_in_' . $user_id );

		if( $already_logged_in !== false ) :

			$data = maybe_unserialize( $already_logged_in );

			if( count( $data ) < 2 )
				return; // do nothing

			// remove the first key
			unset( $data[0] );
			$data = array_values( $data );

			if( ! in_array( $_COOKIE[LOGGED_IN_COOKIE], $data ) ) :

				set_transient( 'rcp_user_logged_in_' . $user_id, $data );

				// Log the user out - this is the oldest user logged into this account
				wp_logout();
				wp_safe_redirect( trailingslashit( get_bloginfo( 'wpurl' ) ) . 'wp-login.php?loggedout=true' );

			endif;

		endif;

	endif;
}
/**
 * Checks if a user is allowed to be logged-in.
 *
 * The transient related to the user is retrieved and the first cookie in the transient
 * is compared to the LOGGED_IN_COOKIE of the current user.
 *
 * The first cookie in the transient is the oldest, so it is the one that gets logged out.
 *
 * We only log a user out if there are more than 2 users logged into the same account.
 *
 * @access private
 * @since  1.5
 * @return void
*/
function rcp_can_user_be_logged_in()
{
    if (is_user_logged_in() && rcp_no_account_sharing()) {
        if (defined('REST_REQUEST') && REST_REQUEST) {
            return;
        }
        $user_id = get_current_user_id();
        $already_logged_in = get_transient('rcp_user_logged_in_' . $user_id);
        if ($already_logged_in !== false) {
            $data = maybe_unserialize($already_logged_in);
            // remove the oldest logged in users
            $prev_data_count = count($data);
            while (count($data) >= 2) {
                unset($data[0]);
                $data = array_values($data);
            }
            // save modified data
            if (count($data) != $prev_data_count) {
                set_transient('rcp_user_logged_in_' . $user_id, $data);
            }
            if (!in_array($_COOKIE[LOGGED_IN_COOKIE], $data)) {
                // Log the user out - this is one of the oldest user logged into this account
                wp_logout();
                wp_safe_redirect(trailingslashit(get_bloginfo('wpurl')) . 'wp-login.php?loggedout=true');
            }
        }
    }
}