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


Generated: Fri Apr 3 01:00:03 2020 Cross-referenced by PHPXref 0.7.1