*/ private static $readable = array(); /** * IDs of every space the user may read. * * @param int $user_id User ID, 0 for a visitor. * @return int[] */ public static function readable_space_ids( $user_id ) { // Key on the cache generations so new spaces and memberships are seen at once. $user_id = absint( $user_id ); $key = $user_id . ':' . wp_cache_get_last_changed( 'spacebay_spaces' ) . ':' . wp_cache_get_last_changed( 'spacebay_space_members' ) . ':' . wp_cache_get_last_changed( 'spacebay_profiles' ); if ( ! isset( self::$readable[ $key ] ) ) { $ids = array(); foreach ( SpaceRepository::all( 'space' ) as $space ) { if ( SpaceAccess::can_read( $space, $user_id ) ) { $ids[] = $space['id']; } } self::$readable[ $key ] = $ids; } return self::$readable[ $key ]; } /** * Clears the request cache after memberships change. * * @return void */ public static function flush() { self::$readable = array(); } /** * Whether the user is an active member of the space or a community manager. * * @param array $space Space row. * @param int $user_id User ID. * @return bool */ public static function is_participant( array $space, $user_id ) { $user_id = SpaceAccess::effective_id( $user_id ); if ( ! $user_id ) { return false; } if ( SpaceAccess::is_manager( $user_id ) ) { return true; } $membership = Membership::get( $space['id'], $user_id ); return $membership && 'active' === $membership['status']; } /** * Whether the user may start a post in the space. * * @param array $space Space row. * @param int $user_id User ID. * @return bool */ public static function can_post( array $space, $user_id ) { if ( 'published' !== $space['status'] || ! self::is_participant( $space, $user_id ) ) { return false; } $who = $space['settings']['who_can_post'] ?? 'members'; return 'admins' === $who ? SpaceAccess::can_moderate( $space, $user_id ) : true; } /** * Whether the user may comment on posts in the space. * * @param array $space Space row. * @param int $user_id User ID. * @return bool */ public static function can_comment( array $space, $user_id ) { return 'published' === $space['status'] && self::is_participant( $space, $user_id ); } /** * Whether the user may edit or delete content written by someone. * * @param array $space Space row. * @param int $author_id Author of the content. * @param int $user_id User ID. * @return bool */ public static function can_change( array $space, $author_id, $user_id ) { $user_id = SpaceAccess::effective_id( $user_id ); if ( ! $user_id ) { return false; } if ( SpaceAccess::can_moderate( $space, $user_id ) ) { return true; } return (int) $author_id === (int) $user_id && SpaceAccess::can_read( $space, $user_id ); } }