[ 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', bp_is_running_wp( '4.7.0' ) && 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 a REST API object URL from a component.
 139   *
 140   * @since 9.0.0
 141   *
 142   * @param integer $object_id   Object ID.
 143   * @param string  $object_path Path of the component endpoint.
 144   * @return string
 145   */
 146  function bp_rest_get_object_url( $object_id, $object_path ) {
 147      return rest_url(
 148          sprintf(
 149              '/%1$s/%2$s/%3$s/%4$d',
 150              bp_rest_namespace(),
 151              bp_rest_version(),
 152              $object_path,
 153              $object_id
 154          )
 155      );
 156  }
 157  
 158  /**
 159   * Set headers to let the Client Script be aware of the pagination.
 160   *
 161   * @since 5.0.0
 162   *
 163   * @param  WP_REST_Response $response The response data.
 164   * @param  integer          $total    The total number of found items.
 165   * @param  integer          $per_page The number of items per page of results.
 166   * @return WP_REST_Response $response The response data.
 167   */
 168  function bp_rest_response_add_total_headers( WP_REST_Response $response, $total = 0, $per_page = 0 ) {
 169      if ( ! $total || ! $per_page ) {
 170          return $response;
 171      }
 172  
 173      $total_items = (int) $total;
 174      $max_pages   = ceil( $total_items / (int) $per_page );
 175  
 176      $response->header( 'X-WP-Total', $total_items );
 177      $response->header( 'X-WP-TotalPages', (int) $max_pages );
 178  
 179      return $response;
 180  }
 181  
 182  /**
 183   * Convert the input date to RFC3339 format.
 184   *
 185   * @since 5.0.0
 186   *
 187   * @param string      $date_gmt Date GMT format.
 188   * @param string|null $date     Optional. Date object.
 189   * @return string|null ISO8601/RFC3339 formatted datetime.
 190   */
 191  function bp_rest_prepare_date_response( $date_gmt, $date = null ) {
 192      if ( isset( $date ) ) {
 193          return mysql_to_rfc3339( $date );
 194      }
 195  
 196      if ( '0000-00-00 00:00:00' === $date_gmt ) {
 197          return null;
 198      }
 199  
 200      return mysql_to_rfc3339( $date_gmt );
 201  }
 202  
 203  /**
 204   * Clean up member_type input.
 205   *
 206   * @since 5.0.0
 207   *
 208   * @param string $value Comma-separated list of group types.
 209   * @return array|null
 210   */
 211  function bp_rest_sanitize_member_types( $value ) {
 212      if ( empty( $value ) ) {
 213          return $value;
 214      }
 215  
 216      $types              = explode( ',', $value );
 217      $registered_types   = bp_get_member_types();
 218      $registered_types[] = 'any';
 219      $valid_types        = array_intersect( $types, $registered_types );
 220  
 221      return ( ! empty( $valid_types ) ) ? $valid_types : null;
 222  }
 223  
 224  /**
 225   * Validate member_type input.
 226   *
 227   * @since 5.0.0
 228   *
 229   * @param  mixed $value Mixed value.
 230   * @return WP_Error|boolean
 231   */
 232  function bp_rest_validate_member_types( $value ) {
 233      if ( empty( $value ) ) {
 234          return true;
 235      }
 236  
 237      $types            = explode( ',', $value );
 238      $registered_types = bp_get_member_types();
 239  
 240      // Add the special value.
 241      $registered_types[] = 'any';
 242      foreach ( $types as $type ) {
 243          if ( ! in_array( $type, $registered_types, true ) ) {
 244              return new WP_Error(
 245                  'bp_rest_invalid_member_type',
 246                  sprintf(
 247                      /* translators: %1$s and %2$s is replaced with the registered type(s) */
 248                      __( 'The member type you provided, %1$s, is not one of %2$s.', 'buddypress' ),
 249                      $type,
 250                      implode( ', ', $registered_types )
 251                  )
 252              );
 253          }
 254      }
 255  }
 256  
 257  /**
 258   * Clean up group_type input.
 259   *
 260   * @since 5.0.0
 261   *
 262   * @param string $value Comma-separated list of group types.
 263   * @return array|null
 264   */
 265  function bp_rest_sanitize_group_types( $value ) {
 266      if ( empty( $value ) ) {
 267          return null;
 268      }
 269  
 270      $types       = explode( ',', $value );
 271      $valid_types = array_intersect( $types, bp_groups_get_group_types() );
 272  
 273      return empty( $valid_types ) ? null : $valid_types;
 274  }
 275  
 276  /**
 277   * Validate group_type input.
 278   *
 279   * @since 5.0.0
 280   *
 281   * @param  mixed $value Mixed value.
 282   * @return WP_Error|bool
 283   */
 284  function bp_rest_validate_group_types( $value ) {
 285      if ( empty( $value ) ) {
 286          return true;
 287      }
 288  
 289      $types            = explode( ',', $value );
 290      $registered_types = bp_groups_get_group_types();
 291      foreach ( $types as $type ) {
 292          if ( ! in_array( $type, $registered_types, true ) ) {
 293              return new WP_Error(
 294                  'bp_rest_invalid_group_type',
 295                  sprintf(
 296                      /* translators: %1$s and %2$s is replaced with the registered types */
 297                      __( 'The group type you provided, %1$s, is not one of %2$s.', 'buddypress' ),
 298                      $type,
 299                      implode( ', ', $registered_types )
 300                  )
 301              );
 302          }
 303      }
 304  }
 305  
 306  /**
 307   * Clean up an array, comma- or space-separated list of strings.
 308   *
 309   * @since 5.0.0
 310   *
 311   * @param array|string $list List of strings.
 312   * @return array Sanitized array of strings.
 313   */
 314  function bp_rest_sanitize_string_list( $list ) {
 315      if ( ! is_array( $list ) ) {
 316          $list = preg_split( '/[\s,]+/', $list );
 317      }
 318  
 319      return array_unique( array_map( 'sanitize_text_field', $list ) );
 320  }
 321  
 322  /**
 323   * Get the user object, if the ID is valid.
 324   *
 325   * @since 5.0.0
 326   *
 327   * @param int $user_id Supplied user ID.
 328   * @return WP_User|boolean
 329   */
 330  function bp_rest_get_user( $user_id ) {
 331      if ( (int) $user_id <= 0 ) {
 332          return false;
 333      }
 334  
 335      $user = get_userdata( (int) $user_id );
 336      if ( empty( $user ) || ! $user->exists() ) {
 337          return false;
 338      }
 339  
 340      return $user;
 341  }
 342  
 343  /**
 344   * Registers a new field on an existing BuddyPress object.
 345   *
 346   * @since 5.0.0
 347   *
 348   * @param string $component_id The name of the *active* component (eg: `activity`, `groups`, `xprofile`).
 349   *                             Required.
 350   * @param string $attribute    The attribute name. Required.
 351   * @param array  $args {
 352   *     Optional. An array of arguments used to handle the registered field.
 353   *     @see `register_rest_field()` for a full description.
 354   * }
 355   * @param string $object_type  The xProfile object type to get. This parameter is only required for
 356   *                             the Extended Profiles component. Not used for all other components.
 357   *                             Possible values are `data`, `field` or `group`.
 358   * @return bool                True if the field has been registered successfully. False otherwise.
 359   */
 360  function bp_rest_register_field( $component_id, $attribute, $args = array(), $object_type = '' ) {
 361      $registered_fields = false;
 362  
 363      if ( ! $component_id || ! bp_is_active( $component_id ) || ! $attribute ) {
 364          return $registered_fields;
 365      }
 366  
 367      // Use the `bp_` prefix as we're using a WordPress global used for Post Types.
 368      $field_name = 'bp_' . $component_id;
 369  
 370      // Use the meta type as a suffix for the field name.
 371      if ( 'xprofile' === $component_id ) {
 372          if ( ! in_array( $object_type, array( 'data', 'field', 'group' ), true ) ) {
 373              return $registered_fields;
 374          }
 375  
 376          $field_name .= '_' . $object_type;
 377      }
 378  
 379      $args = bp_parse_args(
 380          $args,
 381          array(
 382              'get_callback'    => null,
 383              'update_callback' => null,
 384              'schema'          => null,
 385          ),
 386          'rest_register_field'
 387      );
 388  
 389      // Register the field.
 390      register_rest_field( $field_name, $attribute, $args );
 391  
 392      if ( isset( $GLOBALS['wp_rest_additional_fields'][ $field_name ] ) ) {
 393          $registered_fields = $GLOBALS['wp_rest_additional_fields'][ $field_name ];
 394      }
 395  
 396      // Check it has been registered.
 397      return isset( $registered_fields[ $attribute ] );
 398  }


Generated: Sun Aug 1 01:01:41 2021 Cross-referenced by PHPXref 0.7.1