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


Generated: Tue Oct 15 01:00:54 2024 Cross-referenced by PHPXref 0.7.1