Skip to:
Content

BuddyPress.org


Ignore:
Timestamp:
08/28/2019 08:38:00 PM (5 years ago)
Author:
imath
Message:

Prepare BuddyPress to welcome the BP REST API

  • Add a grunt tasks to import the master branch of the BP REST API into the BuddyPress /build directory.
  • Add some other grunt tasks to move each BP REST Controller class into their corresponding component classes directory.
  • Add the needed mechanism to make sure activating the BP REST API plugin will take over the BP REST API in BuddyPress core so that it is possible to iterate/fix bugs from the BP REST API GitHub repository.
  • Make sure the buddypress.pot is generated once the BP REST API has been imported.
  • Update the BuddyPress class autoloader to manage the loading of the BP REST API Controllers.
  • Add a new method rest_api_init() to the BP Component API to register the BP REST Controllers from their belonging component classes.

Props boonebgorges & espellcaste

See #7156

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/bp-core/bp-core-rest-api.php

    r12405 r12451  
    2323
    2424/**
     25 * Should we use the REST Endpoints of built BuddyPress?
     26 *
     27 * If the BP REST plugin is active, it overrides BuddyPress REST enpoints.
     28 * This allows us to carry on maintaining all the BP REST API endpoints from
     29 * the BP REST plugin on GitHub.
     30 *
     31 * @since 5.0.0
     32 *
     33 * @return bool Whether to use the REST Endpoints of built BuddyPress.
     34 */
     35function bp_rest_in_buddypress() {
     36    $is_src = defined( 'BP_SOURCE_SUBDIRECTORY' ) && BP_SOURCE_SUBDIRECTORY === 'src';
     37
     38    return ! $is_src && ! bp_rest_is_plugin_active();
     39}
     40
     41/**
    2542 * Check the availability of the BP REST API.
    2643 *
     
    3047 */
    3148function bp_rest_api_is_available() {
     49
    3250    /**
    3351     * Filter here to disable the BP REST API.
     
    3957     * @param boolean $value True if the BP REST API is available. False otherwise.
    4058     */
    41     return apply_filters( 'bp_rest_api_is_available', function_exists( 'create_initial_rest_routes' ) && bp_rest_is_plugin_active() );
     59    return apply_filters( 'bp_rest_api_is_available', function_exists( 'create_initial_rest_routes' ) && bp_rest_in_buddypress() ) || bp_rest_is_plugin_active();
    4260}
    4361
     
    7694}
    7795add_action( 'bp_init', 'bp_rest_api_register_request_script' );
     96
     97/**
     98 * BuddyPress REST API namespace.
     99 *
     100 * @since 5.0.0
     101 *
     102 * @return string
     103 */
     104function bp_rest_namespace() {
     105
     106    /**
     107     * Filter API namespace.
     108     *
     109     * @since 5.0.0
     110     *
     111     * @param string $namespace BuddyPress core namespace.
     112     */
     113    return apply_filters( 'bp_rest_namespace', 'buddypress' );
     114}
     115
     116/**
     117 * BuddyPress REST API version.
     118 *
     119 * @since 5.0.0
     120 *
     121 * @return string
     122 */
     123function bp_rest_version() {
     124
     125    /**
     126     * Filter API version.
     127     *
     128     * @since 5.0.0
     129     *
     130     * @param string $version BuddyPress core version.
     131     */
     132    return apply_filters( 'bp_rest_version', 'v1' );
     133}
     134
     135/**
     136 * Get user URL.
     137 *
     138 * @since 5.0.0
     139 *
     140 * @param  int $user_id User ID.
     141 * @return string
     142 */
     143function bp_rest_get_user_url( $user_id ) {
     144    return sprintf(
     145        '/%s/%s/members/%d',
     146        bp_rest_namespace(),
     147        bp_rest_version(),
     148        $user_id
     149    );
     150}
     151
     152/**
     153 * Set headers to let the Client Script be aware of the pagination.
     154 *
     155 * @since 5.0.0
     156 *
     157 * @param  WP_REST_Response $response The response data.
     158 * @param  integer          $total    The total number of found items.
     159 * @param  integer          $per_page The number of items per page of results.
     160 * @return WP_REST_Response $response The response data.
     161 */
     162function bp_rest_response_add_total_headers( WP_REST_Response $response, $total = 0, $per_page = 0 ) {
     163    if ( ! $total || ! $per_page ) {
     164        return $response;
     165    }
     166
     167    $total_items = (int) $total;
     168    $max_pages   = ceil( $total_items / (int) $per_page );
     169
     170    $response->header( 'X-WP-Total', $total_items );
     171    $response->header( 'X-WP-TotalPages', (int) $max_pages );
     172
     173    return $response;
     174}
     175
     176/**
     177 * Convert the input date to RFC3339 format.
     178 *
     179 * @since 5.0.0
     180 *
     181 * @param string      $date_gmt Date GMT format.
     182 * @param string|null $date     Optional. Date object.
     183 * @return string|null ISO8601/RFC3339 formatted datetime.
     184 */
     185function bp_rest_prepare_date_response( $date_gmt, $date = null ) {
     186    if ( isset( $date ) ) {
     187        return mysql_to_rfc3339( $date );
     188    }
     189
     190    if ( '0000-00-00 00:00:00' === $date_gmt ) {
     191        return null;
     192    }
     193
     194    return mysql_to_rfc3339( $date_gmt );
     195}
     196
     197/**
     198 * Clean up member_type input.
     199 *
     200 * @since 5.0.0
     201 *
     202 * @param string $value Comma-separated list of group types.
     203 * @return array|null
     204 */
     205function bp_rest_sanitize_member_types( $value ) {
     206    if ( empty( $value ) ) {
     207        return $value;
     208    }
     209
     210    $types              = explode( ',', $value );
     211    $registered_types   = bp_get_member_types();
     212    $registered_types[] = 'any';
     213    $valid_types        = array_intersect( $types, $registered_types );
     214
     215    return ( ! empty( $valid_types ) ) ? $valid_types : null;
     216}
     217
     218/**
     219 * Validate member_type input.
     220 *
     221 * @since 5.0.0
     222 *
     223 * @param  mixed $value Mixed value.
     224 * @return WP_Error|boolean
     225 */
     226function bp_rest_validate_member_types( $value ) {
     227    if ( empty( $value ) ) {
     228        return true;
     229    }
     230
     231    $types            = explode( ',', $value );
     232    $registered_types = bp_get_member_types();
     233
     234    // Add the special value.
     235    $registered_types[] = 'any';
     236    foreach ( $types as $type ) {
     237        if ( ! in_array( $type, $registered_types, true ) ) {
     238            return new WP_Error(
     239                'bp_rest_invalid_group_type',
     240                sprintf(
     241                    /* translators: %1$s and %2$s is replaced with the registered type(s) */
     242                    __( 'The member type you provided, %$1s, is not one of %$2s.', 'buddypress' ),
     243                    $type,
     244                    implode( ', ', $registered_types )
     245                )
     246            );
     247        }
     248    }
     249}
     250
     251/**
     252 * Clean up group_type input.
     253 *
     254 * @since 5.0.0
     255 *
     256 * @param string $value Comma-separated list of group types.
     257 * @return array|null
     258 */
     259function bp_rest_sanitize_group_types( $value ) {
     260    if ( empty( $value ) ) {
     261        return null;
     262    }
     263
     264    $types       = explode( ',', $value );
     265    $valid_types = array_intersect( $types, bp_groups_get_group_types() );
     266
     267    return empty( $valid_types ) ? null : $valid_types;
     268}
     269
     270/**
     271 * Validate group_type input.
     272 *
     273 * @since 5.0.0
     274 *
     275 * @param  mixed $value Mixed value.
     276 * @return WP_Error|bool
     277 */
     278function bp_rest_validate_group_types( $value ) {
     279    if ( empty( $value ) ) {
     280        return true;
     281    }
     282
     283    $types            = explode( ',', $value );
     284    $registered_types = bp_groups_get_group_types();
     285    foreach ( $types as $type ) {
     286        if ( ! in_array( $type, $registered_types, true ) ) {
     287            return new WP_Error(
     288                'bp_rest_invalid_group_type',
     289                sprintf(
     290                    /* translators: %1$s and %2$s is replaced with the registered types */
     291                    __( 'The group type you provided, %1$s, is not one of %2$s.', 'buddypress' ),
     292                    $type,
     293                    implode( ', ', $registered_types )
     294                )
     295            );
     296        }
     297    }
     298}
     299
     300/**
     301 * Clean up an array, comma- or space-separated list of strings.
     302 *
     303 * @since 5.0.0
     304 *
     305 * @param array|string $list List of strings.
     306 * @return array Sanitized array of strings.
     307 */
     308function bp_rest_sanitize_string_list( $list ) {
     309    if ( ! is_array( $list ) ) {
     310        $list = preg_split( '/[\s,]+/', $list );
     311    }
     312
     313    return array_unique( array_map( 'sanitize_text_field', $list ) );
     314}
     315
     316/**
     317 * Get the user object, if the ID is valid.
     318 *
     319 * @since 5.0.0
     320 *
     321 * @param int $user_id Supplied user ID.
     322 * @return WP_User|boolean
     323 */
     324function bp_rest_get_user( $user_id ) {
     325    if ( (int) $user_id <= 0 ) {
     326        return false;
     327    }
     328
     329    $user = get_userdata( (int) $user_id );
     330    if ( empty( $user ) || ! $user->exists() ) {
     331        return false;
     332    }
     333
     334    return $user;
     335}
     336
     337/**
     338 * Registers a new field on an existing BuddyPress object.
     339 *
     340 * @since 5.0.0
     341 *
     342 * @param string $component_id The name of the *active* component (eg: `activity`, `groups`, `xprofile`).
     343 *                             Required.
     344 * @param string $attribute    The attribute name. Required.
     345 * @param array  $args {
     346 *     Optional. An array of arguments used to handle the registered field.
     347 *     @see `register_rest_field()` for a full description.
     348 * }
     349 * @param string $object_type  The xProfile object type to get. This parameter is only required for
     350 *                             the Extended Profiles component. Not used for all other components.
     351 *                             Possible values are `data`, `field` or `group`.
     352 * @return bool                True if the field has been registered successfully. False otherwise.
     353 */
     354function bp_rest_register_field( $component_id, $attribute, $args = array(), $object_type = '' ) {
     355    $registered_fields = false;
     356
     357    if ( ! $component_id || ! bp_is_active( $component_id ) || ! $attribute ) {
     358        return $registered_fields;
     359    }
     360
     361    // Use the `bp_` prefix as we're using a WordPress global used for Post Types.
     362    $field_name = 'bp_' . $component_id;
     363
     364    // Use the meta type as a suffix for the field name.
     365    if ( 'xprofile' === $component_id ) {
     366        if ( ! in_array( $object_type, array( 'data', 'field', 'group' ), true ) ) {
     367            return $registered_fields;
     368        }
     369
     370        $field_name .= '_' . $object_type;
     371    }
     372
     373    $args = bp_parse_args(
     374        $args,
     375        array(
     376            'get_callback'    => null,
     377            'update_callback' => null,
     378            'schema'          => null,
     379        ),
     380        'rest_register_field'
     381    );
     382
     383    // Register the field.
     384    register_rest_field( $field_name, $attribute, $args );
     385
     386    if ( isset( $GLOBALS['wp_rest_additional_fields'][ $field_name ] ) ) {
     387        $registered_fields = $GLOBALS['wp_rest_additional_fields'][ $field_name ];
     388    }
     389
     390    // Check it has been registered.
     391    return isset( $registered_fields[ $attribute ] );
     392}
Note: See TracChangeset for help on using the changeset viewer.