class-wp-rest-meta-fields.php 18 KB

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