class-wc-api-resource.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. /**
  3. * WooCommerce API Resource class
  4. *
  5. * Provides shared functionality for resource-specific API classes
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 2.1
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. class WC_API_Resource {
  16. /** @var WC_API_Server the API server */
  17. protected $server;
  18. /** @var string sub-classes override this to set a resource-specific base route */
  19. protected $base;
  20. /**
  21. * Setup class
  22. *
  23. * @since 2.1
  24. * @param WC_API_Server $server
  25. */
  26. public function __construct( WC_API_Server $server ) {
  27. $this->server = $server;
  28. // automatically register routes for sub-classes
  29. add_filter( 'woocommerce_api_endpoints', array( $this, 'register_routes' ) );
  30. // maybe add meta to top-level resource responses
  31. foreach ( array( 'order', 'coupon', 'customer', 'product', 'report' ) as $resource ) {
  32. add_filter( "woocommerce_api_{$resource}_response", array( $this, 'maybe_add_meta' ), 15, 2 );
  33. }
  34. $response_names = array(
  35. 'order',
  36. 'coupon',
  37. 'customer',
  38. 'product',
  39. 'report',
  40. 'customer_orders',
  41. 'customer_downloads',
  42. 'order_note',
  43. 'order_refund',
  44. 'product_reviews',
  45. 'product_category',
  46. );
  47. foreach ( $response_names as $name ) {
  48. /**
  49. * Remove fields from responses when requests specify certain fields
  50. * note these are hooked at a later priority so data added via
  51. * filters (e.g. customer data to the order response) still has the
  52. * fields filtered properly
  53. */
  54. add_filter( "woocommerce_api_{$name}_response", array( $this, 'filter_response_fields' ), 20, 3 );
  55. }
  56. }
  57. /**
  58. * Validate the request by checking:
  59. *
  60. * 1) the ID is a valid integer
  61. * 2) the ID returns a valid post object and matches the provided post type
  62. * 3) the current user has the proper permissions to read/edit/delete the post
  63. *
  64. * @since 2.1
  65. * @param string|int $id the post ID
  66. * @param string $type the post type, either `shop_order`, `shop_coupon`, or `product`
  67. * @param string $context the context of the request, either `read`, `edit` or `delete`
  68. * @return int|WP_Error valid post ID or WP_Error if any of the checks fails
  69. */
  70. protected function validate_request( $id, $type, $context ) {
  71. if ( 'shop_order' === $type || 'shop_coupon' === $type || 'shop_webhook' === $type ) {
  72. $resource_name = str_replace( 'shop_', '', $type );
  73. } else {
  74. $resource_name = $type;
  75. }
  76. $id = absint( $id );
  77. // Validate ID
  78. if ( empty( $id ) ) {
  79. return new WP_Error( "woocommerce_api_invalid_{$resource_name}_id", sprintf( __( 'Invalid %s ID', 'woocommerce' ), $type ), array( 'status' => 404 ) );
  80. }
  81. // Only custom post types have per-post type/permission checks
  82. if ( 'customer' !== $type ) {
  83. $post = get_post( $id );
  84. if ( null === $post ) {
  85. return new WP_Error( "woocommerce_api_no_{$resource_name}_found", sprintf( __( 'No %1$s found with the ID equal to %2$s', 'woocommerce' ), $resource_name, $id ), array( 'status' => 404 ) );
  86. }
  87. // For checking permissions, product variations are the same as the product post type
  88. $post_type = ( 'product_variation' === $post->post_type ) ? 'product' : $post->post_type;
  89. // Validate post type
  90. if ( $type !== $post_type ) {
  91. return new WP_Error( "woocommerce_api_invalid_{$resource_name}", sprintf( __( 'Invalid %s', 'woocommerce' ), $resource_name ), array( 'status' => 404 ) );
  92. }
  93. // Validate permissions
  94. switch ( $context ) {
  95. case 'read':
  96. if ( ! $this->is_readable( $post ) ) {
  97. return new WP_Error( "woocommerce_api_user_cannot_read_{$resource_name}", sprintf( __( 'You do not have permission to read this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
  98. }
  99. break;
  100. case 'edit':
  101. if ( ! $this->is_editable( $post ) ) {
  102. return new WP_Error( "woocommerce_api_user_cannot_edit_{$resource_name}", sprintf( __( 'You do not have permission to edit this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
  103. }
  104. break;
  105. case 'delete':
  106. if ( ! $this->is_deletable( $post ) ) {
  107. return new WP_Error( "woocommerce_api_user_cannot_delete_{$resource_name}", sprintf( __( 'You do not have permission to delete this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
  108. }
  109. break;
  110. }
  111. }
  112. return $id;
  113. }
  114. /**
  115. * Add common request arguments to argument list before WP_Query is run
  116. *
  117. * @since 2.1
  118. * @param array $base_args required arguments for the query (e.g. `post_type`, etc)
  119. * @param array $request_args arguments provided in the request
  120. * @return array
  121. */
  122. protected function merge_query_args( $base_args, $request_args ) {
  123. $args = array();
  124. // date
  125. if ( ! empty( $request_args['created_at_min'] ) || ! empty( $request_args['created_at_max'] ) || ! empty( $request_args['updated_at_min'] ) || ! empty( $request_args['updated_at_max'] ) ) {
  126. $args['date_query'] = array();
  127. // resources created after specified date
  128. if ( ! empty( $request_args['created_at_min'] ) ) {
  129. $args['date_query'][] = array( 'column' => 'post_date_gmt', 'after' => $this->server->parse_datetime( $request_args['created_at_min'] ), 'inclusive' => true );
  130. }
  131. // resources created before specified date
  132. if ( ! empty( $request_args['created_at_max'] ) ) {
  133. $args['date_query'][] = array( 'column' => 'post_date_gmt', 'before' => $this->server->parse_datetime( $request_args['created_at_max'] ), 'inclusive' => true );
  134. }
  135. // resources updated after specified date
  136. if ( ! empty( $request_args['updated_at_min'] ) ) {
  137. $args['date_query'][] = array( 'column' => 'post_modified_gmt', 'after' => $this->server->parse_datetime( $request_args['updated_at_min'] ), 'inclusive' => true );
  138. }
  139. // resources updated before specified date
  140. if ( ! empty( $request_args['updated_at_max'] ) ) {
  141. $args['date_query'][] = array( 'column' => 'post_modified_gmt', 'before' => $this->server->parse_datetime( $request_args['updated_at_max'] ), 'inclusive' => true );
  142. }
  143. }
  144. // search
  145. if ( ! empty( $request_args['q'] ) ) {
  146. $args['s'] = $request_args['q'];
  147. }
  148. // resources per response
  149. if ( ! empty( $request_args['limit'] ) ) {
  150. $args['posts_per_page'] = $request_args['limit'];
  151. }
  152. // resource offset
  153. if ( ! empty( $request_args['offset'] ) ) {
  154. $args['offset'] = $request_args['offset'];
  155. }
  156. // order (ASC or DESC, ASC by default)
  157. if ( ! empty( $request_args['order'] ) ) {
  158. $args['order'] = $request_args['order'];
  159. }
  160. // orderby
  161. if ( ! empty( $request_args['orderby'] ) ) {
  162. $args['orderby'] = $request_args['orderby'];
  163. // allow sorting by meta value
  164. if ( ! empty( $request_args['orderby_meta_key'] ) ) {
  165. $args['meta_key'] = $request_args['orderby_meta_key'];
  166. }
  167. }
  168. // allow post status change
  169. if ( ! empty( $request_args['post_status'] ) ) {
  170. $args['post_status'] = $request_args['post_status'];
  171. unset( $request_args['post_status'] );
  172. }
  173. // filter by a list of post id
  174. if ( ! empty( $request_args['in'] ) ) {
  175. $args['post__in'] = explode( ',', $request_args['in'] );
  176. unset( $request_args['in'] );
  177. }
  178. // filter by a list of post id
  179. if ( ! empty( $request_args['in'] ) ) {
  180. $args['post__in'] = explode( ',', $request_args['in'] );
  181. unset( $request_args['in'] );
  182. }
  183. // resource page
  184. $args['paged'] = ( isset( $request_args['page'] ) ) ? absint( $request_args['page'] ) : 1;
  185. $args = apply_filters( 'woocommerce_api_query_args', $args, $request_args );
  186. return array_merge( $base_args, $args );
  187. }
  188. /**
  189. * Add meta to resources when requested by the client. Meta is added as a top-level
  190. * `<resource_name>_meta` attribute (e.g. `order_meta`) as a list of key/value pairs
  191. *
  192. * @since 2.1
  193. * @param array $data the resource data
  194. * @param object $resource the resource object (e.g WC_Order)
  195. * @return mixed
  196. */
  197. public function maybe_add_meta( $data, $resource ) {
  198. if ( isset( $this->server->params['GET']['filter']['meta'] ) && 'true' === $this->server->params['GET']['filter']['meta'] && is_object( $resource ) ) {
  199. // don't attempt to add meta more than once
  200. if ( preg_grep( '/[a-z]+_meta/', array_keys( $data ) ) ) {
  201. return $data;
  202. }
  203. // define the top-level property name for the meta
  204. switch ( get_class( $resource ) ) {
  205. case 'WC_Order':
  206. $meta_name = 'order_meta';
  207. break;
  208. case 'WC_Coupon':
  209. $meta_name = 'coupon_meta';
  210. break;
  211. case 'WP_User':
  212. $meta_name = 'customer_meta';
  213. break;
  214. default:
  215. $meta_name = 'product_meta';
  216. break;
  217. }
  218. if ( is_a( $resource, 'WP_User' ) ) {
  219. // customer meta
  220. $meta = (array) get_user_meta( $resource->ID );
  221. } else {
  222. // coupon/order/product meta
  223. $meta = (array) get_post_meta( $resource->get_id() );
  224. }
  225. foreach ( $meta as $meta_key => $meta_value ) {
  226. // don't add hidden meta by default
  227. if ( ! is_protected_meta( $meta_key ) ) {
  228. $data[ $meta_name ][ $meta_key ] = maybe_unserialize( $meta_value[0] );
  229. }
  230. }
  231. }
  232. return $data;
  233. }
  234. /**
  235. * Restrict the fields included in the response if the request specified certain only certain fields should be returned
  236. *
  237. * @since 2.1
  238. * @param array $data the response data
  239. * @param object $resource the object that provided the response data, e.g. WC_Coupon or WC_Order
  240. * @param array|string the requested list of fields to include in the response
  241. * @return array response data
  242. */
  243. public function filter_response_fields( $data, $resource, $fields ) {
  244. if ( ! is_array( $data ) || empty( $fields ) ) {
  245. return $data;
  246. }
  247. $fields = explode( ',', $fields );
  248. $sub_fields = array();
  249. // get sub fields
  250. foreach ( $fields as $field ) {
  251. if ( false !== strpos( $field, '.' ) ) {
  252. list( $name, $value ) = explode( '.', $field );
  253. $sub_fields[ $name ] = $value;
  254. }
  255. }
  256. // iterate through top-level fields
  257. foreach ( $data as $data_field => $data_value ) {
  258. // if a field has sub-fields and the top-level field has sub-fields to filter
  259. if ( is_array( $data_value ) && in_array( $data_field, array_keys( $sub_fields ) ) ) {
  260. // iterate through each sub-field
  261. foreach ( $data_value as $sub_field => $sub_field_value ) {
  262. // remove non-matching sub-fields
  263. if ( ! in_array( $sub_field, $sub_fields ) ) {
  264. unset( $data[ $data_field ][ $sub_field ] );
  265. }
  266. }
  267. } else {
  268. // remove non-matching top-level fields
  269. if ( ! in_array( $data_field, $fields ) ) {
  270. unset( $data[ $data_field ] );
  271. }
  272. }
  273. }
  274. return $data;
  275. }
  276. /**
  277. * Delete a given resource
  278. *
  279. * @since 2.1
  280. * @param int $id the resource ID
  281. * @param string $type the resource post type, or `customer`
  282. * @param bool $force true to permanently delete resource, false to move to trash (not supported for `customer`)
  283. * @return array|WP_Error
  284. */
  285. protected function delete( $id, $type, $force = false ) {
  286. if ( 'shop_order' === $type || 'shop_coupon' === $type ) {
  287. $resource_name = str_replace( 'shop_', '', $type );
  288. } else {
  289. $resource_name = $type;
  290. }
  291. if ( 'customer' === $type ) {
  292. $result = wp_delete_user( $id );
  293. if ( $result ) {
  294. return array( 'message' => __( 'Permanently deleted customer', 'woocommerce' ) );
  295. } else {
  296. return new WP_Error( 'woocommerce_api_cannot_delete_customer', __( 'The customer cannot be deleted', 'woocommerce' ), array( 'status' => 500 ) );
  297. }
  298. } else {
  299. // delete order/coupon/webhook
  300. $result = ( $force ) ? wp_delete_post( $id, true ) : wp_trash_post( $id );
  301. if ( ! $result ) {
  302. return new WP_Error( "woocommerce_api_cannot_delete_{$resource_name}", sprintf( __( 'This %s cannot be deleted', 'woocommerce' ), $resource_name ), array( 'status' => 500 ) );
  303. }
  304. if ( $force ) {
  305. return array( 'message' => sprintf( __( 'Permanently deleted %s', 'woocommerce' ), $resource_name ) );
  306. } else {
  307. $this->server->send_status( '202' );
  308. return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), $resource_name ) );
  309. }
  310. }
  311. }
  312. /**
  313. * Checks if the given post is readable by the current user
  314. *
  315. * @since 2.1
  316. * @see WC_API_Resource::check_permission()
  317. * @param WP_Post|int $post
  318. * @return bool
  319. */
  320. protected function is_readable( $post ) {
  321. return $this->check_permission( $post, 'read' );
  322. }
  323. /**
  324. * Checks if the given post is editable by the current user
  325. *
  326. * @since 2.1
  327. * @see WC_API_Resource::check_permission()
  328. * @param WP_Post|int $post
  329. * @return bool
  330. */
  331. protected function is_editable( $post ) {
  332. return $this->check_permission( $post, 'edit' );
  333. }
  334. /**
  335. * Checks if the given post is deletable by the current user
  336. *
  337. * @since 2.1
  338. * @see WC_API_Resource::check_permission()
  339. * @param WP_Post|int $post
  340. * @return bool
  341. */
  342. protected function is_deletable( $post ) {
  343. return $this->check_permission( $post, 'delete' );
  344. }
  345. /**
  346. * Checks the permissions for the current user given a post and context
  347. *
  348. * @since 2.1
  349. * @param WP_Post|int $post
  350. * @param string $context the type of permission to check, either `read`, `write`, or `delete`
  351. * @return bool true if the current user has the permissions to perform the context on the post
  352. */
  353. private function check_permission( $post, $context ) {
  354. if ( ! is_a( $post, 'WP_Post' ) ) {
  355. $post = get_post( $post );
  356. }
  357. if ( is_null( $post ) ) {
  358. return false;
  359. }
  360. $post_type = get_post_type_object( $post->post_type );
  361. if ( 'read' === $context ) {
  362. return ( 'revision' !== $post->post_type && current_user_can( $post_type->cap->read_private_posts, $post->ID ) );
  363. } elseif ( 'edit' === $context ) {
  364. return current_user_can( $post_type->cap->edit_post, $post->ID );
  365. } elseif ( 'delete' === $context ) {
  366. return current_user_can( $post_type->cap->delete_post, $post->ID );
  367. } else {
  368. return false;
  369. }
  370. }
  371. }