[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sun Apr 18 01:00:12 2021 Cross-referenced by PHPXref 0.7.1