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

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