Нет описания

class-acf-rest-api.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. // Exit if accessed directly.
  3. if ( ! defined( 'ABSPATH' ) ) {
  4. exit;
  5. }
  6. // If class is already defined, return.
  7. if ( class_exists( 'ACF_Rest_Api' ) ) {
  8. return;
  9. }
  10. class ACF_Rest_Api {
  11. /** @var ACF_Rest_Request */
  12. private $request;
  13. /** @var ACF_Rest_Embed_Links */
  14. private $embed_links;
  15. public function __construct() {
  16. add_action( 'rest_api_init', array( $this, 'initialize' ) );
  17. }
  18. public function initialize() {
  19. if ( ! acf_get_setting( 'rest_api_enabled' ) ) {
  20. return;
  21. }
  22. // Parse request and set the object for local access.
  23. $this->request = new ACF_Rest_Request();
  24. $this->request->parse_request();
  25. // Register the 'acf' REST property.
  26. $this->register_field();
  27. // If embed links are enabled in ACF's global settings, init the handler and set for local access.
  28. if ( acf_get_setting( 'rest_api_embed_links' ) ) {
  29. $this->embed_links = new ACF_Rest_Embed_Links();
  30. $this->embed_links->initialize();
  31. }
  32. }
  33. /**
  34. * Register our custom property as a REST field.
  35. */
  36. private function register_field() {
  37. $base = $this->request->object_sub_type;
  38. // If the object sub type ($post_type, $taxonomy, 'user') cannot be determined from the current request,
  39. // we don't know what endpoint to register the field against. Bail if that is the case.
  40. if ( ! $base ) {
  41. return;
  42. }
  43. if ( $this->request->child_object_type ) {
  44. $base = $this->request->child_object_type;
  45. }
  46. register_rest_field(
  47. $base,
  48. 'acf',
  49. array(
  50. 'schema' => $this->get_schema(),
  51. 'get_callback' => array( $this, 'load_fields' ),
  52. 'update_callback' => array( $this, 'update_fields' ),
  53. )
  54. );
  55. }
  56. /**
  57. * Dynamically generate the schema for the current request.
  58. *
  59. * @return array
  60. */
  61. private function get_schema() {
  62. $schema = array(
  63. 'description' => 'ACF field data',
  64. 'type' => 'object',
  65. 'properties' => array(),
  66. 'arg_options' => array(
  67. 'validate_callback' => array( $this, 'validate_rest_arg' ),
  68. ),
  69. );
  70. // If we don't have an object type, we can't determine the schema for the current request.
  71. $object_type = $this->request->object_type;
  72. if ( ! $object_type ) {
  73. return $schema;
  74. }
  75. $object_id = $this->request->get_url_param( 'id' );
  76. $child_id = $this->request->get_url_param( 'child_id' );
  77. $object_sub_type = $this->request->object_sub_type;
  78. if ( $child_id ) {
  79. $object_id = $child_id;
  80. }
  81. if ( ! $object_id ) {
  82. $field_groups = $this->get_field_groups_by_object_type( $object_type );
  83. } else {
  84. $field_groups = $this->get_field_groups_by_id( $object_id, $object_type, $object_sub_type );
  85. }
  86. if ( empty( $field_groups ) ) {
  87. return $schema;
  88. }
  89. foreach ( $field_groups as $field_group ) {
  90. foreach ( $this->get_fields( $field_group, $object_id ) as $field ) {
  91. $schema['properties'][ $field['name'] ] = acf_get_field_rest_schema( $field );
  92. }
  93. }
  94. return $schema;
  95. }
  96. /**
  97. * Validate the request args. Mostly a wrapper for `rest_validate_request_arg()`, but also
  98. * fires off a filter, so we can add some custom validation for specific fields.
  99. *
  100. * This will likely no longer be needed once WordPress implements something like `validate_callback`
  101. * and `sanitize_callback` for nested schema properties, see:
  102. * https://core.trac.wordpress.org/ticket/49960
  103. *
  104. * @param mixed $value
  105. * @param \WP_REST_Request $request
  106. * @param string $param
  107. *
  108. * @return bool|WP_Error
  109. */
  110. public function validate_rest_arg( $value, $request, $param ) {
  111. // Validate all fields with default WordPress validation first.
  112. $valid = rest_validate_request_arg( $value, $request, $param );
  113. if ( true !== $valid ) {
  114. return $valid;
  115. }
  116. foreach ( $value as $field_name => $field_value ) {
  117. $field = acf_get_field( $field_name );
  118. if ( ! $field ) {
  119. continue;
  120. }
  121. /**
  122. * Filters whether a value passed via REST is valid.
  123. *
  124. * @since 5.11
  125. *
  126. * @param bool $valid True if the value is valid, false or WP_Error if not.
  127. * @param mixed $value The value to check.
  128. * @param array $field An array of information about the field.
  129. */
  130. $valid = apply_filters( 'acf/validate_rest_value/type=' . $field['type'], true, $field_value, $field );
  131. if ( true !== $valid ) {
  132. return $valid;
  133. }
  134. }
  135. return true;
  136. }
  137. /**
  138. * Load field values into the requested object. This method is not a part of any public API and is only public as
  139. * it is required by WordPress.
  140. *
  141. * @param array $object An array representation of the post, term, or user object.
  142. * @param string $field_name
  143. * @param WP_REST_Request $request
  144. * @param string $object_sub_type Note that this isn't the same as $this->object_type. This variable is
  145. * more specific and can be a post type or taxonomy.
  146. * @return array
  147. */
  148. public function load_fields( $object, $field_name, $request, $object_sub_type ) {
  149. // The fields loaded for display on the REST API in the form of {$field_name}=>{$field_value} pairs.
  150. $fields = array();
  151. // Determine the object ID from the given object.
  152. $object_id = acf_get_object_id( $object );
  153. // Use this object type parsed from the request.
  154. $object_type = $this->request->object_type;
  155. // Object ID and type are essential to determining which fields to load. Return if we don't have both.
  156. if ( ! $object_id or ! $object_type ) {
  157. return $fields;
  158. }
  159. $object_sub_type = str_replace( '-revision', '', $object_sub_type );
  160. // Get all field groups for the current object.
  161. $field_groups = $this->get_field_groups_by_id( $object_id, $object_type, $object_sub_type );
  162. if ( empty( $field_groups ) ) {
  163. return $fields;
  164. }
  165. // Determine the ACF ID string for the current object.
  166. $post_id = $this->make_identifier( $object_id, $object_type );
  167. // Loop through the fields within all applicable field groups and add the fields to the response.
  168. foreach ( $field_groups as $field_group ) {
  169. foreach ( $this->get_fields( $field_group, $object_id ) as $field ) {
  170. $value = acf_get_value( $post_id, $field );
  171. if ( $this->embed_links ) {
  172. $this->embed_links->prepare_links( $post_id, $field );
  173. }
  174. // Format the field value according to the request params.
  175. $format = $request->get_param( 'acf_format' ) ?: acf_get_setting( 'rest_api_format' );
  176. $value = acf_format_value_for_rest( $value, $post_id, $field, $format );
  177. $fields[ $field['name'] ] = $value;
  178. }
  179. }
  180. return $fields;
  181. }
  182. /**
  183. * Update any incoming field values for the given object. This method is not a part of any public API and is only
  184. * public as it is required by WordPress.
  185. *
  186. * @param array $data
  187. * @param WP_Post|WP_Term|WP_User $object
  188. * @param string $property 'acf'
  189. * @param WP_REST_Request $request
  190. * @param string $object_sub_type This will be the post type, the taxonomy, or 'user'.
  191. * @return bool|WP_Error
  192. */
  193. public function update_fields( $data, $object, $property, $request, $object_sub_type ) {
  194. // If 'acf' data object is empty, don't do anything.
  195. if ( empty( $data ) ) {
  196. return true;
  197. }
  198. // Determine the object context (type & ID). If the context can't be determined from the current request, throw an
  199. // error as the fields are not updateable. This handles in line with WordPress' \WP_REST_Request::sanitize_params().
  200. $object_id = acf_get_object_id( $object );
  201. $object_type = $this->request->object_type;
  202. if ( ! $object_id or ! $object_type ) {
  203. return new WP_Error(
  204. 'acf_rest_object_unknown',
  205. __( sprintf( 'Unable to determine the %s object ID or type. The %s property cannot be updated.', get_class( $object ), $property ), 'acf' ),
  206. array( 'status' => 400 )
  207. );
  208. }
  209. // Determine the ACF selector for the current object.
  210. $post_id = $this->make_identifier( $object_id, $object_type );
  211. // Allow unrestricted update of fields by field key when saving via the WordPress admin. Admin mode will
  212. // update fields using their field keys to lookup the field. The field lookup is not scoped to field groups
  213. // located on the given object so any field can be updated. Given the field keys are not defined in the
  214. // schema, core validation/sanitisation are also bypassed.
  215. // if ( $this->is_admin_mode( $data ) ) {
  216. // Loop through payload and save fields using field keys.
  217. // foreach ( $data as $field_key => $value ) {
  218. // if ( $field = acf_get_field( $field_key ) ) {
  219. // acf_update_value( $value, $post_id, $field );
  220. // }
  221. // }
  222. //
  223. // return true;
  224. // }
  225. // todo - consider/discuss handling this in the request object instead
  226. // If the incoming data defines field group keys, extract it from the data. This is used to scope the
  227. // field lookup in \ACF_Rest_Api::get_field_groups_by_id();
  228. $field_group_scope = acf_extract_var( $data, '_acf_field_group_scope', array() );
  229. // Get all field groups for the current object.
  230. $field_groups = $this->get_field_groups_by_id( $object_id, $object_type, $object_sub_type, $field_group_scope );
  231. if ( empty( $field_groups ) ) {
  232. return true;
  233. }
  234. // Collect all fields from matching field groups.
  235. $all_fields = array();
  236. foreach ( $field_groups as $field_group ) {
  237. if ( $fields = $this->get_fields( $field_group, $object_id ) ) {
  238. $all_fields = array_merge( $fields, $all_fields );
  239. }
  240. }
  241. if ( $all_fields ) {
  242. // todo - consider/discuss handling this in the request object instead.
  243. // If the incoming request has a map of field names to keys, extract it for use in the subsequent
  244. // field search.
  245. $field_key_map = acf_extract_var( $data, '_acf_field_key_map', array() );
  246. // Loop through the inbound data payload, find the field matching the incoming field name, and
  247. // update the field.
  248. foreach ( $data as $field_name => $value ) {
  249. // If the field name has a key explicitly mapped to it, use the field key to find the field.
  250. if ( isset( $field_key_map[ $field_name ] ) ) {
  251. $field_name = $field_key_map[ $field_name ];
  252. }
  253. if ( $field = acf_search_fields( $field_name, $all_fields ) ) {
  254. acf_update_value( $value, $post_id, $field );
  255. }
  256. }
  257. }
  258. return true;
  259. }
  260. // todo - this should check for a flag and validate a nonce to ensure we are in admin mode.
  261. // todo - consider/discuss handling this in the request object instead.
  262. private function is_admin_mode( $data ) {
  263. return isset( $data['_acf_admin_mode'] ) && $data['_acf_admin_mode'];
  264. }
  265. /**
  266. * Make the ACF identifier string for the given object.
  267. *
  268. * @param int $object_id
  269. * @param string $object_type 'user', 'term', or 'post'
  270. * @return string
  271. */
  272. private function make_identifier( $object_id, $object_type ) {
  273. $formats = array(
  274. 'user' => 'user_%s',
  275. 'term' => 'term_%s',
  276. );
  277. return isset( $formats[ $object_type ] )
  278. ? sprintf( $formats[ $object_type ], $object_id )
  279. : $object_id;
  280. }
  281. /**
  282. * Gets an array of the location types that a field group is configured to use.
  283. *
  284. * @param string $object_type 'user', 'term', or 'post'
  285. * @param array $field_group The field group to check.
  286. * @param array $location_types An array of location types.
  287. *
  288. * @return bool
  289. */
  290. private function object_type_has_field_group( $object_type, $field_group, $location_types = array() ) {
  291. if ( ! isset( $field_group['location'] ) || ! is_array( $field_group['location'] ) ) {
  292. return false;
  293. }
  294. $location_types = empty( $location_types ) ? acf_get_location_types() : $location_types;
  295. foreach ( $field_group['location'] as $rule_group ) {
  296. $match = false;
  297. foreach ( $rule_group as $rule ) {
  298. $rule = acf_validate_location_rule( $rule );
  299. if ( ! isset( $location_types[ $rule['param'] ] ) ) {
  300. continue;
  301. }
  302. // Make sure the main object type matches.
  303. $location_type = $location_types[ $rule['param'] ];
  304. if ( ! isset( $location_type->object_type ) || $location_type->object_type !== (string) $object_type ) {
  305. continue;
  306. }
  307. /**
  308. * For posts/pages, we can only be sure that fields will show up if
  309. * the field group is configured to show up for all items of the current
  310. * post type.
  311. */
  312. if ( 'post' === $object_type && 'post_type' === $rule['param'] ) {
  313. if ( $rule['operator'] === '==' && $this->request->object_sub_type !== $rule['value'] ) {
  314. continue;
  315. }
  316. if ( $rule['operator'] === '!=' && $this->request->object_sub_type === $rule['value'] ) {
  317. continue;
  318. }
  319. $match = true;
  320. }
  321. if ( 'term' === $object_type && 'taxonomy' === $rule['param'] ) {
  322. if ( $rule['operator'] === '==' && $this->request->object_sub_type !== $rule['value'] ) {
  323. continue;
  324. }
  325. if ( $rule['operator'] === '!=' && $this->request->object_sub_type === $rule['value'] ) {
  326. continue;
  327. }
  328. $match = true;
  329. }
  330. if ( 'user' === $object_type ) {
  331. $match = true;
  332. }
  333. }
  334. if ( $match ) {
  335. return true;
  336. }
  337. }
  338. return false;
  339. }
  340. /**
  341. * Get all field groups for the provided object type.
  342. *
  343. * @param string $object_type 'user', 'term', or 'post'
  344. *
  345. * @return array An array of field groups that display for that location type.
  346. */
  347. private function get_field_groups_by_object_type( $object_type ) {
  348. $field_groups = acf_get_field_groups();
  349. $location_types = acf_get_location_types();
  350. $object_type_groups = array();
  351. foreach ( $field_groups as $field_group ) {
  352. if ( ! $field_group['show_in_rest'] ) {
  353. continue;
  354. }
  355. if ( $this->object_type_has_field_group( $object_type, $field_group, $location_types ) ) {
  356. $object_type_groups[] = $field_group;
  357. }
  358. }
  359. return $object_type_groups;
  360. }
  361. /**
  362. * Get all field groups for a given object.
  363. *
  364. * @param int $object_id
  365. * @param string $object_type 'user', 'term', or 'post'
  366. * @param string|null $object_sub_type The post type or taxonomy. When an $object_type of 'user' is in play, this can be ignored.
  367. * @param array $scope Field group keys to limit the returned set of field groups to. This is used to scope field lookups to specific groups.
  368. * @return array An array of matching field groups.
  369. */
  370. private function get_field_groups_by_id( $object_id, $object_type, $object_sub_type = null, $scope = array() ) {
  371. // When dealing with a term, we need the taxonomy in order to look up the relevant field groups. The taxonomy is expected
  372. // in the $object_sub_type variable but when building our schema, this isn't readily available. This block ensures the
  373. // taxonomy is set when not passed in.
  374. if ( $object_type === 'term' && $object_sub_type === null ) {
  375. $term = get_term( $object_id );
  376. if ( ! $term instanceof WP_Term ) {
  377. return array();
  378. }
  379. $object_sub_type = $term->taxonomy;
  380. }
  381. switch ( $object_type ) {
  382. case 'user':
  383. $args = array(
  384. 'user_id' => $object_id,
  385. 'rest' => true,
  386. );
  387. break;
  388. case 'term':
  389. $args = array( 'taxonomy' => $object_sub_type );
  390. break;
  391. case 'post':
  392. default:
  393. $args = array( 'post_id' => $object_id );
  394. $child_rest_base = $this->request->get_url_param( 'child_rest_base' );
  395. if ( $child_rest_base && 'post' === $object_type ) {
  396. $args['post_type'] = $object_sub_type;
  397. }
  398. }
  399. // Only return field groups that are configured to show in REST.
  400. return array_filter(
  401. acf_get_field_groups( $args ),
  402. function ( $group ) use ( $scope ) {
  403. if ( $scope and ! in_array( $group['key'], $scope ) ) {
  404. return false;
  405. }
  406. return $group['show_in_rest'];
  407. }
  408. );
  409. }
  410. /**
  411. * Get all ACF fields for a given field group and allow third party filtering.
  412. *
  413. * @param array $field_group This could technically be other possible values supported by acf_get_fields() but in this
  414. * context, we're only using the field group arrays.
  415. * @param null|int $object_id The ID of the object being prepared.
  416. * @return array
  417. */
  418. private function get_fields( $field_group, $object_id = null ) {
  419. // Get all fields for this field group that are rest enabled.
  420. $fields = array_filter(
  421. acf_get_fields( $field_group ),
  422. function ( $field ) {
  423. $field_type = acf_get_field_type( $field['type'] );
  424. return isset( $field_type->show_in_rest ) && $field_type->show_in_rest;
  425. }
  426. );
  427. // Set up context array for use in the filter below.
  428. $resource = array(
  429. 'type' => $this->request->object_type,
  430. 'sub_type' => $this->request->object_sub_type,
  431. 'id' => $object_id,
  432. );
  433. $http_method = $this->request->http_method;
  434. /**
  435. * Filter the fields available to the REST API.
  436. *
  437. * @param array $fields The ACF fields for this field group.
  438. * @param array $resource Contextual information about the current resource request.
  439. * @param string $http_method The HTTP method of the current request (GET, POST, PUT, PATCH, DELETE, OPTION, HEAD).
  440. */
  441. return (array) apply_filters( 'acf/rest/get_fields', $fields, $resource, $http_method );
  442. }
  443. }