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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. abstract class WP_REST_Meta_Fields {
  15. /**
  16. * Retrieves the object meta type.
  17. *
  18. * @since 4.7.0
  19. *
  20. * @return string One of 'post', 'comment', 'term', 'user', or anything
  21. * else supported by `_get_meta_table()`.
  22. */
  23. abstract protected function get_meta_type();
  24. /**
  25. * Retrieves the object meta subtype.
  26. *
  27. * @since 4.9.8
  28. *
  29. * @return string Subtype for the meta type, or empty string if no specific subtype.
  30. */
  31. protected function get_meta_subtype() {
  32. return '';
  33. }
  34. /**
  35. * Retrieves the object type for register_rest_field().
  36. *
  37. * @since 4.7.0
  38. *
  39. * @return string The REST field type, such as post type name, taxonomy name, 'comment', or `user`.
  40. */
  41. abstract protected function get_rest_field_type();
  42. /**
  43. * Registers the meta field.
  44. *
  45. * @since 4.7.0
  46. *
  47. * @see register_rest_field()
  48. */
  49. public function register_field() {
  50. register_rest_field( $this->get_rest_field_type(), 'meta', array(
  51. 'get_callback' => array( $this, 'get_value' ),
  52. 'update_callback' => array( $this, 'update_value' ),
  53. 'schema' => $this->get_field_schema(),
  54. ));
  55. }
  56. /**
  57. * Retrieves the meta field value.
  58. *
  59. * @since 4.7.0
  60. *
  61. * @param int $object_id Object ID to fetch meta for.
  62. * @param WP_REST_Request $request Full details about the request.
  63. * @return WP_Error|object Object containing the meta values by name, otherwise WP_Error object.
  64. */
  65. public function get_value( $object_id, $request ) {
  66. $fields = $this->get_registered_fields();
  67. $response = array();
  68. foreach ( $fields as $meta_key => $args ) {
  69. $name = $args['name'];
  70. $all_values = get_metadata( $this->get_meta_type(), $object_id, $meta_key, false );
  71. if ( $args['single'] ) {
  72. if ( empty( $all_values ) ) {
  73. $value = $args['schema']['default'];
  74. } else {
  75. $value = $all_values[0];
  76. }
  77. $value = $this->prepare_value_for_response( $value, $request, $args );
  78. } else {
  79. $value = array();
  80. foreach ( $all_values as $row ) {
  81. $value[] = $this->prepare_value_for_response( $row, $request, $args );
  82. }
  83. }
  84. $response[ $name ] = $value;
  85. }
  86. return $response;
  87. }
  88. /**
  89. * Prepares a meta value for a response.
  90. *
  91. * This is required because some native types cannot be stored correctly
  92. * in the database, such as booleans. We need to cast back to the relevant
  93. * type before passing back to JSON.
  94. *
  95. * @since 4.7.0
  96. *
  97. * @param mixed $value Meta value to prepare.
  98. * @param WP_REST_Request $request Current request object.
  99. * @param array $args Options for the field.
  100. * @return mixed Prepared value.
  101. */
  102. protected function prepare_value_for_response( $value, $request, $args ) {
  103. if ( ! empty( $args['prepare_callback'] ) ) {
  104. $value = call_user_func( $args['prepare_callback'], $value, $request, $args );
  105. }
  106. return $value;
  107. }
  108. /**
  109. * Updates meta values.
  110. *
  111. * @since 4.7.0
  112. *
  113. * @param array $meta Array of meta parsed from the request.
  114. * @param int $object_id Object ID to fetch meta for.
  115. * @return WP_Error|null WP_Error if one occurs, null on success.
  116. */
  117. public function update_value( $meta, $object_id ) {
  118. $fields = $this->get_registered_fields();
  119. foreach ( $fields as $meta_key => $args ) {
  120. $name = $args['name'];
  121. if ( ! array_key_exists( $name, $meta ) ) {
  122. continue;
  123. }
  124. /*
  125. * A null value means reset the field, which is essentially deleting it
  126. * from the database and then relying on the default value.
  127. */
  128. if ( is_null( $meta[ $name ] ) ) {
  129. $result = $this->delete_meta_value( $object_id, $meta_key, $name );
  130. if ( is_wp_error( $result ) ) {
  131. return $result;
  132. }
  133. continue;
  134. }
  135. $is_valid = rest_validate_value_from_schema( $meta[ $name ], $args['schema'], 'meta.' . $name );
  136. if ( is_wp_error( $is_valid ) ) {
  137. $is_valid->add_data( array( 'status' => 400 ) );
  138. return $is_valid;
  139. }
  140. $value = rest_sanitize_value_from_schema( $meta[ $name ], $args['schema'] );
  141. if ( $args['single'] ) {
  142. $result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
  143. } else {
  144. $result = $this->update_multi_meta_value( $object_id, $meta_key, $name, $value );
  145. }
  146. if ( is_wp_error( $result ) ) {
  147. return $result;
  148. }
  149. }
  150. return null;
  151. }
  152. /**
  153. * Deletes a meta value for an object.
  154. *
  155. * @since 4.7.0
  156. *
  157. * @param int $object_id Object ID the field belongs to.
  158. * @param string $meta_key Key for the field.
  159. * @param string $name Name for the field that is exposed in the REST API.
  160. * @return bool|WP_Error True if meta field is deleted, WP_Error otherwise.
  161. */
  162. protected function delete_meta_value( $object_id, $meta_key, $name ) {
  163. $meta_type = $this->get_meta_type();
  164. if ( ! current_user_can( "delete_{$meta_type}_meta", $object_id, $meta_key ) ) {
  165. return new WP_Error(
  166. 'rest_cannot_delete',
  167. /* translators: %s: custom field key */
  168. sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  169. array( 'key' => $name, 'status' => rest_authorization_required_code() )
  170. );
  171. }
  172. if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
  173. return new WP_Error(
  174. 'rest_meta_database_error',
  175. __( 'Could not delete meta value from database.' ),
  176. array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  177. );
  178. }
  179. return true;
  180. }
  181. /**
  182. * Updates multiple meta values for an object.
  183. *
  184. * Alters the list of values in the database to match the list of provided values.
  185. *
  186. * @since 4.7.0
  187. *
  188. * @param int $object_id Object ID to update.
  189. * @param string $meta_key Key for the custom field.
  190. * @param string $name Name for the field that is exposed in the REST API.
  191. * @param array $values List of values to update to.
  192. * @return bool|WP_Error True if meta fields are updated, WP_Error otherwise.
  193. */
  194. protected function update_multi_meta_value( $object_id, $meta_key, $name, $values ) {
  195. $meta_type = $this->get_meta_type();
  196. if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
  197. return new WP_Error(
  198. 'rest_cannot_update',
  199. /* translators: %s: custom field key */
  200. sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  201. array( 'key' => $name, 'status' => rest_authorization_required_code() )
  202. );
  203. }
  204. $current = get_metadata( $meta_type, $object_id, $meta_key, false );
  205. $to_remove = $current;
  206. $to_add = $values;
  207. foreach ( $to_add as $add_key => $value ) {
  208. $remove_keys = array_keys( $to_remove, $value, true );
  209. if ( empty( $remove_keys ) ) {
  210. continue;
  211. }
  212. if ( count( $remove_keys ) > 1 ) {
  213. // To remove, we need to remove first, then add, so don't touch.
  214. continue;
  215. }
  216. $remove_key = $remove_keys[0];
  217. unset( $to_remove[ $remove_key ] );
  218. unset( $to_add[ $add_key ] );
  219. }
  220. // `delete_metadata` removes _all_ instances of the value, so only call once.
  221. $to_remove = array_unique( $to_remove );
  222. foreach ( $to_remove as $value ) {
  223. if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
  224. return new WP_Error(
  225. 'rest_meta_database_error',
  226. __( 'Could not update meta value in database.' ),
  227. array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  228. );
  229. }
  230. }
  231. foreach ( $to_add as $value ) {
  232. if ( ! add_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
  233. return new WP_Error(
  234. 'rest_meta_database_error',
  235. __( 'Could not update meta value in database.' ),
  236. array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  237. );
  238. }
  239. }
  240. return true;
  241. }
  242. /**
  243. * Updates a meta value for an object.
  244. *
  245. * @since 4.7.0
  246. *
  247. * @param int $object_id Object ID to update.
  248. * @param string $meta_key Key for the custom field.
  249. * @param string $name Name for the field that is exposed in the REST API.
  250. * @param mixed $value Updated value.
  251. * @return bool|WP_Error True if the meta field was updated, WP_Error otherwise.
  252. */
  253. protected function update_meta_value( $object_id, $meta_key, $name, $value ) {
  254. $meta_type = $this->get_meta_type();
  255. if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
  256. return new WP_Error(
  257. 'rest_cannot_update',
  258. /* translators: %s: custom field key */
  259. sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
  260. array( 'key' => $name, 'status' => rest_authorization_required_code() )
  261. );
  262. }
  263. $meta_key = wp_slash( $meta_key );
  264. $meta_value = wp_slash( $value );
  265. // Do the exact same check for a duplicate value as in update_metadata() to avoid update_metadata() returning false.
  266. $old_value = get_metadata( $meta_type, $object_id, $meta_key );
  267. if ( 1 === count( $old_value ) ) {
  268. if ( $old_value[0] === $meta_value ) {
  269. return true;
  270. }
  271. }
  272. if ( ! update_metadata( $meta_type, $object_id, $meta_key, $meta_value ) ) {
  273. return new WP_Error(
  274. 'rest_meta_database_error',
  275. __( 'Could not update meta value in database.' ),
  276. array( 'key' => $name, 'status' => WP_Http::INTERNAL_SERVER_ERROR )
  277. );
  278. }
  279. return true;
  280. }
  281. /**
  282. * Retrieves all the registered meta fields.
  283. *
  284. * @since 4.7.0
  285. *
  286. * @return array Registered fields.
  287. */
  288. protected function get_registered_fields() {
  289. $registered = array();
  290. $meta_type = $this->get_meta_type();
  291. $meta_subtype = $this->get_meta_subtype();
  292. $meta_keys = get_registered_meta_keys( $meta_type );
  293. if ( ! empty( $meta_subtype ) ) {
  294. $meta_keys = array_merge( $meta_keys, get_registered_meta_keys( $meta_type, $meta_subtype ) );
  295. }
  296. foreach ( $meta_keys as $name => $args ) {
  297. if ( empty( $args['show_in_rest'] ) ) {
  298. continue;
  299. }
  300. $rest_args = array();
  301. if ( is_array( $args['show_in_rest'] ) ) {
  302. $rest_args = $args['show_in_rest'];
  303. }
  304. $default_args = array(
  305. 'name' => $name,
  306. 'single' => $args['single'],
  307. 'type' => ! empty( $args['type'] ) ? $args['type'] : null,
  308. 'schema' => array(),
  309. 'prepare_callback' => array( $this, 'prepare_value' ),
  310. );
  311. $default_schema = array(
  312. 'type' => $default_args['type'],
  313. 'description' => empty( $args['description'] ) ? '' : $args['description'],
  314. 'default' => isset( $args['default'] ) ? $args['default'] : null,
  315. );
  316. $rest_args = array_merge( $default_args, $rest_args );
  317. $rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
  318. $type = ! empty( $rest_args['type'] ) ? $rest_args['type'] : null;
  319. $type = ! empty( $rest_args['schema']['type'] ) ? $rest_args['schema']['type'] : $type;
  320. if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number' ) ) ) {
  321. continue;
  322. }
  323. if ( empty( $rest_args['single'] ) ) {
  324. $rest_args['schema']['items'] = array(
  325. 'type' => $rest_args['type'],
  326. );
  327. $rest_args['schema']['type'] = 'array';
  328. }
  329. $registered[ $name ] = $rest_args;
  330. }
  331. return $registered;
  332. }
  333. /**
  334. * Retrieves the object's meta schema, conforming to JSON Schema.
  335. *
  336. * @since 4.7.0
  337. *
  338. * @return array Field schema data.
  339. */
  340. public function get_field_schema() {
  341. $fields = $this->get_registered_fields();
  342. $schema = array(
  343. 'description' => __( 'Meta fields.' ),
  344. 'type' => 'object',
  345. 'context' => array( 'view', 'edit' ),
  346. 'properties' => array(),
  347. 'arg_options' => array(
  348. 'sanitize_callback' => null,
  349. 'validate_callback' => array( $this, 'check_meta_is_array' ),
  350. ),
  351. );
  352. foreach ( $fields as $args ) {
  353. $schema['properties'][ $args['name'] ] = $args['schema'];
  354. }
  355. return $schema;
  356. }
  357. /**
  358. * Prepares a meta value for output.
  359. *
  360. * Default preparation for meta fields. Override by passing the
  361. * `prepare_callback` in your `show_in_rest` options.
  362. *
  363. * @since 4.7.0
  364. *
  365. * @param mixed $value Meta value from the database.
  366. * @param WP_REST_Request $request Request object.
  367. * @param array $args REST-specific options for the meta key.
  368. * @return mixed Value prepared for output. If a non-JsonSerializable object, null.
  369. */
  370. public static function prepare_value( $value, $request, $args ) {
  371. $type = $args['schema']['type'];
  372. // For multi-value fields, check the item type instead.
  373. if ( 'array' === $type && ! empty( $args['schema']['items']['type'] ) ) {
  374. $type = $args['schema']['items']['type'];
  375. }
  376. switch ( $type ) {
  377. case 'string':
  378. $value = (string) $value;
  379. break;
  380. case 'integer':
  381. $value = (int) $value;
  382. break;
  383. case 'number':
  384. $value = (float) $value;
  385. break;
  386. case 'boolean':
  387. $value = (bool) $value;
  388. break;
  389. }
  390. // Don't allow objects to be output.
  391. if ( is_object( $value ) && ! ( $value instanceof JsonSerializable ) ) {
  392. return null;
  393. }
  394. return $value;
  395. }
  396. /**
  397. * Check the 'meta' value of a request is an associative array.
  398. *
  399. * @since 4.7.0
  400. *
  401. * @param mixed $value The meta value submitted in the request.
  402. * @param WP_REST_Request $request Full details about the request.
  403. * @param string $param The parameter name.
  404. * @return WP_Error|string The meta array, if valid, otherwise an error.
  405. */
  406. public function check_meta_is_array( $value, $request, $param ) {
  407. if ( ! is_array( $value ) ) {
  408. return false;
  409. }
  410. return $value;
  411. }
  412. }