[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/fields/ -> class-wp-rest-meta-fields.php (source)

   1  <?php
   2  /**
   3   * REST API: WP_REST_Meta_Fields class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.7.0
   8   */
   9  
  10  /**
  11   * Core class to manage meta values for an object via the REST API.
  12   *
  13   * @since 4.7.0
  14   */
  15  #[AllowDynamicProperties]
  16  abstract class WP_REST_Meta_Fields {
  17  
  18      /**
  19       * Retrieves the object meta type.
  20       *
  21       * @since 4.7.0
  22       *
  23       * @return string One of 'post', 'comment', 'term', 'user', or anything
  24       *                else supported by `_get_meta_table()`.
  25       */
  26      abstract protected function get_meta_type();
  27  
  28      /**
  29       * Retrieves the object meta subtype.
  30       *
  31       * @since 4.9.8
  32       *
  33       * @return string Subtype for the meta type, or empty string if no specific subtype.
  34       */
  35  	protected function get_meta_subtype() {
  36          return '';
  37      }
  38  
  39      /**
  40       * Retrieves the object type for register_rest_field().
  41       *
  42       * @since 4.7.0
  43       *
  44       * @return string The REST field type, such as post type name, taxonomy name, 'comment', or `user`.
  45       */
  46      abstract protected function get_rest_field_type();
  47  
  48      /**
  49       * Registers the meta field.
  50       *
  51       * @since 4.7.0
  52       * @deprecated 5.6.0
  53       *
  54       * @see register_rest_field()
  55       */
  56  	public function register_field() {
  57          _deprecated_function( __METHOD__, '5.6.0' );
  58  
  59          register_rest_field(
  60              $this->get_rest_field_type(),
  61              'meta',
  62              array(
  63                  'get_callback'    => array( $this, 'get_value' ),
  64                  'update_callback' => array( $this, 'update_value' ),
  65                  'schema'          => $this->get_field_schema(),
  66              )
  67          );
  68      }
  69  
  70      /**
  71       * Retrieves the meta field value.
  72       *
  73       * @since 4.7.0
  74       *
  75       * @param int             $object_id Object ID to fetch meta for.
  76       * @param WP_REST_Request $request   Full details about the request.
  77       * @return array Array containing the meta values keyed by name.
  78       */
  79  	public function get_value( $object_id, $request ) {
  80          $fields   = $this->get_registered_fields();
  81          $response = array();
  82  
  83          foreach ( $fields as $meta_key => $args ) {
  84              $name       = $args['name'];
  85              $all_values = get_metadata( $this->get_meta_type(), $object_id, $meta_key, false );
  86  
  87              if ( $args['single'] ) {
  88                  if ( empty( $all_values ) ) {
  89                      $value = $args['schema']['default'];
  90                  } else {
  91                      $value = $all_values[0];
  92                  }
  93  
  94                  $value = $this->prepare_value_for_response( $value, $request, $args );
  95              } else {
  96                  $value = array();
  97  
  98                  if ( is_array( $all_values ) ) {
  99                      foreach ( $all_values as $row ) {
 100                          $value[] = $this->prepare_value_for_response( $row, $request, $args );
 101                      }
 102                  }
 103              }
 104  
 105              $response[ $name ] = $value;
 106          }
 107  
 108          return $response;
 109      }
 110  
 111      /**
 112       * Prepares a meta value for a response.
 113       *
 114       * This is required because some native types cannot be stored correctly
 115       * in the database, such as booleans. We need to cast back to the relevant
 116       * type before passing back to JSON.
 117       *
 118       * @since 4.7.0
 119       *
 120       * @param mixed           $value   Meta value to prepare.
 121       * @param WP_REST_Request $request Current request object.
 122       * @param array           $args    Options for the field.
 123       * @return mixed Prepared value.
 124       */
 125  	protected function prepare_value_for_response( $value, $request, $args ) {
 126          if ( ! empty( $args['prepare_callback'] ) ) {
 127              $value = call_user_func( $args['prepare_callback'], $value, $request, $args );
 128          }
 129  
 130          return $value;
 131      }
 132  
 133      /**
 134       * Updates meta values.
 135       *
 136       * @since 4.7.0
 137       *
 138       * @param array $meta      Array of meta parsed from the request.
 139       * @param int   $object_id Object ID to fetch meta for.
 140       * @return null|WP_Error Null on success, WP_Error object on failure.
 141       */
 142  	public function update_value( $meta, $object_id ) {
 143          $fields = $this->get_registered_fields();
 144          $error  = new WP_Error();
 145  
 146          foreach ( $fields as $meta_key => $args ) {
 147              $name = $args['name'];
 148              if ( ! array_key_exists( $name, $meta ) ) {
 149                  continue;
 150              }
 151  
 152              $value = $meta[ $name ];
 153  
 154              /*
 155               * A null value means reset the field, which is essentially deleting it
 156               * from the database and then relying on the default value.
 157               *
 158               * Non-single meta can also be removed by passing an empty array.
 159               */
 160              if ( is_null( $value ) || ( array() === $value && ! $args['single'] ) ) {
 161                  $args = $this->get_registered_fields()[ $meta_key ];
 162  
 163                  if ( $args['single'] ) {
 164                      $current = get_metadata( $this->get_meta_type(), $object_id, $meta_key, true );
 165  
 166                      if ( is_wp_error( rest_validate_value_from_schema( $current, $args['schema'] ) ) ) {
 167                          $error->add(
 168                              'rest_invalid_stored_value',
 169                              /* translators: %s: Custom field key. */
 170                              sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
 171                              array( 'status' => 500 )
 172                          );
 173                          continue;
 174                      }
 175                  }
 176  
 177                  $result = $this->delete_meta_value( $object_id, $meta_key, $name );
 178                  if ( is_wp_error( $result ) ) {
 179                      $error->merge_from( $result );
 180                  }
 181                  continue;
 182              }
 183  
 184              if ( ! $args['single'] && is_array( $value ) && count( array_filter( $value, 'is_null' ) ) ) {
 185                  $error->add(
 186                      'rest_invalid_stored_value',
 187                      /* translators: %s: Custom field key. */
 188                      sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
 189                      array( 'status' => 500 )
 190                  );
 191                  continue;
 192              }
 193  
 194              $is_valid = rest_validate_value_from_schema( $value, $args['schema'], 'meta.' . $name );
 195              if ( is_wp_error( $is_valid ) ) {
 196                  $is_valid->add_data( array( 'status' => 400 ) );
 197                  $error->merge_from( $is_valid );
 198                  continue;
 199              }
 200  
 201              $value = rest_sanitize_value_from_schema( $value, $args['schema'] );
 202  
 203              if ( $args['single'] ) {
 204                  $result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
 205              } else {
 206                  $result = $this->update_multi_meta_value( $object_id, $meta_key, $name, $value );
 207              }
 208  
 209              if ( is_wp_error( $result ) ) {
 210                  $error->merge_from( $result );
 211                  continue;
 212              }
 213          }
 214  
 215          if ( $error->has_errors() ) {
 216              return $error;
 217          }
 218  
 219          return null;
 220      }
 221  
 222      /**
 223       * Deletes a meta value for an object.
 224       *
 225       * @since 4.7.0
 226       *
 227       * @param int    $object_id Object ID the field belongs to.
 228       * @param string $meta_key  Key for the field.
 229       * @param string $name      Name for the field that is exposed in the REST API.
 230       * @return true|WP_Error True if meta field is deleted, WP_Error otherwise.
 231       */
 232  	protected function delete_meta_value( $object_id, $meta_key, $name ) {
 233          $meta_type = $this->get_meta_type();
 234  
 235          if ( ! current_user_can( "delete_{$meta_type}_meta", $object_id, $meta_key ) ) {
 236              return new WP_Error(
 237                  'rest_cannot_delete',
 238                  /* translators: %s: Custom field key. */
 239                  sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 240                  array(
 241                      'key'    => $name,
 242                      'status' => rest_authorization_required_code(),
 243                  )
 244              );
 245          }
 246  
 247          if ( null === get_metadata_raw( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
 248              return true;
 249          }
 250  
 251          if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
 252              return new WP_Error(
 253                  'rest_meta_database_error',
 254                  __( 'Could not delete meta value from database.' ),
 255                  array(
 256                      'key'    => $name,
 257                      'status' => WP_Http::INTERNAL_SERVER_ERROR,
 258                  )
 259              );
 260          }
 261  
 262          return true;
 263      }
 264  
 265      /**
 266       * Updates multiple meta values for an object.
 267       *
 268       * Alters the list of values in the database to match the list of provided values.
 269       *
 270       * @since 4.7.0
 271       *
 272       * @param int    $object_id Object ID to update.
 273       * @param string $meta_key  Key for the custom field.
 274       * @param string $name      Name for the field that is exposed in the REST API.
 275       * @param array  $values    List of values to update to.
 276       * @return true|WP_Error True if meta fields are updated, WP_Error otherwise.
 277       */
 278  	protected function update_multi_meta_value( $object_id, $meta_key, $name, $values ) {
 279          $meta_type = $this->get_meta_type();
 280  
 281          if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
 282              return new WP_Error(
 283                  'rest_cannot_update',
 284                  /* translators: %s: Custom field key. */
 285                  sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 286                  array(
 287                      'key'    => $name,
 288                      'status' => rest_authorization_required_code(),
 289                  )
 290              );
 291          }
 292  
 293          $current_values = get_metadata( $meta_type, $object_id, $meta_key, false );
 294          $subtype        = get_object_subtype( $meta_type, $object_id );
 295  
 296          if ( ! is_array( $current_values ) ) {
 297              $current_values = array();
 298          }
 299  
 300          $to_remove = $current_values;
 301          $to_add    = $values;
 302  
 303          foreach ( $to_add as $add_key => $value ) {
 304              $remove_keys = array_keys(
 305                  array_filter(
 306                      $current_values,
 307                      function ( $stored_value ) use ( $meta_key, $subtype, $value ) {
 308                          return $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $value );
 309                      }
 310                  )
 311              );
 312  
 313              if ( empty( $remove_keys ) ) {
 314                  continue;
 315              }
 316  
 317              if ( count( $remove_keys ) > 1 ) {
 318                  // To remove, we need to remove first, then add, so don't touch.
 319                  continue;
 320              }
 321  
 322              $remove_key = $remove_keys[0];
 323  
 324              unset( $to_remove[ $remove_key ] );
 325              unset( $to_add[ $add_key ] );
 326          }
 327  
 328          /*
 329           * `delete_metadata` removes _all_ instances of the value, so only call once. Otherwise,
 330           * `delete_metadata` will return false for subsequent calls of the same value.
 331           * Use serialization to produce a predictable string that can be used by array_unique.
 332           */
 333          $to_remove = array_map( 'maybe_unserialize', array_unique( array_map( 'maybe_serialize', $to_remove ) ) );
 334  
 335          foreach ( $to_remove as $value ) {
 336              if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
 337                  return new WP_Error(
 338                      'rest_meta_database_error',
 339                      /* translators: %s: Custom field key. */
 340                      sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 341                      array(
 342                          'key'    => $name,
 343                          'status' => WP_Http::INTERNAL_SERVER_ERROR,
 344                      )
 345                  );
 346              }
 347          }
 348  
 349          foreach ( $to_add as $value ) {
 350              if ( ! add_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
 351                  return new WP_Error(
 352                      'rest_meta_database_error',
 353                      /* translators: %s: Custom field key. */
 354                      sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 355                      array(
 356                          'key'    => $name,
 357                          'status' => WP_Http::INTERNAL_SERVER_ERROR,
 358                      )
 359                  );
 360              }
 361          }
 362  
 363          return true;
 364      }
 365  
 366      /**
 367       * Updates a meta value for an object.
 368       *
 369       * @since 4.7.0
 370       *
 371       * @param int    $object_id Object ID to update.
 372       * @param string $meta_key  Key for the custom field.
 373       * @param string $name      Name for the field that is exposed in the REST API.
 374       * @param mixed  $value     Updated value.
 375       * @return true|WP_Error True if the meta field was updated, WP_Error otherwise.
 376       */
 377  	protected function update_meta_value( $object_id, $meta_key, $name, $value ) {
 378          $meta_type = $this->get_meta_type();
 379  
 380          // Do the exact same check for a duplicate value as in update_metadata() to avoid update_metadata() returning false.
 381          $old_value = get_metadata( $meta_type, $object_id, $meta_key );
 382          $subtype   = get_object_subtype( $meta_type, $object_id );
 383  
 384          if ( is_array( $old_value ) && 1 === count( $old_value )
 385              && $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $old_value[0], $value )
 386          ) {
 387              return true;
 388          }
 389  
 390          if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
 391              return new WP_Error(
 392                  'rest_cannot_update',
 393                  /* translators: %s: Custom field key. */
 394                  sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
 395                  array(
 396                      'key'    => $name,
 397                      'status' => rest_authorization_required_code(),
 398                  )
 399              );
 400          }
 401  
 402          if ( ! update_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
 403              return new WP_Error(
 404                  'rest_meta_database_error',
 405                  /* translators: %s: Custom field key. */
 406                  sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
 407                  array(
 408                      'key'    => $name,
 409                      'status' => WP_Http::INTERNAL_SERVER_ERROR,
 410                  )
 411              );
 412          }
 413  
 414          return true;
 415      }
 416  
 417      /**
 418       * Checks if the user provided value is equivalent to a stored value for the given meta key.
 419       *
 420       * @since 5.5.0
 421       *
 422       * @param string $meta_key     The meta key being checked.
 423       * @param string $subtype      The object subtype.
 424       * @param mixed  $stored_value The currently stored value retrieved from get_metadata().
 425       * @param mixed  $user_value   The value provided by the user.
 426       * @return bool
 427       */
 428  	protected function is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $user_value ) {
 429          $args      = $this->get_registered_fields()[ $meta_key ];
 430          $sanitized = sanitize_meta( $meta_key, $user_value, $this->get_meta_type(), $subtype );
 431  
 432          if ( in_array( $args['type'], array( 'string', 'number', 'integer', 'boolean' ), true ) ) {
 433              // The return value of get_metadata will always be a string for scalar types.
 434              $sanitized = (string) $sanitized;
 435          }
 436  
 437          return $sanitized === $stored_value;
 438      }
 439  
 440      /**
 441       * Retrieves all the registered meta fields.
 442       *
 443       * @since 4.7.0
 444       *
 445       * @return array Registered fields.
 446       */
 447  	protected function get_registered_fields() {
 448          $registered = array();
 449  
 450          $meta_type    = $this->get_meta_type();
 451          $meta_subtype = $this->get_meta_subtype();
 452  
 453          $meta_keys = get_registered_meta_keys( $meta_type );
 454          if ( ! empty( $meta_subtype ) ) {
 455              $meta_keys = array_merge( $meta_keys, get_registered_meta_keys( $meta_type, $meta_subtype ) );
 456          }
 457  
 458          foreach ( $meta_keys as $name => $args ) {
 459              if ( empty( $args['show_in_rest'] ) ) {
 460                  continue;
 461              }
 462  
 463              $rest_args = array();
 464  
 465              if ( is_array( $args['show_in_rest'] ) ) {
 466                  $rest_args = $args['show_in_rest'];
 467              }
 468  
 469              $default_args = array(
 470                  'name'             => $name,
 471                  'single'           => $args['single'],
 472                  'type'             => ! empty( $args['type'] ) ? $args['type'] : null,
 473                  'schema'           => array(),
 474                  'prepare_callback' => array( $this, 'prepare_value' ),
 475              );
 476  
 477              $default_schema = array(
 478                  'type'        => $default_args['type'],
 479                  'description' => empty( $args['description'] ) ? '' : $args['description'],
 480                  'default'     => isset( $args['default'] ) ? $args['default'] : null,
 481              );
 482  
 483              $rest_args           = array_merge( $default_args, $rest_args );
 484              $rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
 485  
 486              $type = ! empty( $rest_args['type'] ) ? $rest_args['type'] : null;
 487              $type = ! empty( $rest_args['schema']['type'] ) ? $rest_args['schema']['type'] : $type;
 488  
 489              if ( null === $rest_args['schema']['default'] ) {
 490                  $rest_args['schema']['default'] = static::get_empty_value_for_type( $type );
 491              }
 492  
 493              $rest_args['schema'] = rest_default_additional_properties_to_false( $rest_args['schema'] );
 494  
 495              if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number', 'array', 'object' ), true ) ) {
 496                  continue;
 497              }
 498  
 499              if ( empty( $rest_args['single'] ) ) {
 500                  $rest_args['schema'] = array(
 501                      'type'  => 'array',
 502                      'items' => $rest_args['schema'],
 503                  );
 504              }
 505  
 506              $registered[ $name ] = $rest_args;
 507          }
 508  
 509          return $registered;
 510      }
 511  
 512      /**
 513       * Retrieves the object's meta schema, conforming to JSON Schema.
 514       *
 515       * @since 4.7.0
 516       *
 517       * @return array Field schema data.
 518       */
 519  	public function get_field_schema() {
 520          $fields = $this->get_registered_fields();
 521  
 522          $schema = array(
 523              'description' => __( 'Meta fields.' ),
 524              'type'        => 'object',
 525              'context'     => array( 'view', 'edit' ),
 526              'properties'  => array(),
 527              'arg_options' => array(
 528                  'sanitize_callback' => null,
 529                  'validate_callback' => array( $this, 'check_meta_is_array' ),
 530              ),
 531          );
 532  
 533          foreach ( $fields as $args ) {
 534              $schema['properties'][ $args['name'] ] = $args['schema'];
 535          }
 536  
 537          return $schema;
 538      }
 539  
 540      /**
 541       * Prepares a meta value for output.
 542       *
 543       * Default preparation for meta fields. Override by passing the
 544       * `prepare_callback` in your `show_in_rest` options.
 545       *
 546       * @since 4.7.0
 547       *
 548       * @param mixed           $value   Meta value from the database.
 549       * @param WP_REST_Request $request Request object.
 550       * @param array           $args    REST-specific options for the meta key.
 551       * @return mixed Value prepared for output. If a non-JsonSerializable object, null.
 552       */
 553  	public static function prepare_value( $value, $request, $args ) {
 554          if ( $args['single'] ) {
 555              $schema = $args['schema'];
 556          } else {
 557              $schema = $args['schema']['items'];
 558          }
 559  
 560          if ( '' === $value && in_array( $schema['type'], array( 'boolean', 'integer', 'number' ), true ) ) {
 561              $value = static::get_empty_value_for_type( $schema['type'] );
 562          }
 563  
 564          if ( is_wp_error( rest_validate_value_from_schema( $value, $schema ) ) ) {
 565              return null;
 566          }
 567  
 568          return rest_sanitize_value_from_schema( $value, $schema );
 569      }
 570  
 571      /**
 572       * Check the 'meta' value of a request is an associative array.
 573       *
 574       * @since 4.7.0
 575       *
 576       * @param mixed           $value   The meta value submitted in the request.
 577       * @param WP_REST_Request $request Full details about the request.
 578       * @param string          $param   The parameter name.
 579       * @return array|false The meta array, if valid, false otherwise.
 580       */
 581  	public function check_meta_is_array( $value, $request, $param ) {
 582          if ( ! is_array( $value ) ) {
 583              return false;
 584          }
 585  
 586          return $value;
 587      }
 588  
 589      /**
 590       * Recursively add additionalProperties = false to all objects in a schema if no additionalProperties setting
 591       * is specified.
 592       *
 593       * This is needed to restrict properties of objects in meta values to only
 594       * registered items, as the REST API will allow additional properties by
 595       * default.
 596       *
 597       * @since 5.3.0
 598       * @deprecated 5.6.0 Use rest_default_additional_properties_to_false() instead.
 599       *
 600       * @param array $schema The schema array.
 601       * @return array
 602       */
 603  	protected function default_additional_properties_to_false( $schema ) {
 604          _deprecated_function( __METHOD__, '5.6.0', 'rest_default_additional_properties_to_false()' );
 605  
 606          return rest_default_additional_properties_to_false( $schema );
 607      }
 608  
 609      /**
 610       * Gets the empty value for a schema type.
 611       *
 612       * @since 5.3.0
 613       *
 614       * @param string $type The schema type.
 615       * @return mixed
 616       */
 617  	protected static function get_empty_value_for_type( $type ) {
 618          switch ( $type ) {
 619              case 'string':
 620                  return '';
 621              case 'boolean':
 622                  return false;
 623              case 'integer':
 624                  return 0;
 625              case 'number':
 626                  return 0.0;
 627              case 'array':
 628              case 'object':
 629                  return array();
 630              default:
 631                  return null;
 632          }
 633      }
 634  }


Generated : Thu Mar 28 08:20:01 2024 Cross-referenced by PHPXref