class-wc-post-data.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. <?php
  2. /**
  3. * Post Data
  4. *
  5. * Standardises certain post data on save.
  6. *
  7. * @package WooCommerce/Classes/Data
  8. * @version 2.2.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Post data class.
  13. */
  14. class WC_Post_Data {
  15. /**
  16. * Editing term.
  17. *
  18. * @var object
  19. */
  20. private static $editing_term = null;
  21. /**
  22. * Hook in methods.
  23. */
  24. public static function init() {
  25. add_filter( 'post_type_link', array( __CLASS__, 'variation_post_link' ), 10, 2 );
  26. add_action( 'shutdown', array( __CLASS__, 'do_deferred_product_sync' ), 10 );
  27. add_action( 'set_object_terms', array( __CLASS__, 'set_object_terms' ), 10, 6 );
  28. add_action( 'set_object_terms', array( __CLASS__, 'force_default_term' ), 10, 5 );
  29. add_action( 'transition_post_status', array( __CLASS__, 'transition_post_status' ), 10, 3 );
  30. add_action( 'woocommerce_product_set_stock_status', array( __CLASS__, 'delete_product_query_transients' ) );
  31. add_action( 'woocommerce_product_set_visibility', array( __CLASS__, 'delete_product_query_transients' ) );
  32. add_action( 'woocommerce_product_type_changed', array( __CLASS__, 'product_type_changed' ), 10, 3 );
  33. add_action( 'edit_term', array( __CLASS__, 'edit_term' ), 10, 3 );
  34. add_action( 'edited_term', array( __CLASS__, 'edited_term' ), 10, 3 );
  35. add_filter( 'update_order_item_metadata', array( __CLASS__, 'update_order_item_metadata' ), 10, 5 );
  36. add_filter( 'update_post_metadata', array( __CLASS__, 'update_post_metadata' ), 10, 5 );
  37. add_filter( 'wp_insert_post_data', array( __CLASS__, 'wp_insert_post_data' ) );
  38. add_filter( 'oembed_response_data', array( __CLASS__, 'filter_oembed_response_data' ), 10, 2 );
  39. // Status transitions.
  40. add_action( 'delete_post', array( __CLASS__, 'delete_post' ) );
  41. add_action( 'wp_trash_post', array( __CLASS__, 'trash_post' ) );
  42. add_action( 'untrashed_post', array( __CLASS__, 'untrash_post' ) );
  43. add_action( 'before_delete_post', array( __CLASS__, 'before_delete_order' ) );
  44. // Meta cache flushing.
  45. add_action( 'updated_post_meta', array( __CLASS__, 'flush_object_meta_cache' ), 10, 4 );
  46. add_action( 'updated_order_item_meta', array( __CLASS__, 'flush_object_meta_cache' ), 10, 4 );
  47. }
  48. /**
  49. * Link to parent products when getting permalink for variation.
  50. *
  51. * @param string $permalink Permalink.
  52. * @param WP_Post $post Post data.
  53. *
  54. * @return string
  55. */
  56. public static function variation_post_link( $permalink, $post ) {
  57. if ( isset( $post->ID, $post->post_type ) && 'product_variation' === $post->post_type ) {
  58. $variation = wc_get_product( $post->ID );
  59. if ( $variation && $variation->get_parent_id() ) {
  60. return $variation->get_permalink();
  61. }
  62. }
  63. return $permalink;
  64. }
  65. /**
  66. * Sync products queued to sync.
  67. */
  68. public static function do_deferred_product_sync() {
  69. global $wc_deferred_product_sync;
  70. if ( ! empty( $wc_deferred_product_sync ) ) {
  71. $wc_deferred_product_sync = wp_parse_id_list( $wc_deferred_product_sync );
  72. array_walk( $wc_deferred_product_sync, array( __CLASS__, 'deferred_product_sync' ) );
  73. }
  74. }
  75. /**
  76. * Sync a product.
  77. *
  78. * @param int $product_id Product ID.
  79. */
  80. public static function deferred_product_sync( $product_id ) {
  81. $product = wc_get_product( $product_id );
  82. if ( is_callable( array( $product, 'sync' ) ) ) {
  83. $product->sync( $product );
  84. }
  85. }
  86. /**
  87. * Delete transients when terms are set.
  88. *
  89. * @param int $object_id Object ID.
  90. * @param mixed $terms An array of object terms.
  91. * @param array $tt_ids An array of term taxonomy IDs.
  92. * @param string $taxonomy Taxonomy slug.
  93. * @param mixed $append Whether to append new terms to the old terms.
  94. * @param array $old_tt_ids Old array of term taxonomy IDs.
  95. */
  96. public static function set_object_terms( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
  97. foreach ( array_merge( $tt_ids, $old_tt_ids ) as $id ) {
  98. delete_transient( 'wc_ln_count_' . md5( sanitize_key( $taxonomy ) . sanitize_key( $id ) ) );
  99. }
  100. if ( in_array( get_post_type( $object_id ), array( 'product', 'product_variation' ), true ) ) {
  101. self::delete_product_query_transients();
  102. }
  103. }
  104. /**
  105. * When a post status changes.
  106. *
  107. * @param string $new_status New status.
  108. * @param string $old_status Old status.
  109. * @param WP_Post $post Post data.
  110. */
  111. public static function transition_post_status( $new_status, $old_status, $post ) {
  112. if ( ( 'publish' === $new_status || 'publish' === $old_status ) && in_array( $post->post_type, array( 'product', 'product_variation' ), true ) ) {
  113. self::delete_product_query_transients();
  114. }
  115. }
  116. /**
  117. * Delete product view transients when needed e.g. when post status changes, or visibility/stock status is modified.
  118. */
  119. public static function delete_product_query_transients() {
  120. // Increments the transient version to invalidate cache.
  121. WC_Cache_Helper::get_transient_version( 'product_query', true );
  122. // If not using an external caching system, we can clear the transients out manually and avoid filling our DB.
  123. if ( ! wp_using_ext_object_cache() ) {
  124. global $wpdb;
  125. $wpdb->query(
  126. "
  127. DELETE FROM `$wpdb->options`
  128. WHERE `option_name` LIKE ('\_transient\_wc\_uf\_pid\_%')
  129. OR `option_name` LIKE ('\_transient\_timeout\_wc\_uf\_pid\_%')
  130. OR `option_name` LIKE ('\_transient\_wc\_products\_will\_display\_%')
  131. OR `option_name` LIKE ('\_transient\_timeout\_wc\_products\_will\_display\_%')
  132. "
  133. );
  134. }
  135. }
  136. /**
  137. * Handle type changes.
  138. *
  139. * @since 3.0.0
  140. * @param WC_Product $product Product data.
  141. * @param string $from Origin type.
  142. * @param string $to New type.
  143. */
  144. public static function product_type_changed( $product, $from, $to ) {
  145. if ( 'variable' === $from && 'variable' !== $to ) {
  146. // If the product is no longer variable, we should ensure all variations are removed.
  147. $data_store = WC_Data_Store::load( 'product-variable' );
  148. $data_store->delete_variations( $product->get_id() );
  149. }
  150. }
  151. /**
  152. * When editing a term, check for product attributes.
  153. *
  154. * @param int $term_id Term ID.
  155. * @param int $tt_id Term taxonomy ID.
  156. * @param string $taxonomy Taxonomy slug.
  157. */
  158. public static function edit_term( $term_id, $tt_id, $taxonomy ) {
  159. if ( strpos( $taxonomy, 'pa_' ) === 0 ) {
  160. self::$editing_term = get_term_by( 'id', $term_id, $taxonomy );
  161. } else {
  162. self::$editing_term = null;
  163. }
  164. }
  165. /**
  166. * When a term is edited, check for product attributes and update variations.
  167. *
  168. * @param int $term_id Term ID.
  169. * @param int $tt_id Term taxonomy ID.
  170. * @param string $taxonomy Taxonomy slug.
  171. */
  172. public static function edited_term( $term_id, $tt_id, $taxonomy ) {
  173. if ( ! is_null( self::$editing_term ) && strpos( $taxonomy, 'pa_' ) === 0 ) {
  174. $edited_term = get_term_by( 'id', $term_id, $taxonomy );
  175. if ( $edited_term->slug !== self::$editing_term->slug ) {
  176. global $wpdb;
  177. $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = %s WHERE meta_key = %s AND meta_value = %s;", $edited_term->slug, 'attribute_' . sanitize_title( $taxonomy ), self::$editing_term->slug ) );
  178. }
  179. } else {
  180. self::$editing_term = null;
  181. }
  182. }
  183. /**
  184. * Ensure floats are correctly converted to strings based on PHP locale.
  185. *
  186. * @param null $check Whether to allow updating metadata for the given type.
  187. * @param int $object_id Object ID.
  188. * @param string $meta_key Meta key.
  189. * @param mixed $meta_value Meta value. Must be serializable if non-scalar.
  190. * @param mixed $prev_value If specified, only update existing metadata entries with the specified value. Otherwise, update all entries.
  191. * @return null|bool
  192. */
  193. public static function update_order_item_metadata( $check, $object_id, $meta_key, $meta_value, $prev_value ) {
  194. if ( ! empty( $meta_value ) && is_float( $meta_value ) ) {
  195. // Convert float to string.
  196. $meta_value = wc_float_to_string( $meta_value );
  197. // Update meta value with new string.
  198. update_metadata( 'order_item', $object_id, $meta_key, $meta_value, $prev_value );
  199. return true;
  200. }
  201. return $check;
  202. }
  203. /**
  204. * Ensure floats are correctly converted to strings based on PHP locale.
  205. *
  206. * @param null $check Whether to allow updating metadata for the given type.
  207. * @param int $object_id Object ID.
  208. * @param string $meta_key Meta key.
  209. * @param mixed $meta_value Meta value. Must be serializable if non-scalar.
  210. * @param mixed $prev_value If specified, only update existing metadata entries with the specified value. Otherwise, update all entries.
  211. * @return null|bool
  212. */
  213. public static function update_post_metadata( $check, $object_id, $meta_key, $meta_value, $prev_value ) {
  214. // Delete product cache if someone uses meta directly.
  215. if ( in_array( get_post_type( $object_id ), array( 'product', 'product_variation' ), true ) ) {
  216. wp_cache_delete( 'product-' . $object_id, 'products' );
  217. }
  218. if ( ! empty( $meta_value ) && is_float( $meta_value ) && in_array( get_post_type( $object_id ), array_merge( wc_get_order_types(), array( 'shop_coupon', 'product', 'product_variation' ) ), true ) ) {
  219. // Convert float to string.
  220. $meta_value = wc_float_to_string( $meta_value );
  221. // Update meta value with new string.
  222. update_metadata( 'post', $object_id, $meta_key, $meta_value, $prev_value );
  223. return true;
  224. }
  225. return $check;
  226. }
  227. /**
  228. * When setting stock level, ensure the stock status is kept in sync.
  229. *
  230. * @param int $meta_id Meta ID.
  231. * @param int $object_id Object ID.
  232. * @param string $meta_key Meta key.
  233. * @param mixed $meta_value Meta value.
  234. * @deprecated
  235. */
  236. public static function sync_product_stock_status( $meta_id, $object_id, $meta_key, $meta_value ) {}
  237. /**
  238. * Forces the order posts to have a title in a certain format (containing the date).
  239. * Forces certain product data based on the product's type, e.g. grouped products cannot have a parent.
  240. *
  241. * @param array $data An array of slashed post data.
  242. * @return array
  243. */
  244. public static function wp_insert_post_data( $data ) {
  245. if ( 'shop_order' === $data['post_type'] && isset( $data['post_date'] ) ) {
  246. $order_title = 'Order';
  247. if ( $data['post_date'] ) {
  248. $order_title .= ' &ndash; ' . date_i18n( 'F j, Y @ h:i A', strtotime( $data['post_date'] ) );
  249. }
  250. $data['post_title'] = $order_title;
  251. } elseif ( 'product' === $data['post_type'] && isset( $_POST['product-type'] ) ) { // WPCS: input var ok, CSRF ok.
  252. $product_type = wc_clean( wp_unslash( $_POST['product-type'] ) ); // WPCS: input var ok, CSRF ok.
  253. switch ( $product_type ) {
  254. case 'grouped':
  255. case 'variable':
  256. $data['post_parent'] = 0;
  257. break;
  258. }
  259. } elseif ( 'product' === $data['post_type'] && 'auto-draft' === $data['post_status'] ) {
  260. $data['post_title'] = 'AUTO-DRAFT';
  261. }
  262. return $data;
  263. }
  264. /**
  265. * Change embed data for certain post types.
  266. *
  267. * @since 3.2.0
  268. * @param array $data The response data.
  269. * @param WP_Post $post The post object.
  270. * @return array
  271. */
  272. public static function filter_oembed_response_data( $data, $post ) {
  273. if ( in_array( $post->post_type, array( 'shop_order', 'shop_coupon' ), true ) ) {
  274. return array();
  275. }
  276. return $data;
  277. }
  278. /**
  279. * Removes variations etc belonging to a deleted post, and clears transients.
  280. *
  281. * @param mixed $id ID of post being deleted.
  282. */
  283. public static function delete_post( $id ) {
  284. if ( ! current_user_can( 'delete_posts' ) || ! $id ) {
  285. return;
  286. }
  287. $post_type = get_post_type( $id );
  288. switch ( $post_type ) {
  289. case 'product':
  290. $data_store = WC_Data_Store::load( 'product-variable' );
  291. $data_store->delete_variations( $id, true );
  292. $parent_id = wp_get_post_parent_id( $id );
  293. if ( $parent_id ) {
  294. wc_delete_product_transients( $parent_id );
  295. }
  296. break;
  297. case 'product_variation':
  298. wc_delete_product_transients( wp_get_post_parent_id( $id ) );
  299. break;
  300. case 'shop_order':
  301. global $wpdb;
  302. $refunds = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = 'shop_order_refund' AND post_parent = %d", $id ) );
  303. if ( ! is_null( $refunds ) ) {
  304. foreach ( $refunds as $refund ) {
  305. wp_delete_post( $refund->ID, true );
  306. }
  307. }
  308. break;
  309. }
  310. }
  311. /**
  312. * Trash post.
  313. *
  314. * @param mixed $id Post ID.
  315. */
  316. public static function trash_post( $id ) {
  317. if ( ! $id ) {
  318. return;
  319. }
  320. $post_type = get_post_type( $id );
  321. // If this is an order, trash any refunds too.
  322. if ( in_array( $post_type, wc_get_order_types( 'order-count' ), true ) ) {
  323. global $wpdb;
  324. $refunds = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = 'shop_order_refund' AND post_parent = %d", $id ) );
  325. foreach ( $refunds as $refund ) {
  326. $wpdb->update( $wpdb->posts, array( 'post_status' => 'trash' ), array( 'ID' => $refund->ID ) );
  327. }
  328. wc_delete_shop_order_transients( $id );
  329. // If this is a product, trash children variations.
  330. } elseif ( 'product' === $post_type ) {
  331. $data_store = WC_Data_Store::load( 'product-variable' );
  332. $data_store->delete_variations( $id, false );
  333. }
  334. }
  335. /**
  336. * Untrash post.
  337. *
  338. * @param mixed $id Post ID.
  339. */
  340. public static function untrash_post( $id ) {
  341. if ( ! $id ) {
  342. return;
  343. }
  344. $post_type = get_post_type( $id );
  345. if ( in_array( $post_type, wc_get_order_types( 'order-count' ), true ) ) {
  346. global $wpdb;
  347. $refunds = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = 'shop_order_refund' AND post_parent = %d", $id ) );
  348. foreach ( $refunds as $refund ) {
  349. $wpdb->update( $wpdb->posts, array( 'post_status' => 'wc-completed' ), array( 'ID' => $refund->ID ) );
  350. }
  351. wc_delete_shop_order_transients( $id );
  352. } elseif ( 'product' === $post_type ) {
  353. $data_store = WC_Data_Store::load( 'product-variable' );
  354. $data_store->untrash_variations( $id );
  355. wc_product_force_unique_sku( $id );
  356. }
  357. }
  358. /**
  359. * Before deleting an order, do some cleanup.
  360. *
  361. * @since 3.2.0
  362. * @param int $order_id Order ID.
  363. */
  364. public static function before_delete_order( $order_id ) {
  365. if ( in_array( get_post_type( $order_id ), wc_get_order_types(), true ) ) {
  366. // Clean up user.
  367. $order = wc_get_order( $order_id );
  368. // Check for `get_customer_id`, since this may be e.g. a refund order (which doesn't implement it).
  369. $customer_id = is_callable( array( $order, 'get_customer_id' ) ) ? $order->get_customer_id() : 0;
  370. if ( $customer_id > 0 && 'shop_order' === $order->get_type() ) {
  371. $customer = new WC_Customer( $customer_id );
  372. $order_count = $customer->get_order_count();
  373. $order_count --;
  374. if ( 0 === $order_count ) {
  375. $customer->set_is_paying_customer( false );
  376. $customer->save();
  377. }
  378. // Delete order count meta.
  379. delete_user_meta( $customer_id, '_order_count' );
  380. }
  381. // Clean up items.
  382. self::delete_order_items( $order_id );
  383. self::delete_order_downloadable_permissions( $order_id );
  384. }
  385. }
  386. /**
  387. * Remove item meta on permanent deletion.
  388. *
  389. * @param int $postid Post ID.
  390. */
  391. public static function delete_order_items( $postid ) {
  392. global $wpdb;
  393. if ( in_array( get_post_type( $postid ), wc_get_order_types(), true ) ) {
  394. do_action( 'woocommerce_delete_order_items', $postid );
  395. $wpdb->query(
  396. "
  397. DELETE {$wpdb->prefix}woocommerce_order_items, {$wpdb->prefix}woocommerce_order_itemmeta
  398. FROM {$wpdb->prefix}woocommerce_order_items
  399. JOIN {$wpdb->prefix}woocommerce_order_itemmeta ON {$wpdb->prefix}woocommerce_order_items.order_item_id = {$wpdb->prefix}woocommerce_order_itemmeta.order_item_id
  400. WHERE {$wpdb->prefix}woocommerce_order_items.order_id = '{$postid}';
  401. "
  402. ); // WPCS: unprepared SQL ok.
  403. do_action( 'woocommerce_deleted_order_items', $postid );
  404. }
  405. }
  406. /**
  407. * Remove downloadable permissions on permanent order deletion.
  408. *
  409. * @param int $postid Post ID.
  410. */
  411. public static function delete_order_downloadable_permissions( $postid ) {
  412. if ( in_array( get_post_type( $postid ), wc_get_order_types(), true ) ) {
  413. do_action( 'woocommerce_delete_order_downloadable_permissions', $postid );
  414. $data_store = WC_Data_Store::load( 'customer-download' );
  415. $data_store->delete_by_order_id( $postid );
  416. do_action( 'woocommerce_deleted_order_downloadable_permissions', $postid );
  417. }
  418. }
  419. /**
  420. * Update changed downloads.
  421. *
  422. * @deprecated 3.3.0 No action is necessary on changes to download paths since download_id is no longer based on file hash.
  423. * @param int $product_id Product ID.
  424. * @param int $variation_id Variation ID. Optional product variation identifier.
  425. * @param array $downloads Newly set files.
  426. */
  427. public static function process_product_file_download_paths( $product_id, $variation_id, $downloads ) {
  428. wc_deprecated_function( __FUNCTION__, '3.3' );
  429. }
  430. /**
  431. * Flush meta cache for CRUD objects on direct update.
  432. *
  433. * @param int $meta_id Meta ID.
  434. * @param int $object_id Object ID.
  435. * @param string $meta_key Meta key.
  436. * @param string $meta_value Meta value.
  437. */
  438. public static function flush_object_meta_cache( $meta_id, $object_id, $meta_key, $meta_value ) {
  439. WC_Cache_Helper::incr_cache_prefix( 'object_' . $object_id );
  440. }
  441. /**
  442. * Ensure default category gets set.
  443. *
  444. * @since 3.3.0
  445. * @param int $object_id Product ID.
  446. * @param array $terms Terms array.
  447. * @param array $tt_ids Term ids array.
  448. * @param string $taxonomy Taxonomy name.
  449. * @param bool $append Are we appending or setting terms.
  450. */
  451. public static function force_default_term( $object_id, $terms, $tt_ids, $taxonomy, $append ) {
  452. if ( ! $append && 'product_cat' === $taxonomy && empty( $tt_ids ) && 'product' === get_post_type( $object_id ) ) {
  453. $default_term = absint( get_option( 'default_product_cat', 0 ) );
  454. $tt_ids = array_map( 'absint', $tt_ids );
  455. if ( $default_term && ! in_array( $default_term, $tt_ids, true ) ) {
  456. wp_set_post_terms( $object_id, array( $default_term ), 'product_cat', true );
  457. }
  458. }
  459. }
  460. }
  461. WC_Post_Data::init();