[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-core/ -> bp-core-rest-api.php (source)

   1  <?php
   2  /**
   3   * Core REST API functions.
   4   *
   5   * @package BuddyPress
   6   * @subpackage Core
   7   * @since 5.0.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * Is the BP REST plugin is active?
  15   *
  16   * @since 5.0.0
  17   *
  18   * @return boolean True if the BP REST plugin is active. False otherwise.
  19   */
  20  function bp_rest_is_plugin_active() {
  21      return (bool) has_action( 'bp_rest_api_init', 'bp_rest', 5 );
  22  }
  23  
  24  /**
  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   */
  35  function 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  /**
  42   * Check the availability of the BP REST API.
  43   *
  44   * @since 5.0.0
  45   *
  46   * @return boolean True if the BP REST API is available. False otherwise.
  47   */
  48  function bp_rest_api_is_available() {
  49  
  50      /**
  51       * Filter here to disable the BP REST API.
  52       *
  53       * The BP REST API requires at least WordPress 4.7.0
  54       *
  55       * @since 5.0.0
  56       *
  57       * @param boolean $value True if the BP REST API is available. False otherwise.
  58       */
  59      return apply_filters( 'bp_rest_api_is_available', function_exists( 'create_initial_rest_routes' ) && bp_rest_in_buddypress() ) || bp_rest_is_plugin_active();
  60  }
  61  
  62  /**
  63   * Register the jQuery.ajax wrapper for BP REST API requests.
  64   *
  65   * @since 5.0.0
  66   */
  67  function bp_rest_api_register_request_script() {
  68      if ( ! bp_rest_api_is_available() ) {
  69          return;
  70      }
  71  
  72      $dependencies = array( 'jquery' );
  73  
  74      // The wrapper for WP REST API requests was introduced in WordPress 4.9.0.
  75      if ( wp_script_is( 'wp-api-request', 'registered' ) ) {
  76          $dependencies = array( 'wp-api-request' );
  77      }
  78  
  79      wp_register_script(
  80          'bp-api-request',
  81          sprintf( '%1$sbp-core/js/bp-api-request%2$s.js', buddypress()->plugin_url, bp_core_get_minified_asset_suffix() ),
  82          $dependencies,
  83          bp_get_version(),
  84          true
  85      );
  86  
  87      wp_localize_script(
  88          'bp-api-request',
  89          'bpApiSettings',
  90          array(
  91              'root'            => esc_url_raw( get_rest_url() ),
  92              'nonce'           => wp_create_nonce( 'wp_rest' ),
  93              'unexpectedError' => __( 'An unexpected error occured. Please try again.', 'buddypress' ),
  94          )
  95      );
  96  }
  97  add_action( 'bp_init', 'bp_rest_api_register_request_script' );
  98  
  99  /**
 100   * BuddyPress REST API namespace.
 101   *
 102   * @since 5.0.0
 103   *
 104   * @return string
 105   */
 106  function bp_rest_namespace() {
 107  
 108      /**
 109       * Filter API namespace.
 110       *
 111       * @since 5.0.0
 112       *
 113       * @param string $namespace BuddyPress core namespace.
 114       */
 115      return apply_filters( 'bp_rest_namespace', 'buddypress' );
 116  }
 117  
 118  /**
 119   * BuddyPress REST API version.
 120   *
 121   * @since 5.0.0
 122   *
 123   * @return string
 124   */
 125  function bp_rest_version() {
 126  
 127      /**
 128       * Filter API version.
 129       *
 130       * @since 5.0.0
 131       *
 132       * @param string $version BuddyPress core version.
 133       */
 134      return apply_filters( 'bp_rest_version', 'v1' );
 135  }
 136  
 137  /**
 138   * Get user URL.
 139   *
 140   * @since 5.0.0
 141   *
 142   * @param  int $user_id User ID.
 143   * @return string
 144   */
 145  function bp_rest_get_user_url( $user_id ) {
 146      return sprintf(
 147          '/%s/%s/members/%d',
 148          bp_rest_namespace(),
 149          bp_rest_version(),
 150          $user_id
 151      );
 152  }
 153  
 154  /**
 155   * Set headers to let the Client Script be aware of the pagination.
 156   *
 157   * @since 5.0.0
 158   *
 159   * @param  WP_REST_Response $response The response data.
 160   * @param  integer          $total    The total number of found items.
 161   * @param  integer          $per_page The number of items per page of results.
 162   * @return WP_REST_Response $response The response data.
 163   */
 164  function bp_rest_response_add_total_headers( WP_REST_Response $response, $total = 0, $per_page = 0 ) {
 165      if ( ! $total || ! $per_page ) {
 166          return $response;
 167      }
 168  
 169      $total_items = (int) $total;
 170      $max_pages   = ceil( $total_items / (int) $per_page );
 171  
 172      $response->header( 'X-WP-Total', $total_items );
 173      $response->header( 'X-WP-TotalPages', (int) $max_pages );
 174  
 175      return $response;
 176  }
 177  
 178  /**
 179   * Convert the input date to RFC3339 format.
 180   *
 181   * @since 5.0.0
 182   *
 183   * @param string      $date_gmt Date GMT format.
 184   * @param string|null $date     Optional. Date object.
 185   * @return string|null ISO8601/RFC3339 formatted datetime.
 186   */
 187  function bp_rest_prepare_date_response( $date_gmt, $date = null ) {
 188      if ( isset( $date ) ) {
 189          return mysql_to_rfc3339( $date );
 190      }
 191  
 192      if ( '0000-00-00 00:00:00' === $date_gmt ) {
 193          return null;
 194      }
 195  
 196      return mysql_to_rfc3339( $date_gmt );
 197  }
 198  
 199  /**
 200   * Clean up member_type input.
 201   *
 202   * @since 5.0.0
 203   *
 204   * @param string $value Comma-separated list of group types.
 205   * @return array|null
 206   */
 207  function bp_rest_sanitize_member_types( $value ) {
 208      if ( empty( $value ) ) {
 209          return $value;
 210      }
 211  
 212      $types              = explode( ',', $value );
 213      $registered_types   = bp_get_member_types();
 214      $registered_types[] = 'any';
 215      $valid_types        = array_intersect( $types, $registered_types );
 216  
 217      return ( ! empty( $valid_types ) ) ? $valid_types : null;
 218  }
 219  
 220  /**
 221   * Validate member_type input.
 222   *
 223   * @since 5.0.0
 224   *
 225   * @param  mixed $value Mixed value.
 226   * @return WP_Error|boolean
 227   */
 228  function bp_rest_validate_member_types( $value ) {
 229      if ( empty( $value ) ) {
 230          return true;
 231      }
 232  
 233      $types            = explode( ',', $value );
 234      $registered_types = bp_get_member_types();
 235  
 236      // Add the special value.
 237      $registered_types[] = 'any';
 238      foreach ( $types as $type ) {
 239          if ( ! in_array( $type, $registered_types, true ) ) {
 240              return new WP_Error(
 241                  'bp_rest_invalid_member_type',
 242                  sprintf(
 243                      /* translators: %1$s and %2$s is replaced with the registered type(s) */
 244                      __( 'The member type you provided, %1$s, is not one of %2$s.', 'buddypress' ),
 245                      $type,
 246                      implode( ', ', $registered_types )
 247                  )
 248              );
 249          }
 250      }
 251  }
 252  
 253  /**
 254   * Clean up group_type input.
 255   *
 256   * @since 5.0.0
 257   *
 258   * @param string $value Comma-separated list of group types.
 259   * @return array|null
 260   */
 261  function bp_rest_sanitize_group_types( $value ) {
 262      if ( empty( $value ) ) {
 263          return null;
 264      }
 265  
 266      $types       = explode( ',', $value );
 267      $valid_types = array_intersect( $types, bp_groups_get_group_types() );
 268  
 269      return empty( $valid_types ) ? null : $valid_types;
 270  }
 271  
 272  /**
 273   * Validate group_type input.
 274   *
 275   * @since 5.0.0
 276   *
 277   * @param  mixed $value Mixed value.
 278   * @return WP_Error|bool
 279   */
 280  function bp_rest_validate_group_types( $value ) {
 281      if ( empty( $value ) ) {
 282          return true;
 283      }
 284  
 285      $types            = explode( ',', $value );
 286      $registered_types = bp_groups_get_group_types();
 287      foreach ( $types as $type ) {
 288          if ( ! in_array( $type, $registered_types, true ) ) {
 289              return new WP_Error(
 290                  'bp_rest_invalid_group_type',
 291                  sprintf(
 292                      /* translators: %1$s and %2$s is replaced with the registered types */
 293                      __( 'The group type you provided, %1$s, is not one of %2$s.', 'buddypress' ),
 294                      $type,
 295                      implode( ', ', $registered_types )
 296                  )
 297              );
 298          }
 299      }
 300  }
 301  
 302  /**
 303   * Clean up an array, comma- or space-separated list of strings.
 304   *
 305   * @since 5.0.0
 306   *
 307   * @param array|string $list List of strings.
 308   * @return array Sanitized array of strings.
 309   */
 310  function bp_rest_sanitize_string_list( $list ) {
 311      if ( ! is_array( $list ) ) {
 312          $list = preg_split( '/[\s,]+/', $list );
 313      }
 314  
 315      return array_unique( array_map( 'sanitize_text_field', $list ) );
 316  }
 317  
 318  /**
 319   * Get the user object, if the ID is valid.
 320   *
 321   * @since 5.0.0
 322   *
 323   * @param int $user_id Supplied user ID.
 324   * @return WP_User|boolean
 325   */
 326  function bp_rest_get_user( $user_id ) {
 327      if ( (int) $user_id <= 0 ) {
 328          return false;
 329      }
 330  
 331      $user = get_userdata( (int) $user_id );
 332      if ( empty( $user ) || ! $user->exists() ) {
 333          return false;
 334      }
 335  
 336      return $user;
 337  }
 338  
 339  /**
 340   * Registers a new field on an existing BuddyPress object.
 341   *
 342   * @since 5.0.0
 343   *
 344   * @param string $component_id The name of the *active* component (eg: `activity`, `groups`, `xprofile`).
 345   *                             Required.
 346   * @param string $attribute    The attribute name. Required.
 347   * @param array  $args {
 348   *     Optional. An array of arguments used to handle the registered field.
 349   *     @see `register_rest_field()` for a full description.
 350   * }
 351   * @param string $object_type  The xProfile object type to get. This parameter is only required for
 352   *                             the Extended Profiles component. Not used for all other components.
 353   *                             Possible values are `data`, `field` or `group`.
 354   * @return bool                True if the field has been registered successfully. False otherwise.
 355   */
 356  function bp_rest_register_field( $component_id, $attribute, $args = array(), $object_type = '' ) {
 357      $registered_fields = false;
 358  
 359      if ( ! $component_id || ! bp_is_active( $component_id ) || ! $attribute ) {
 360          return $registered_fields;
 361      }
 362  
 363      // Use the `bp_` prefix as we're using a WordPress global used for Post Types.
 364      $field_name = 'bp_' . $component_id;
 365  
 366      // Use the meta type as a suffix for the field name.
 367      if ( 'xprofile' === $component_id ) {
 368          if ( ! in_array( $object_type, array( 'data', 'field', 'group' ), true ) ) {
 369              return $registered_fields;
 370          }
 371  
 372          $field_name .= '_' . $object_type;
 373      }
 374  
 375      $args = bp_parse_args(
 376          $args,
 377          array(
 378              'get_callback'    => null,
 379              'update_callback' => null,
 380              'schema'          => null,
 381          ),
 382          'rest_register_field'
 383      );
 384  
 385      // Register the field.
 386      register_rest_field( $field_name, $attribute, $args );
 387  
 388      if ( isset( $GLOBALS['wp_rest_additional_fields'][ $field_name ] ) ) {
 389          $registered_fields = $GLOBALS['wp_rest_additional_fields'][ $field_name ];
 390      }
 391  
 392      // Check it has been registered.
 393      return isset( $registered_fields[ $attribute ] );
 394  }


Generated: Sun Dec 8 01:01:37 2019 Cross-referenced by PHPXref 0.7.1