Няма описание

class-wc-cart-session.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. /**
  3. * Cart session handling class.
  4. *
  5. * @package WooCommerce\Classes
  6. * @version 3.2.0
  7. */
  8. if ( ! defined( 'ABSPATH' ) ) {
  9. exit;
  10. }
  11. /**
  12. * WC_Cart_Session class.
  13. *
  14. * @since 3.2.0
  15. */
  16. final class WC_Cart_Session {
  17. /**
  18. * Reference to cart object.
  19. *
  20. * @since 3.2.0
  21. * @var WC_Cart
  22. */
  23. protected $cart;
  24. /**
  25. * Sets up the items provided, and calculate totals.
  26. *
  27. * @since 3.2.0
  28. * @throws Exception If missing WC_Cart object.
  29. *
  30. * @param WC_Cart $cart Cart object to calculate totals for.
  31. */
  32. public function __construct( &$cart ) {
  33. if ( ! is_a( $cart, 'WC_Cart' ) ) {
  34. throw new Exception( 'A valid WC_Cart object is required' );
  35. }
  36. $this->cart = $cart;
  37. }
  38. /**
  39. * Register methods for this object on the appropriate WordPress hooks.
  40. */
  41. public function init() {
  42. add_action( 'wp_loaded', array( $this, 'get_cart_from_session' ) );
  43. add_action( 'woocommerce_cart_emptied', array( $this, 'destroy_cart_session' ) );
  44. add_action( 'woocommerce_after_calculate_totals', array( $this, 'set_session' ) );
  45. add_action( 'woocommerce_cart_loaded_from_session', array( $this, 'set_session' ) );
  46. add_action( 'woocommerce_removed_coupon', array( $this, 'set_session' ) );
  47. // Persistent cart stored to usermeta.
  48. add_action( 'woocommerce_add_to_cart', array( $this, 'persistent_cart_update' ) );
  49. add_action( 'woocommerce_cart_item_removed', array( $this, 'persistent_cart_update' ) );
  50. add_action( 'woocommerce_cart_item_restored', array( $this, 'persistent_cart_update' ) );
  51. add_action( 'woocommerce_cart_item_set_quantity', array( $this, 'persistent_cart_update' ) );
  52. // Cookie events - cart cookies need to be set before headers are sent.
  53. add_action( 'woocommerce_add_to_cart', array( $this, 'maybe_set_cart_cookies' ) );
  54. add_action( 'wp', array( $this, 'maybe_set_cart_cookies' ), 99 );
  55. add_action( 'shutdown', array( $this, 'maybe_set_cart_cookies' ), 0 );
  56. }
  57. /**
  58. * Get the cart data from the PHP session and store it in class variables.
  59. *
  60. * @since 3.2.0
  61. */
  62. public function get_cart_from_session() {
  63. do_action( 'woocommerce_load_cart_from_session' );
  64. $this->cart->set_totals( WC()->session->get( 'cart_totals', null ) );
  65. $this->cart->set_applied_coupons( WC()->session->get( 'applied_coupons', array() ) );
  66. $this->cart->set_coupon_discount_totals( WC()->session->get( 'coupon_discount_totals', array() ) );
  67. $this->cart->set_coupon_discount_tax_totals( WC()->session->get( 'coupon_discount_tax_totals', array() ) );
  68. $this->cart->set_removed_cart_contents( WC()->session->get( 'removed_cart_contents', array() ) );
  69. $update_cart_session = false; // Flag to indicate the stored cart should be updated.
  70. $order_again = false; // Flag to indicate whether this is a re-order.
  71. $cart = WC()->session->get( 'cart', null );
  72. $merge_saved_cart = (bool) get_user_meta( get_current_user_id(), '_woocommerce_load_saved_cart_after_login', true );
  73. // Merge saved cart with current cart.
  74. if ( is_null( $cart ) || $merge_saved_cart ) {
  75. $saved_cart = $this->get_saved_cart();
  76. $cart = is_null( $cart ) ? array() : $cart;
  77. $cart = array_merge( $saved_cart, $cart );
  78. $update_cart_session = true;
  79. delete_user_meta( get_current_user_id(), '_woocommerce_load_saved_cart_after_login' );
  80. }
  81. // Populate cart from order.
  82. if ( isset( $_GET['order_again'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) { // WPCS: input var ok, sanitization ok.
  83. $cart = $this->populate_cart_from_order( absint( $_GET['order_again'] ), $cart ); // WPCS: input var ok.
  84. $order_again = true;
  85. }
  86. // Prime caches to reduce future queries.
  87. if ( is_callable( '_prime_post_caches' ) ) {
  88. _prime_post_caches( wp_list_pluck( $cart, 'product_id' ) );
  89. }
  90. $cart_contents = array();
  91. foreach ( $cart as $key => $values ) {
  92. if ( ! is_customize_preview() && 'customize-preview' === $key ) {
  93. continue;
  94. }
  95. $product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
  96. if ( empty( $product ) || ! $product->exists() || 0 >= $values['quantity'] ) {
  97. continue;
  98. }
  99. /**
  100. * Allow 3rd parties to validate this item before it's added to cart and add their own notices.
  101. *
  102. * @since 3.6.0
  103. *
  104. * @param bool $remove_cart_item_from_session If true, the item will not be added to the cart. Default: false.
  105. * @param string $key Cart item key.
  106. * @param array $values Cart item values e.g. quantity and product_id.
  107. */
  108. if ( apply_filters( 'woocommerce_pre_remove_cart_item_from_session', false, $key, $values ) ) {
  109. $update_cart_session = true;
  110. do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
  111. } elseif ( ! $product->is_purchasable() ) {
  112. $update_cart_session = true;
  113. /* translators: %s: product name */
  114. $message = sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $product->get_name() );
  115. /**
  116. * Filter message about item removed from the cart.
  117. *
  118. * @since 3.8.0
  119. * @param string $message Message.
  120. * @param WC_Product $product Product data.
  121. */
  122. $message = apply_filters( 'woocommerce_cart_item_removed_message', $message, $product );
  123. wc_add_notice( $message, 'error' );
  124. do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
  125. } elseif ( ! empty( $values['data_hash'] ) && ! hash_equals( $values['data_hash'], wc_get_cart_item_data_hash( $product ) ) ) { // phpcs:ignore PHPCompatibility.PHP.NewFunctions.hash_equalsFound
  126. $update_cart_session = true;
  127. /* translators: %1$s: product name. %2$s product permalink */
  128. wc_add_notice( sprintf( __( '%1$s has been removed from your cart because it has since been modified. You can add it back to your cart <a href="%2$s">here</a>.', 'woocommerce' ), $product->get_name(), $product->get_permalink() ), 'notice' );
  129. do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
  130. } else {
  131. // Put session data into array. Run through filter so other plugins can load their own session data.
  132. $session_data = array_merge(
  133. $values,
  134. array(
  135. 'data' => $product,
  136. )
  137. );
  138. $cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
  139. // Add to cart right away so the product is visible in woocommerce_get_cart_item_from_session hook.
  140. $this->cart->set_cart_contents( $cart_contents );
  141. }
  142. }
  143. // If it's not empty, it's been already populated by the loop above.
  144. if ( ! empty( $cart_contents ) ) {
  145. $this->cart->set_cart_contents( apply_filters( 'woocommerce_cart_contents_changed', $cart_contents ) );
  146. }
  147. do_action( 'woocommerce_cart_loaded_from_session', $this->cart );
  148. if ( $update_cart_session || is_null( WC()->session->get( 'cart_totals', null ) ) ) {
  149. WC()->session->set( 'cart', $this->get_cart_for_session() );
  150. $this->cart->calculate_totals();
  151. if ( $merge_saved_cart ) {
  152. $this->persistent_cart_update();
  153. }
  154. }
  155. // If this is a re-order, redirect to the cart page to get rid of the `order_again` query string.
  156. if ( $order_again ) {
  157. wp_safe_redirect( wc_get_cart_url() );
  158. exit;
  159. }
  160. }
  161. /**
  162. * Destroy cart session data.
  163. *
  164. * @since 3.2.0
  165. */
  166. public function destroy_cart_session() {
  167. WC()->session->set( 'cart', null );
  168. WC()->session->set( 'cart_totals', null );
  169. WC()->session->set( 'applied_coupons', null );
  170. WC()->session->set( 'coupon_discount_totals', null );
  171. WC()->session->set( 'coupon_discount_tax_totals', null );
  172. WC()->session->set( 'removed_cart_contents', null );
  173. WC()->session->set( 'order_awaiting_payment', null );
  174. }
  175. /**
  176. * Will set cart cookies if needed and when possible.
  177. *
  178. * @since 3.2.0
  179. */
  180. public function maybe_set_cart_cookies() {
  181. if ( ! headers_sent() && did_action( 'wp_loaded' ) ) {
  182. if ( ! $this->cart->is_empty() ) {
  183. $this->set_cart_cookies( true );
  184. } elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) { // WPCS: input var ok.
  185. $this->set_cart_cookies( false );
  186. }
  187. }
  188. }
  189. /**
  190. * Sets the php session data for the cart and coupons.
  191. */
  192. public function set_session() {
  193. WC()->session->set( 'cart', $this->get_cart_for_session() );
  194. WC()->session->set( 'cart_totals', $this->cart->get_totals() );
  195. WC()->session->set( 'applied_coupons', $this->cart->get_applied_coupons() );
  196. WC()->session->set( 'coupon_discount_totals', $this->cart->get_coupon_discount_totals() );
  197. WC()->session->set( 'coupon_discount_tax_totals', $this->cart->get_coupon_discount_tax_totals() );
  198. WC()->session->set( 'removed_cart_contents', $this->cart->get_removed_cart_contents() );
  199. do_action( 'woocommerce_cart_updated' );
  200. }
  201. /**
  202. * Returns the contents of the cart in an array without the 'data' element.
  203. *
  204. * @return array contents of the cart
  205. */
  206. public function get_cart_for_session() {
  207. $cart_session = array();
  208. foreach ( $this->cart->get_cart() as $key => $values ) {
  209. $cart_session[ $key ] = $values;
  210. unset( $cart_session[ $key ]['data'] ); // Unset product object.
  211. }
  212. return $cart_session;
  213. }
  214. /**
  215. * Save the persistent cart when the cart is updated.
  216. */
  217. public function persistent_cart_update() {
  218. if ( get_current_user_id() && apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
  219. update_user_meta(
  220. get_current_user_id(),
  221. '_woocommerce_persistent_cart_' . get_current_blog_id(),
  222. array(
  223. 'cart' => $this->get_cart_for_session(),
  224. )
  225. );
  226. }
  227. }
  228. /**
  229. * Delete the persistent cart permanently.
  230. */
  231. public function persistent_cart_destroy() {
  232. if ( get_current_user_id() && apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
  233. delete_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id() );
  234. }
  235. }
  236. /**
  237. * Set cart hash cookie and items in cart if not already set.
  238. *
  239. * @param bool $set Should cookies be set (true) or unset.
  240. */
  241. private function set_cart_cookies( $set = true ) {
  242. if ( $set ) {
  243. $setcookies = array(
  244. 'woocommerce_items_in_cart' => '1',
  245. 'woocommerce_cart_hash' => WC()->cart->get_cart_hash(),
  246. );
  247. foreach ( $setcookies as $name => $value ) {
  248. if ( ! isset( $_COOKIE[ $name ] ) || $_COOKIE[ $name ] !== $value ) {
  249. wc_setcookie( $name, $value );
  250. }
  251. }
  252. } else {
  253. $unsetcookies = array(
  254. 'woocommerce_items_in_cart',
  255. 'woocommerce_cart_hash',
  256. );
  257. foreach ( $unsetcookies as $name ) {
  258. if ( isset( $_COOKIE[ $name ] ) ) {
  259. wc_setcookie( $name, 0, time() - HOUR_IN_SECONDS );
  260. unset( $_COOKIE[ $name ] );
  261. }
  262. }
  263. }
  264. do_action( 'woocommerce_set_cart_cookies', $set );
  265. }
  266. /**
  267. * Get the persistent cart from the database.
  268. *
  269. * @since 3.5.0
  270. * @return array
  271. */
  272. private function get_saved_cart() {
  273. $saved_cart = array();
  274. if ( apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
  275. $saved_cart_meta = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart_' . get_current_blog_id(), true );
  276. if ( isset( $saved_cart_meta['cart'] ) ) {
  277. $saved_cart = array_filter( (array) $saved_cart_meta['cart'] );
  278. }
  279. }
  280. return $saved_cart;
  281. }
  282. /**
  283. * Get a cart from an order, if user has permission.
  284. *
  285. * @since 3.5.0
  286. *
  287. * @param int $order_id Order ID to try to load.
  288. * @param array $cart Current cart array.
  289. *
  290. * @return array
  291. */
  292. private function populate_cart_from_order( $order_id, $cart ) {
  293. $order = wc_get_order( $order_id );
  294. if ( ! $order->get_id() || ! $order->has_status( apply_filters( 'woocommerce_valid_order_statuses_for_order_again', array( 'completed' ) ) ) || ! current_user_can( 'order_again', $order->get_id() ) ) {
  295. return;
  296. }
  297. if ( apply_filters( 'woocommerce_empty_cart_when_order_again', true ) ) {
  298. $cart = array();
  299. }
  300. $inital_cart_size = count( $cart );
  301. $order_items = $order->get_items();
  302. foreach ( $order_items as $item ) {
  303. $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $item->get_product_id() );
  304. $quantity = $item->get_quantity();
  305. $variation_id = (int) $item->get_variation_id();
  306. $variations = array();
  307. $cart_item_data = apply_filters( 'woocommerce_order_again_cart_item_data', array(), $item, $order );
  308. $product = $item->get_product();
  309. if ( ! $product ) {
  310. continue;
  311. }
  312. // Prevent reordering variable products if no selected variation.
  313. if ( ! $variation_id && $product->is_type( 'variable' ) ) {
  314. continue;
  315. }
  316. // Prevent reordering items specifically out of stock.
  317. if ( ! $product->is_in_stock() ) {
  318. continue;
  319. }
  320. foreach ( $item->get_meta_data() as $meta ) {
  321. if ( taxonomy_is_product_attribute( $meta->key ) ) {
  322. $term = get_term_by( 'slug', $meta->value, $meta->key );
  323. $variations[ $meta->key ] = $term ? $term->name : $meta->value;
  324. } elseif ( meta_is_product_attribute( $meta->key, $meta->value, $product_id ) ) {
  325. $variations[ $meta->key ] = $meta->value;
  326. }
  327. }
  328. if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data ) ) {
  329. continue;
  330. }
  331. // Add to cart directly.
  332. $cart_id = WC()->cart->generate_cart_id( $product_id, $variation_id, $variations, $cart_item_data );
  333. $product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
  334. $cart[ $cart_id ] = apply_filters(
  335. 'woocommerce_add_order_again_cart_item',
  336. array_merge(
  337. $cart_item_data,
  338. array(
  339. 'key' => $cart_id,
  340. 'product_id' => $product_id,
  341. 'variation_id' => $variation_id,
  342. 'variation' => $variations,
  343. 'quantity' => $quantity,
  344. 'data' => $product_data,
  345. 'data_hash' => wc_get_cart_item_data_hash( $product_data ),
  346. )
  347. ),
  348. $cart_id
  349. );
  350. }
  351. do_action_ref_array( 'woocommerce_ordered_again', array( $order->get_id(), $order_items, &$cart ) );
  352. $num_items_in_cart = count( $cart );
  353. $num_items_in_original_order = count( $order_items );
  354. $num_items_added = $num_items_in_cart - $inital_cart_size;
  355. if ( $num_items_in_original_order > $num_items_added ) {
  356. wc_add_notice(
  357. sprintf(
  358. /* translators: %d item count */
  359. _n(
  360. '%d item from your previous order is currently unavailable and could not be added to your cart.',
  361. '%d items from your previous order are currently unavailable and could not be added to your cart.',
  362. $num_items_in_original_order - $num_items_added,
  363. 'woocommerce'
  364. ),
  365. $num_items_in_original_order - $num_items_added
  366. ),
  367. 'error'
  368. );
  369. }
  370. if ( 0 < $num_items_added ) {
  371. wc_add_notice( __( 'The cart has been filled with the items from your previous order.', 'woocommerce' ) );
  372. }
  373. return $cart;
  374. }
  375. }