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0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / includes / class-wc-cart.php
woocommerce / includes Last commit date
abstracts 2 years ago admin 2 years ago blocks 5 years ago cli 3 years ago customizer 3 years ago data-stores 2 years ago emails 2 years ago export 2 years ago gateways 2 years ago import 3 years ago integrations 4 years ago interfaces 3 years ago legacy 2 years ago libraries 3 years ago log-handlers 4 years ago payment-tokens 5 years ago queue 4 years ago react-admin 2 years ago rest-api 3 years ago shipping 2 years ago shortcodes 2 years ago theme-support 3 years ago tracks 2 years ago traits 5 years ago walkers 5 years ago wccom-site 3 years ago widgets 3 years ago class-wc-ajax.php 2 years ago class-wc-api.php 4 years ago class-wc-auth.php 4 years ago class-wc-autoloader.php 5 years ago class-wc-background-emailer.php 5 years ago class-wc-background-updater.php 5 years ago class-wc-breadcrumb.php 5 years ago class-wc-cache-helper.php 3 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 3 years ago class-wc-cart-totals.php 2 years ago class-wc-cart.php 3 years ago class-wc-checkout.php 3 years ago class-wc-cli.php 3 years ago class-wc-comments.php 3 years ago class-wc-countries.php 2 years ago class-wc-coupon.php 3 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 4 years ago class-wc-customer.php 3 years ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 3 years ago class-wc-datetime.php 4 years ago class-wc-deprecated-action-hooks.php 8 years ago class-wc-deprecated-filter-hooks.php 3 years ago class-wc-discounts.php 3 years ago class-wc-download-handler.php 3 years ago class-wc-emails.php 3 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 3 years ago class-wc-frontend-scripts.php 3 years ago class-wc-geo-ip.php 4 years ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 3 years ago class-wc-https.php 2 years ago class-wc-install.php 2 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 4 years ago class-wc-meta-data.php 4 years ago class-wc-order-factory.php 3 years ago class-wc-order-item-coupon.php 4 years ago class-wc-order-item-fee.php 4 years ago class-wc-order-item-meta.php 4 years ago class-wc-order-item-product.php 4 years ago class-wc-order-item-shipping.php 4 years ago class-wc-order-item-tax.php 4 years ago class-wc-order-item.php 4 years ago class-wc-order-query.php 4 years ago class-wc-order-refund.php 2 years ago class-wc-order.php 2 years ago class-wc-payment-gateways.php 4 years ago class-wc-payment-tokens.php 3 years ago class-wc-post-data.php 3 years ago class-wc-post-types.php 3 years ago class-wc-privacy-background-process.php 5 years ago class-wc-privacy-erasers.php 4 years ago class-wc-privacy-exporters.php 4 years ago class-wc-privacy.php 2 years ago class-wc-product-attribute.php 4 years ago class-wc-product-download.php 4 years ago class-wc-product-external.php 5 years ago class-wc-product-factory.php 5 years ago class-wc-product-grouped.php 8 years ago class-wc-product-query.php 5 years ago class-wc-product-simple.php 3 years ago class-wc-product-variable.php 3 years ago class-wc-product-variation.php 4 years ago class-wc-query.php 3 years ago class-wc-rate-limiter.php 4 years ago class-wc-regenerate-images-request.php 3 years ago class-wc-regenerate-images.php 3 years ago class-wc-register-wp-admin-settings.php 4 years ago class-wc-rest-authentication.php 3 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 2 years ago class-wc-shipping-rate.php 3 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 4 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 3 years ago class-wc-tax.php 2 years ago class-wc-template-loader.php 2 years ago class-wc-tracker.php 2 years ago class-wc-validation.php 3 years ago class-wc-webhook.php 3 years ago class-woocommerce.php 2 years ago wc-account-functions.php 3 years ago wc-attribute-functions.php 3 years ago wc-cart-functions.php 3 years ago wc-conditional-functions.php 3 years ago wc-core-functions.php 2 years ago wc-coupon-functions.php 3 years ago wc-deprecated-functions.php 3 years ago wc-formatting-functions.php 2 years ago wc-notice-functions.php 3 years ago wc-order-functions.php 2 years ago wc-order-item-functions.php 3 years ago wc-page-functions.php 2 years ago wc-product-functions.php 3 years ago wc-rest-functions.php 3 years ago wc-stock-functions.php 3 years ago wc-template-functions.php 2 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 3 years ago wc-update-functions.php 2 years ago wc-user-functions.php 2 years ago wc-webhook-functions.php 4 years ago wc-widget-functions.php 5 years ago
class-wc-cart.php
2147 lines
1 <?php
2 /**
3 * WooCommerce cart
4 *
5 * The WooCommerce cart class stores cart data and active coupons as well as handling customer sessions and some cart related urls.
6 * The cart class also has a price calculation function which calls upon other classes to calculate totals.
7 *
8 * @package WooCommerce\Classes
9 * @version 2.1.0
10 */
11
12 use Automattic\WooCommerce\Utilities\NumberUtil;
13
14 defined( 'ABSPATH' ) || exit;
15
16 require_once WC_ABSPATH . 'includes/legacy/class-wc-legacy-cart.php';
17 require_once WC_ABSPATH . 'includes/class-wc-cart-fees.php';
18 require_once WC_ABSPATH . 'includes/class-wc-cart-session.php';
19
20 /**
21 * WC_Cart class.
22 */
23 class WC_Cart extends WC_Legacy_Cart {
24
25 /**
26 * Contains an array of cart items.
27 *
28 * @var array
29 */
30 public $cart_contents = array();
31
32 /**
33 * Contains an array of removed cart items so we can restore them if needed.
34 *
35 * @var array
36 */
37 public $removed_cart_contents = array();
38
39 /**
40 * Contains an array of coupon codes applied to the cart.
41 *
42 * @var array
43 */
44 public $applied_coupons = array();
45
46 /**
47 * This stores the chosen shipping methods for the cart item packages.
48 *
49 * @var array
50 */
51 protected $shipping_methods;
52
53 /**
54 * Total defaults used to reset.
55 *
56 * @var array
57 */
58 protected $default_totals = array(
59 'subtotal' => 0,
60 'subtotal_tax' => 0,
61 'shipping_total' => 0,
62 'shipping_tax' => 0,
63 'shipping_taxes' => array(),
64 'discount_total' => 0,
65 'discount_tax' => 0,
66 'cart_contents_total' => 0,
67 'cart_contents_tax' => 0,
68 'cart_contents_taxes' => array(),
69 'fee_total' => 0,
70 'fee_tax' => 0,
71 'fee_taxes' => array(),
72 'total' => 0,
73 'total_tax' => 0,
74 );
75 /**
76 * Store calculated totals.
77 *
78 * @var array
79 */
80 protected $totals = array();
81
82 /**
83 * Reference to the cart session handling class.
84 *
85 * @var WC_Cart_Session
86 */
87 protected $session;
88
89 /**
90 * Reference to the cart fees API class.
91 *
92 * @var WC_Cart_Fees
93 */
94 protected $fees_api;
95
96 /**
97 * Constructor for the cart class. Loads options and hooks in the init method.
98 */
99 public function __construct() {
100 $this->session = new WC_Cart_Session( $this );
101 $this->fees_api = new WC_Cart_Fees( $this );
102
103 // Register hooks for the objects.
104 $this->session->init();
105
106 add_action( 'woocommerce_add_to_cart', array( $this, 'calculate_totals' ), 20, 0 );
107 add_action( 'woocommerce_applied_coupon', array( $this, 'calculate_totals' ), 20, 0 );
108 add_action( 'woocommerce_cart_item_removed', array( $this, 'calculate_totals' ), 20, 0 );
109 add_action( 'woocommerce_cart_item_restored', array( $this, 'calculate_totals' ), 20, 0 );
110 add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_items' ), 1 );
111 add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_coupons' ), 1 );
112 add_action( 'woocommerce_after_checkout_validation', array( $this, 'check_customer_coupons' ), 1, 2 );
113 }
114
115 /**
116 * When cloning, ensure object properties are handled.
117 *
118 * These properties store a reference to the cart, so we use new instead of clone.
119 */
120 public function __clone() {
121 $this->session = clone $this->session;
122 $this->fees_api = clone $this->fees_api;
123 }
124
125 /*
126 |--------------------------------------------------------------------------
127 | Getters.
128 |--------------------------------------------------------------------------
129 |
130 | Methods to retrieve class properties and avoid direct access.
131 */
132
133 /**
134 * Gets cart contents.
135 *
136 * @since 3.2.0
137 * @return array of cart items
138 */
139 public function get_cart_contents() {
140 return apply_filters( 'woocommerce_get_cart_contents', (array) $this->cart_contents );
141 }
142
143 /**
144 * Return items removed from the cart.
145 *
146 * @since 3.2.0
147 * @return array
148 */
149 public function get_removed_cart_contents() {
150 return (array) $this->removed_cart_contents;
151 }
152
153 /**
154 * Gets the array of applied coupon codes.
155 *
156 * @return array of applied coupons
157 */
158 public function get_applied_coupons() {
159 return (array) $this->applied_coupons;
160 }
161
162 /**
163 * Return all calculated coupon totals.
164 *
165 * @since 3.2.0
166 * @return array
167 */
168 public function get_coupon_discount_totals() {
169 return (array) $this->coupon_discount_totals;
170 }
171 /**
172 * Return all calculated coupon tax totals.
173 *
174 * @since 3.2.0
175 * @return array
176 */
177 public function get_coupon_discount_tax_totals() {
178 return (array) $this->coupon_discount_tax_totals;
179 }
180
181 /**
182 * Return all calculated totals.
183 *
184 * @since 3.2.0
185 * @return array
186 */
187 public function get_totals() {
188 return empty( $this->totals ) ? $this->default_totals : $this->totals;
189 }
190
191 /**
192 * Get a total.
193 *
194 * @since 3.2.0
195 * @param string $key Key of element in $totals array.
196 * @return mixed
197 */
198 protected function get_totals_var( $key ) {
199 return isset( $this->totals[ $key ] ) ? $this->totals[ $key ] : $this->default_totals[ $key ];
200 }
201
202 /**
203 * Get subtotal.
204 *
205 * @since 3.2.0
206 * @return float
207 */
208 public function get_subtotal() {
209 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'subtotal' ) );
210 }
211
212 /**
213 * Get subtotal_tax.
214 *
215 * @since 3.2.0
216 * @return float
217 */
218 public function get_subtotal_tax() {
219 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'subtotal_tax' ) );
220 }
221
222 /**
223 * Get discount_total.
224 *
225 * @since 3.2.0
226 * @return float
227 */
228 public function get_discount_total() {
229 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'discount_total' ) );
230 }
231
232 /**
233 * Get discount_tax.
234 *
235 * @since 3.2.0
236 * @return float
237 */
238 public function get_discount_tax() {
239 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'discount_tax' ) );
240 }
241
242 /**
243 * Get shipping_total.
244 *
245 * @since 3.2.0
246 * @return float
247 */
248 public function get_shipping_total() {
249 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'shipping_total' ) );
250 }
251
252 /**
253 * Get shipping_tax.
254 *
255 * @since 3.2.0
256 * @return float
257 */
258 public function get_shipping_tax() {
259 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'shipping_tax' ) );
260 }
261
262 /**
263 * Gets cart total. This is the total of items in the cart, but after discounts. Subtotal is before discounts.
264 *
265 * @since 3.2.0
266 * @return float
267 */
268 public function get_cart_contents_total() {
269 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'cart_contents_total' ) );
270 }
271
272 /**
273 * Gets cart tax amount.
274 *
275 * @since 3.2.0
276 * @return float
277 */
278 public function get_cart_contents_tax() {
279 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'cart_contents_tax' ) );
280 }
281
282 /**
283 * Gets cart total after calculation.
284 *
285 * @since 3.2.0
286 * @param string $context If the context is view, the value will be formatted for display. This keeps it compatible with pre-3.2 versions.
287 * @return float|string
288 */
289 public function get_total( $context = 'view' ) {
290 $total = apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'total' ) );
291 return 'view' === $context ? apply_filters( 'woocommerce_cart_total', wc_price( $total ) ) : $total;
292 }
293
294 /**
295 * Get total tax amount.
296 *
297 * @since 3.2.0
298 * @return float
299 */
300 public function get_total_tax() {
301 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'total_tax' ) );
302 }
303
304 /**
305 * Get total fee amount.
306 *
307 * @since 3.2.0
308 * @return float
309 */
310 public function get_fee_total() {
311 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'fee_total' ) );
312 }
313
314 /**
315 * Get total fee tax amount.
316 *
317 * @since 3.2.0
318 * @return float
319 */
320 public function get_fee_tax() {
321 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'fee_tax' ) );
322 }
323
324 /**
325 * Get taxes.
326 *
327 * @since 3.2.0
328 */
329 public function get_shipping_taxes() {
330 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'shipping_taxes' ) );
331 }
332
333 /**
334 * Get taxes.
335 *
336 * @since 3.2.0
337 */
338 public function get_cart_contents_taxes() {
339 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'cart_contents_taxes' ) );
340 }
341
342 /**
343 * Get taxes.
344 *
345 * @since 3.2.0
346 */
347 public function get_fee_taxes() {
348 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, $this->get_totals_var( 'fee_taxes' ) );
349 }
350
351 /**
352 * Return whether or not the cart is displaying prices including tax, rather than excluding tax.
353 *
354 * @since 3.3.0
355 * @return bool
356 */
357 public function display_prices_including_tax() {
358 return apply_filters( 'woocommerce_cart_' . __FUNCTION__, 'incl' === $this->get_tax_price_display_mode() );
359 }
360
361 /*
362 |--------------------------------------------------------------------------
363 | Setters.
364 |--------------------------------------------------------------------------
365 |
366 | Methods to set class properties and avoid direct access.
367 */
368
369 /**
370 * Sets the contents of the cart.
371 *
372 * @param array $value Cart array.
373 */
374 public function set_cart_contents( $value ) {
375 $this->cart_contents = (array) $value;
376 }
377
378 /**
379 * Set items removed from the cart.
380 *
381 * @since 3.2.0
382 * @param array $value Item array.
383 */
384 public function set_removed_cart_contents( $value = array() ) {
385 $this->removed_cart_contents = (array) $value;
386 }
387
388 /**
389 * Sets the array of applied coupon codes.
390 *
391 * @param array $value List of applied coupon codes.
392 */
393 public function set_applied_coupons( $value = array() ) {
394 $this->applied_coupons = (array) $value;
395 }
396
397 /**
398 * Sets the array of calculated coupon totals.
399 *
400 * @since 3.2.0
401 * @param array $value Value to set.
402 */
403 public function set_coupon_discount_totals( $value = array() ) {
404 $this->coupon_discount_totals = (array) $value;
405 }
406 /**
407 * Sets the array of calculated coupon tax totals.
408 *
409 * @since 3.2.0
410 * @param array $value Value to set.
411 */
412 public function set_coupon_discount_tax_totals( $value = array() ) {
413 $this->coupon_discount_tax_totals = (array) $value;
414 }
415
416 /**
417 * Set all calculated totals.
418 *
419 * @since 3.2.0
420 * @param array $value Value to set.
421 */
422 public function set_totals( $value = array() ) {
423 $this->totals = wp_parse_args( $value, $this->default_totals );
424 }
425
426 /**
427 * Set subtotal.
428 *
429 * @since 3.2.0
430 * @param string $value Value to set.
431 */
432 public function set_subtotal( $value ) {
433 $this->totals['subtotal'] = wc_format_decimal( $value );
434 }
435
436 /**
437 * Set subtotal.
438 *
439 * @since 3.2.0
440 * @param string $value Value to set.
441 */
442 public function set_subtotal_tax( $value ) {
443 $this->totals['subtotal_tax'] = $value;
444 }
445
446 /**
447 * Set discount_total.
448 *
449 * @since 3.2.0
450 * @param string $value Value to set.
451 */
452 public function set_discount_total( $value ) {
453 $this->totals['discount_total'] = $value;
454 }
455
456 /**
457 * Set discount_tax.
458 *
459 * @since 3.2.0
460 * @param string $value Value to set.
461 */
462 public function set_discount_tax( $value ) {
463 $this->totals['discount_tax'] = $value;
464 }
465
466 /**
467 * Set shipping_total.
468 *
469 * @since 3.2.0
470 * @param string $value Value to set.
471 */
472 public function set_shipping_total( $value ) {
473 $this->totals['shipping_total'] = wc_format_decimal( $value );
474 }
475
476 /**
477 * Set shipping_tax.
478 *
479 * @since 3.2.0
480 * @param string $value Value to set.
481 */
482 public function set_shipping_tax( $value ) {
483 $this->totals['shipping_tax'] = $value;
484 }
485
486 /**
487 * Set cart_contents_total.
488 *
489 * @since 3.2.0
490 * @param string $value Value to set.
491 */
492 public function set_cart_contents_total( $value ) {
493 $this->totals['cart_contents_total'] = wc_format_decimal( $value );
494 }
495
496 /**
497 * Set cart tax amount.
498 *
499 * @since 3.2.0
500 * @param string $value Value to set.
501 */
502 public function set_cart_contents_tax( $value ) {
503 $this->totals['cart_contents_tax'] = $value;
504 }
505
506 /**
507 * Set cart total.
508 *
509 * @since 3.2.0
510 * @param string $value Value to set.
511 */
512 public function set_total( $value ) {
513 $this->totals['total'] = wc_format_decimal( $value, wc_get_price_decimals() );
514 }
515
516 /**
517 * Set total tax amount.
518 *
519 * @since 3.2.0
520 * @param string $value Value to set.
521 */
522 public function set_total_tax( $value ) {
523 // We round here because this is a total entry, as opposed to line items in other setters.
524 $this->totals['total_tax'] = wc_round_tax_total( $value );
525 }
526
527 /**
528 * Set fee amount.
529 *
530 * @since 3.2.0
531 * @param string $value Value to set.
532 */
533 public function set_fee_total( $value ) {
534 $this->totals['fee_total'] = wc_format_decimal( $value );
535 }
536
537 /**
538 * Set fee tax.
539 *
540 * @since 3.2.0
541 * @param string $value Value to set.
542 */
543 public function set_fee_tax( $value ) {
544 $this->totals['fee_tax'] = $value;
545 }
546
547 /**
548 * Set taxes.
549 *
550 * @since 3.2.0
551 * @param array $value Tax values.
552 */
553 public function set_shipping_taxes( $value ) {
554 $this->totals['shipping_taxes'] = (array) $value;
555 }
556
557 /**
558 * Set taxes.
559 *
560 * @since 3.2.0
561 * @param array $value Tax values.
562 */
563 public function set_cart_contents_taxes( $value ) {
564 $this->totals['cart_contents_taxes'] = (array) $value;
565 }
566
567 /**
568 * Set taxes.
569 *
570 * @since 3.2.0
571 * @param array $value Tax values.
572 */
573 public function set_fee_taxes( $value ) {
574 $this->totals['fee_taxes'] = (array) $value;
575 }
576
577 /*
578 |--------------------------------------------------------------------------
579 | Helper methods.
580 |--------------------------------------------------------------------------
581 */
582
583 /**
584 * Returns the cart and shipping taxes, merged.
585 *
586 * @return array merged taxes
587 */
588 public function get_taxes() {
589 return apply_filters( 'woocommerce_cart_get_taxes', wc_array_merge_recursive_numeric( $this->get_shipping_taxes(), $this->get_cart_contents_taxes(), $this->get_fee_taxes() ), $this );
590 }
591
592 /**
593 * Returns the contents of the cart in an array.
594 *
595 * @return array contents of the cart
596 */
597 public function get_cart() {
598 if ( ! did_action( 'wp_loaded' ) ) {
599 wc_doing_it_wrong( __FUNCTION__, __( 'Get cart should not be called before the wp_loaded action.', 'woocommerce' ), '2.3' );
600 }
601 if ( ! did_action( 'woocommerce_load_cart_from_session' ) ) {
602 $this->session->get_cart_from_session();
603 }
604 return array_filter( $this->get_cart_contents() );
605 }
606
607 /**
608 * Returns a specific item in the cart.
609 *
610 * @param string $item_key Cart item key.
611 * @return array Item data
612 */
613 public function get_cart_item( $item_key ) {
614 return isset( $this->cart_contents[ $item_key ] ) ? $this->cart_contents[ $item_key ] : array();
615 }
616
617 /**
618 * Checks if the cart is empty.
619 *
620 * @return bool
621 */
622 public function is_empty() {
623 return 0 === count( $this->get_cart() );
624 }
625
626 /**
627 * Empties the cart and optionally the persistent cart too.
628 *
629 * @param bool $clear_persistent_cart Should the persistent cart be cleared too. Defaults to true.
630 */
631 public function empty_cart( $clear_persistent_cart = true ) {
632
633 do_action( 'woocommerce_before_cart_emptied', $clear_persistent_cart );
634
635 $this->cart_contents = array();
636 $this->removed_cart_contents = array();
637 $this->shipping_methods = array();
638 $this->coupon_discount_totals = array();
639 $this->coupon_discount_tax_totals = array();
640 $this->applied_coupons = array();
641 $this->totals = $this->default_totals;
642
643 if ( $clear_persistent_cart ) {
644 $this->session->persistent_cart_destroy();
645 }
646
647 $this->fees_api->remove_all_fees();
648
649 do_action( 'woocommerce_cart_emptied', $clear_persistent_cart );
650 }
651
652 /**
653 * Get number of items in the cart.
654 *
655 * @return int
656 */
657 public function get_cart_contents_count() {
658 return apply_filters( 'woocommerce_cart_contents_count', array_sum( wp_list_pluck( $this->get_cart(), 'quantity' ) ) );
659 }
660
661 /**
662 * Get weight of items in the cart.
663 *
664 * @since 2.5.0
665 * @return float
666 */
667 public function get_cart_contents_weight() {
668 $weight = 0.0;
669
670 foreach ( $this->get_cart() as $cart_item_key => $values ) {
671 if ( $values['data']->has_weight() ) {
672 $weight += (float) $values['data']->get_weight() * $values['quantity'];
673 }
674 }
675
676 return apply_filters( 'woocommerce_cart_contents_weight', $weight );
677 }
678
679 /**
680 * Get cart items quantities - merged so we can do accurate stock checks on items across multiple lines.
681 *
682 * @return array
683 */
684 public function get_cart_item_quantities() {
685 $quantities = array();
686
687 foreach ( $this->get_cart() as $cart_item_key => $values ) {
688 $product = $values['data'];
689 $quantities[ $product->get_stock_managed_by_id() ] = isset( $quantities[ $product->get_stock_managed_by_id() ] ) ? $quantities[ $product->get_stock_managed_by_id() ] + $values['quantity'] : $values['quantity'];
690 }
691
692 return $quantities;
693 }
694
695 /**
696 * Check all cart items for errors.
697 */
698 public function check_cart_items() {
699 $return = true;
700 $result = $this->check_cart_item_validity();
701
702 if ( is_wp_error( $result ) ) {
703 wc_add_notice( $result->get_error_message(), 'error' );
704 $return = false;
705 }
706
707 $result = $this->check_cart_item_stock();
708
709 if ( is_wp_error( $result ) ) {
710 wc_add_notice( $result->get_error_message(), 'error' );
711 $return = false;
712 }
713
714 return $return;
715
716 }
717
718 /**
719 * Check cart coupons for errors.
720 */
721 public function check_cart_coupons() {
722 foreach ( $this->get_applied_coupons() as $code ) {
723 $coupon = new WC_Coupon( $code );
724
725 if ( ! $coupon->is_valid() ) {
726 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_INVALID_REMOVED );
727 $this->remove_coupon( $code );
728 }
729 }
730 }
731
732 /**
733 * Looks through cart items and checks the posts are not trashed or deleted.
734 *
735 * @return bool|WP_Error
736 */
737 public function check_cart_item_validity() {
738 $return = true;
739
740 foreach ( $this->get_cart() as $cart_item_key => $values ) {
741 $product = $values['data'];
742
743 if ( ! $product || ! $product->exists() || 'trash' === $product->get_status() ) {
744 $this->set_quantity( $cart_item_key, 0 );
745 $return = new WP_Error( 'invalid', __( 'An item which is no longer available was removed from your cart.', 'woocommerce' ) );
746 }
747 }
748
749 return $return;
750 }
751
752 /**
753 * Looks through the cart to check each item is in stock. If not, add an error.
754 *
755 * @return bool|WP_Error
756 */
757 public function check_cart_item_stock() {
758 $error = new WP_Error();
759 $product_qty_in_cart = $this->get_cart_item_quantities();
760 $current_session_order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0;
761
762 foreach ( $this->get_cart() as $cart_item_key => $values ) {
763 $product = $values['data'];
764
765 // Check stock based on stock-status.
766 if ( ! $product->is_in_stock() ) {
767 /* translators: %s: product name */
768 $error->add( 'out-of-stock', sprintf( __( 'Sorry, "%s" is not in stock. Please edit your cart and try again. We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name() ) );
769 return $error;
770 }
771
772 // We only need to check products managing stock, with a limited stock qty.
773 if ( ! $product->managing_stock() || $product->backorders_allowed() ) {
774 continue;
775 }
776
777 // Check stock based on all items in the cart and consider any held stock within pending orders.
778 $held_stock = wc_get_held_stock_quantity( $product, $current_session_order_id );
779 $required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ];
780
781 /**
782 * Allows filter if product have enough stock to get added to the cart.
783 *
784 * @since 4.6.0
785 * @param bool $has_stock If have enough stock.
786 * @param WC_Product $product Product instance.
787 * @param array $values Cart item values.
788 */
789 if ( apply_filters( 'woocommerce_cart_item_required_stock_is_not_enough', $product->get_stock_quantity() < ( $held_stock + $required_stock ), $product, $values ) ) {
790 /* translators: 1: product name 2: quantity in stock */
791 $error->add( 'out-of-stock', sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s available). We apologize for any inconvenience caused.', 'woocommerce' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity() - $held_stock, $product ) ) );
792 return $error;
793 }
794 }
795
796 return true;
797 }
798
799 /**
800 * Gets and formats a list of cart item data + variations for display on the frontend.
801 *
802 * @param array $cart_item Cart item object.
803 * @param bool $flat Should the data be returned flat or in a list.
804 * @return string
805 */
806 public function get_item_data( $cart_item, $flat = false ) {
807 wc_deprecated_function( 'WC_Cart::get_item_data', '3.3', 'wc_get_formatted_cart_item_data' );
808
809 return wc_get_formatted_cart_item_data( $cart_item, $flat );
810 }
811
812 /**
813 * Gets cross sells based on the items in the cart.
814 *
815 * @return array cross_sells (item ids)
816 */
817 public function get_cross_sells() {
818 $cross_sells = array();
819 $in_cart = array();
820 if ( ! $this->is_empty() ) {
821 foreach ( $this->get_cart() as $cart_item_key => $values ) {
822 if ( $values['quantity'] > 0 ) {
823 $cross_sells = array_merge( $values['data']->get_cross_sell_ids(), $cross_sells );
824 $in_cart[] = $values['product_id'];
825
826 // Add variations to the in cart array.
827 if ( $values['data']->is_type( 'variation' ) ) {
828 $in_cart[] = $values['variation_id'];
829 }
830 }
831 }
832 }
833 $cross_sells = array_diff( $cross_sells, $in_cart );
834 return apply_filters( 'woocommerce_cart_crosssell_ids', wp_parse_id_list( $cross_sells ), $this );
835 }
836
837 /**
838 * Gets the url to remove an item from the cart.
839 *
840 * @param string $cart_item_key contains the id of the cart item.
841 * @return string url to page
842 */
843 public function get_remove_url( $cart_item_key ) {
844 wc_deprecated_function( 'WC_Cart::get_remove_url', '3.3', 'wc_get_cart_remove_url' );
845
846 return wc_get_cart_remove_url( $cart_item_key );
847 }
848
849 /**
850 * Gets the url to re-add an item into the cart.
851 *
852 * @param string $cart_item_key Cart item key to undo.
853 * @return string url to page
854 */
855 public function get_undo_url( $cart_item_key ) {
856 wc_deprecated_function( 'WC_Cart::get_undo_url', '3.3', 'wc_get_cart_undo_url' );
857
858 return wc_get_cart_undo_url( $cart_item_key );
859 }
860
861 /**
862 * Get taxes, merged by code, formatted ready for output.
863 *
864 * @return array
865 */
866 public function get_tax_totals() {
867 $shipping_taxes = $this->get_shipping_taxes(); // Shipping taxes are rounded differently, so we will subtract from all taxes, then round and then add them back.
868 $taxes = $this->get_taxes();
869 $tax_totals = array();
870
871 foreach ( $taxes as $key => $tax ) {
872 $code = WC_Tax::get_rate_code( $key );
873
874 if ( $code || apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) === $key ) {
875 if ( ! isset( $tax_totals[ $code ] ) ) {
876 $tax_totals[ $code ] = new stdClass();
877 $tax_totals[ $code ]->amount = 0;
878 }
879
880 $tax_totals[ $code ]->tax_rate_id = $key;
881 $tax_totals[ $code ]->is_compound = WC_Tax::is_compound( $key );
882 $tax_totals[ $code ]->label = WC_Tax::get_rate_label( $key );
883
884 if ( isset( $shipping_taxes[ $key ] ) ) {
885 $tax -= $shipping_taxes[ $key ];
886 $tax = wc_round_tax_total( $tax );
887 $tax += NumberUtil::round( $shipping_taxes[ $key ], wc_get_price_decimals() );
888 unset( $shipping_taxes[ $key ] );
889 }
890 $tax_totals[ $code ]->amount += wc_round_tax_total( $tax );
891 $tax_totals[ $code ]->formatted_amount = wc_price( $tax_totals[ $code ]->amount );
892 }
893 }
894
895 if ( apply_filters( 'woocommerce_cart_hide_zero_taxes', true ) ) {
896 $amounts = array_filter( wp_list_pluck( $tax_totals, 'amount' ) );
897 $tax_totals = array_intersect_key( $tax_totals, $amounts );
898 }
899
900 return apply_filters( 'woocommerce_cart_tax_totals', $tax_totals, $this );
901 }
902
903 /**
904 * Get all tax classes for items in the cart.
905 *
906 * @return array
907 */
908 public function get_cart_item_tax_classes() {
909 $found_tax_classes = array();
910
911 foreach ( WC()->cart->get_cart() as $item ) {
912 if ( $item['data'] && ( $item['data']->is_taxable() || $item['data']->is_shipping_taxable() ) ) {
913 $found_tax_classes[] = $item['data']->get_tax_class();
914 }
915 }
916
917 return array_unique( $found_tax_classes );
918 }
919
920 /**
921 * Get all tax classes for shipping based on the items in the cart.
922 *
923 * @return array
924 */
925 public function get_cart_item_tax_classes_for_shipping() {
926 $found_tax_classes = array();
927
928 foreach ( WC()->cart->get_cart() as $item ) {
929 if ( $item['data'] && ( $item['data']->is_shipping_taxable() ) ) {
930 $found_tax_classes[] = $item['data']->get_tax_class();
931 }
932 }
933
934 return array_unique( $found_tax_classes );
935 }
936
937 /**
938 * Determines the value that the customer spent and the subtotal
939 * displayed, used for things like coupon validation.
940 *
941 * Since the coupon lines are displayed based on the TAX DISPLAY value
942 * of cart, this is used to determine the spend.
943 *
944 * If cart totals are shown including tax, use the subtotal.
945 * If cart totals are shown excluding tax, use the subtotal ex tax
946 * (tax is shown after coupons).
947 *
948 * @since 2.6.0
949 * @return string
950 */
951 public function get_displayed_subtotal() {
952 return $this->display_prices_including_tax() ? $this->get_subtotal() + $this->get_subtotal_tax() : $this->get_subtotal();
953 }
954
955 /**
956 * Check if product is in the cart and return cart item key.
957 *
958 * Cart item key will be unique based on the item and its properties, such as variations.
959 *
960 * @param mixed $cart_id id of product to find in the cart.
961 * @return string cart item key
962 */
963 public function find_product_in_cart( $cart_id = false ) {
964 if ( false !== $cart_id ) {
965 if ( is_array( $this->cart_contents ) && isset( $this->cart_contents[ $cart_id ] ) ) {
966 return $cart_id;
967 }
968 }
969 return '';
970 }
971
972 /**
973 * Generate a unique ID for the cart item being added.
974 *
975 * @param int $product_id - id of the product the key is being generated for.
976 * @param int $variation_id of the product the key is being generated for.
977 * @param array $variation data for the cart item.
978 * @param array $cart_item_data other cart item data passed which affects this items uniqueness in the cart.
979 * @return string cart item key
980 */
981 public function generate_cart_id( $product_id, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
982 $id_parts = array( $product_id );
983
984 if ( $variation_id && 0 !== $variation_id ) {
985 $id_parts[] = $variation_id;
986 }
987
988 if ( is_array( $variation ) && ! empty( $variation ) ) {
989 $variation_key = '';
990 foreach ( $variation as $key => $value ) {
991 $variation_key .= trim( $key ) . trim( $value );
992 }
993 $id_parts[] = $variation_key;
994 }
995
996 if ( is_array( $cart_item_data ) && ! empty( $cart_item_data ) ) {
997 $cart_item_data_key = '';
998 foreach ( $cart_item_data as $key => $value ) {
999 if ( is_array( $value ) || is_object( $value ) ) {
1000 $value = http_build_query( $value );
1001 }
1002 $cart_item_data_key .= trim( $key ) . trim( $value );
1003
1004 }
1005 $id_parts[] = $cart_item_data_key;
1006 }
1007
1008 return apply_filters( 'woocommerce_cart_id', md5( implode( '_', $id_parts ) ), $product_id, $variation_id, $variation, $cart_item_data );
1009 }
1010
1011 /**
1012 * Add a product to the cart.
1013 *
1014 * @throws Exception Plugins can throw an exception to prevent adding to cart.
1015 * @param int $product_id contains the id of the product to add to the cart.
1016 * @param int $quantity contains the quantity of the item to add.
1017 * @param int $variation_id ID of the variation being added to the cart.
1018 * @param array $variation attribute values.
1019 * @param array $cart_item_data extra cart item data we want to pass into the item.
1020 * @return string|bool $cart_item_key
1021 */
1022 public function add_to_cart( $product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
1023 try {
1024 $product_id = absint( $product_id );
1025 $variation_id = absint( $variation_id );
1026
1027 // Ensure we don't add a variation to the cart directly by variation ID.
1028 if ( 'product_variation' === get_post_type( $product_id ) ) {
1029 $variation_id = $product_id;
1030 $product_id = wp_get_post_parent_id( $variation_id );
1031 }
1032
1033 $product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
1034 $quantity = apply_filters( 'woocommerce_add_to_cart_quantity', $quantity, $product_id );
1035
1036 if ( $quantity <= 0 || ! $product_data || 'trash' === $product_data->get_status() ) {
1037 return false;
1038 }
1039
1040 if ( $product_data->is_type( 'variation' ) ) {
1041 $missing_attributes = array();
1042 $parent_data = wc_get_product( $product_data->get_parent_id() );
1043
1044 $variation_attributes = $product_data->get_variation_attributes();
1045 // Filter out 'any' variations, which are empty, as they need to be explicitly specified while adding to cart.
1046 $variation_attributes = array_filter( $variation_attributes );
1047
1048 // Gather posted attributes.
1049 $posted_attributes = array();
1050 foreach ( $parent_data->get_attributes() as $attribute ) {
1051 if ( ! $attribute['is_variation'] ) {
1052 continue;
1053 }
1054 $attribute_key = 'attribute_' . sanitize_title( $attribute['name'] );
1055
1056 if ( isset( $variation[ $attribute_key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1057 if ( $attribute['is_taxonomy'] ) {
1058 // Don't use wc_clean as it destroys sanitized characters.
1059 $value = sanitize_title( wp_unslash( $variation[ $attribute_key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1060 } else {
1061 $value = html_entity_decode( wc_clean( wp_unslash( $variation[ $attribute_key ] ) ), ENT_QUOTES, get_bloginfo( 'charset' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1062 }
1063
1064 // Don't include if it's empty.
1065 if ( ! empty( $value ) || '0' === $value ) {
1066 $posted_attributes[ $attribute_key ] = $value;
1067 }
1068 }
1069 }
1070
1071 // Merge variation attributes and posted attributes.
1072 $posted_and_variation_attributes = array_merge( $variation_attributes, $posted_attributes );
1073
1074 // If no variation ID is set, attempt to get a variation ID from posted attributes.
1075 if ( empty( $variation_id ) ) {
1076 $data_store = WC_Data_Store::load( 'product' );
1077 $variation_id = $data_store->find_matching_product_variation( $parent_data, $posted_attributes );
1078 }
1079
1080 // Do we have a variation ID?
1081 if ( empty( $variation_id ) ) {
1082 throw new Exception( __( 'Please choose product options&hellip;', 'woocommerce' ) );
1083 }
1084
1085 // Check the data we have is valid.
1086 $variation_data = wc_get_product_variation_attributes( $variation_id );
1087 $attributes = array();
1088
1089 foreach ( $parent_data->get_attributes() as $attribute ) {
1090 if ( ! $attribute['is_variation'] ) {
1091 continue;
1092 }
1093
1094 // Get valid value from variation data.
1095 $attribute_key = 'attribute_' . sanitize_title( $attribute['name'] );
1096 $valid_value = isset( $variation_data[ $attribute_key ] ) ? $variation_data[ $attribute_key ] : '';
1097
1098 /**
1099 * If the attribute value was posted, check if it's valid.
1100 *
1101 * If no attribute was posted, only error if the variation has an 'any' attribute which requires a value.
1102 */
1103 if ( isset( $posted_and_variation_attributes[ $attribute_key ] ) ) {
1104 $value = $posted_and_variation_attributes[ $attribute_key ];
1105
1106 // Allow if valid or show error.
1107 if ( $valid_value === $value ) {
1108 $attributes[ $attribute_key ] = $value;
1109 } elseif ( '' === $valid_value && in_array( $value, $attribute->get_slugs(), true ) ) {
1110 // If valid values are empty, this is an 'any' variation so get all possible values.
1111 $attributes[ $attribute_key ] = $value;
1112 } else {
1113 /* translators: %s: Attribute name. */
1114 throw new Exception( sprintf( __( 'Invalid value posted for %s', 'woocommerce' ), wc_attribute_label( $attribute['name'] ) ) );
1115 }
1116 } elseif ( '' === $valid_value ) {
1117 $missing_attributes[] = wc_attribute_label( $attribute['name'] );
1118 }
1119
1120 $variation = $attributes;
1121 }
1122 if ( ! empty( $missing_attributes ) ) {
1123 /* translators: %s: Attribute name. */
1124 throw new Exception( sprintf( _n( '%s is a required field', '%s are required fields', count( $missing_attributes ), 'woocommerce' ), wc_format_list_of_items( $missing_attributes ) ) );
1125 }
1126 }
1127
1128 // Validate variation ID.
1129 if (
1130 0 < $variation_id && // Only check if there's any variation_id.
1131 (
1132 ! $product_data->is_type( 'variation' ) || // Check if isn't a variation, it suppose to be a variation at this point.
1133 $product_data->get_parent_id() !== $product_id // Check if belongs to the selected variable product.
1134 )
1135 ) {
1136 $product = wc_get_product( $product_id );
1137
1138 /* translators: 1: product link, 2: product name */
1139 throw new Exception( sprintf( __( 'The selected product isn\'t a variation of %2$s, please choose product options by visiting <a href="%1$s" title="%2$s">%2$s</a>.', 'woocommerce' ), esc_url( $product->get_permalink() ), esc_html( $product->get_name() ) ) );
1140 }
1141
1142 // Load cart item data - may be added by other plugins.
1143 $cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id, $quantity );
1144
1145 // Generate a ID based on product ID, variation ID, variation data, and other cart item data.
1146 $cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );
1147
1148 // Find the cart item key in the existing cart.
1149 $cart_item_key = $this->find_product_in_cart( $cart_id );
1150
1151 // Force quantity to 1 if sold individually and check for existing item in cart.
1152 if ( $product_data->is_sold_individually() ) {
1153 $quantity = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
1154 $found_in_cart = apply_filters( 'woocommerce_add_to_cart_sold_individually_found_in_cart', $cart_item_key && $this->cart_contents[ $cart_item_key ]['quantity'] > 0, $product_id, $variation_id, $cart_item_data, $cart_id );
1155
1156 if ( $found_in_cart ) {
1157 /* translators: %s: product name */
1158 $message = sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_name() );
1159
1160 /**
1161 * Filters message about more than 1 product being added to cart.
1162 *
1163 * @since 4.5.0
1164 * @param string $message Message.
1165 * @param WC_Product $product_data Product data.
1166 */
1167 $message = apply_filters( 'woocommerce_cart_product_cannot_add_another_message', $message, $product_data );
1168 $wp_button_class = wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '';
1169
1170 throw new Exception( sprintf( '<a href="%s" class="button wc-forward%s">%s</a> %s', wc_get_cart_url(), esc_attr( $wp_button_class ), __( 'View cart', 'woocommerce' ), $message ) );
1171 }
1172 }
1173
1174 if ( ! $product_data->is_purchasable() ) {
1175 $message = __( 'Sorry, this product cannot be purchased.', 'woocommerce' );
1176 /**
1177 * Filters message about product unable to be purchased.
1178 *
1179 * @since 3.8.0
1180 * @param string $message Message.
1181 * @param WC_Product $product_data Product data.
1182 */
1183 $message = apply_filters( 'woocommerce_cart_product_cannot_be_purchased_message', $message, $product_data );
1184 throw new Exception( $message );
1185 }
1186
1187 // Stock check - only check if we're managing stock and backorders are not allowed.
1188 if ( ! $product_data->is_in_stock() ) {
1189 /* translators: %s: product name */
1190 $message = sprintf( __( 'You cannot add &quot;%s&quot; to the cart because the product is out of stock.', 'woocommerce' ), $product_data->get_name() );
1191
1192 /**
1193 * Filters message about product being out of stock.
1194 *
1195 * @since 4.5.0
1196 * @param string $message Message.
1197 * @param WC_Product $product_data Product data.
1198 */
1199 $message = apply_filters( 'woocommerce_cart_product_out_of_stock_message', $message, $product_data );
1200 throw new Exception( $message );
1201 }
1202
1203 if ( ! $product_data->has_enough_stock( $quantity ) ) {
1204 $stock_quantity = $product_data->get_stock_quantity();
1205
1206 /* translators: 1: product name 2: quantity in stock */
1207 $message = sprintf( __( 'You cannot add that amount of &quot;%1$s&quot; to the cart because there is not enough stock (%2$s remaining).', 'woocommerce' ), $product_data->get_name(), wc_format_stock_quantity_for_display( $stock_quantity, $product_data ) );
1208
1209 /**
1210 * Filters message about product not having enough stock.
1211 *
1212 * @since 4.5.0
1213 * @param string $message Message.
1214 * @param WC_Product $product_data Product data.
1215 * @param int $stock_quantity Quantity remaining.
1216 */
1217 $message = apply_filters( 'woocommerce_cart_product_not_enough_stock_message', $message, $product_data, $stock_quantity );
1218
1219 throw new Exception( $message );
1220 }
1221
1222 // Stock check - this time accounting for whats already in-cart.
1223 if ( $product_data->managing_stock() ) {
1224 $products_qty_in_cart = $this->get_cart_item_quantities();
1225
1226 if ( isset( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ] ) && ! $product_data->has_enough_stock( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ] + $quantity ) ) {
1227 $stock_quantity = $product_data->get_stock_quantity();
1228 $stock_quantity_in_cart = $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ];
1229 $wp_button_class = wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '';
1230
1231 $message = sprintf(
1232 '<a href="%s" class="button wc-forward%s">%s</a> %s',
1233 wc_get_cart_url(),
1234 esc_attr( $wp_button_class ),
1235 __( 'View cart', 'woocommerce' ),
1236 /* translators: 1: quantity in stock 2: current quantity */
1237 sprintf( __( 'You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_quantity, $product_data ), wc_format_stock_quantity_for_display( $stock_quantity_in_cart, $product_data ) )
1238 );
1239
1240 /**
1241 * Filters message about product not having enough stock accounting for what's already in the cart.
1242 *
1243 * @param string $message Message.
1244 * @param WC_Product $product_data Product data.
1245 * @param int $stock_quantity Quantity remaining.
1246 * @param int $stock_quantity_in_cart
1247 *
1248 * @since 5.3.0
1249 */
1250 $message = apply_filters( 'woocommerce_cart_product_not_enough_stock_already_in_cart_message', $message, $product_data, $stock_quantity, $stock_quantity_in_cart );
1251
1252 throw new Exception( $message );
1253 }
1254 }
1255
1256 // If cart_item_key is set, the item is already in the cart.
1257 if ( $cart_item_key ) {
1258 $new_quantity = $quantity + $this->cart_contents[ $cart_item_key ]['quantity'];
1259 $this->set_quantity( $cart_item_key, $new_quantity, false );
1260 } else {
1261 $cart_item_key = $cart_id;
1262
1263 // Add item after merging with $cart_item_data - hook to allow plugins to modify cart item.
1264 $this->cart_contents[ $cart_item_key ] = apply_filters(
1265 'woocommerce_add_cart_item',
1266 array_merge(
1267 $cart_item_data,
1268 array(
1269 'key' => $cart_item_key,
1270 'product_id' => $product_id,
1271 'variation_id' => $variation_id,
1272 'variation' => $variation,
1273 'quantity' => $quantity,
1274 'data' => $product_data,
1275 'data_hash' => wc_get_cart_item_data_hash( $product_data ),
1276 )
1277 ),
1278 $cart_item_key
1279 );
1280 }
1281
1282 $this->cart_contents = apply_filters( 'woocommerce_cart_contents_changed', $this->cart_contents );
1283
1284 do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );
1285
1286 return $cart_item_key;
1287
1288 } catch ( Exception $e ) {
1289 if ( $e->getMessage() ) {
1290 wc_add_notice( $e->getMessage(), 'error' );
1291 }
1292 return false;
1293 }
1294 }
1295
1296 /**
1297 * Remove a cart item.
1298 *
1299 * @since 2.3.0
1300 * @param string $cart_item_key Cart item key to remove from the cart.
1301 * @return bool
1302 */
1303 public function remove_cart_item( $cart_item_key ) {
1304 if ( isset( $this->cart_contents[ $cart_item_key ] ) ) {
1305 $this->removed_cart_contents[ $cart_item_key ] = $this->cart_contents[ $cart_item_key ];
1306
1307 unset( $this->removed_cart_contents[ $cart_item_key ]['data'] );
1308
1309 do_action( 'woocommerce_remove_cart_item', $cart_item_key, $this );
1310
1311 unset( $this->cart_contents[ $cart_item_key ] );
1312
1313 do_action( 'woocommerce_cart_item_removed', $cart_item_key, $this );
1314
1315 return true;
1316 }
1317 return false;
1318 }
1319
1320 /**
1321 * Restore a cart item.
1322 *
1323 * @param string $cart_item_key Cart item key to restore to the cart.
1324 * @return bool
1325 */
1326 public function restore_cart_item( $cart_item_key ) {
1327 if ( isset( $this->removed_cart_contents[ $cart_item_key ] ) ) {
1328 $restore_item = $this->removed_cart_contents[ $cart_item_key ];
1329 $this->cart_contents[ $cart_item_key ] = $restore_item;
1330 $this->cart_contents[ $cart_item_key ]['data'] = wc_get_product( $restore_item['variation_id'] ? $restore_item['variation_id'] : $restore_item['product_id'] );
1331
1332 do_action( 'woocommerce_restore_cart_item', $cart_item_key, $this );
1333
1334 unset( $this->removed_cart_contents[ $cart_item_key ] );
1335
1336 do_action( 'woocommerce_cart_item_restored', $cart_item_key, $this );
1337
1338 return true;
1339 }
1340 return false;
1341 }
1342
1343 /**
1344 * Set the quantity for an item in the cart using it's key.
1345 *
1346 * @param string $cart_item_key contains the id of the cart item.
1347 * @param int $quantity contains the quantity of the item.
1348 * @param bool $refresh_totals whether or not to calculate totals after setting the new qty. Can be used to defer calculations if setting quantities in bulk.
1349 * @return bool
1350 */
1351 public function set_quantity( $cart_item_key, $quantity = 1, $refresh_totals = true ) {
1352 if ( 0 === $quantity || $quantity < 0 ) {
1353 wc_do_deprecated_action( 'woocommerce_before_cart_item_quantity_zero', array( $cart_item_key, $this ), '3.7.0', 'woocommerce_remove_cart_item' );
1354 // If we're setting qty to 0 we're removing the item from the cart.
1355 return $this->remove_cart_item( $cart_item_key );
1356 }
1357
1358 // Update qty.
1359 $old_quantity = $this->cart_contents[ $cart_item_key ]['quantity'];
1360 $this->cart_contents[ $cart_item_key ]['quantity'] = $quantity;
1361
1362 do_action( 'woocommerce_after_cart_item_quantity_update', $cart_item_key, $quantity, $old_quantity, $this );
1363
1364 if ( $refresh_totals ) {
1365 $this->calculate_totals();
1366 }
1367
1368 /**
1369 * Fired after qty has been changed.
1370 *
1371 * @since 3.6.0
1372 * @param string $cart_item_key contains the id of the cart item. This may be empty if the cart item does not exist any more.
1373 * @param int $quantity contains the quantity of the item.
1374 * @param WC_Cart $this Cart class.
1375 */
1376 do_action( 'woocommerce_cart_item_set_quantity', $cart_item_key, $quantity, $this );
1377
1378 return true;
1379 }
1380
1381 /**
1382 * Get cart's owner.
1383 *
1384 * @since 3.2.0
1385 * @return WC_Customer
1386 */
1387 public function get_customer() {
1388 return WC()->customer;
1389 }
1390
1391 /**
1392 * Calculate totals for the items in the cart.
1393 *
1394 * @uses WC_Cart_Totals
1395 */
1396 public function calculate_totals() {
1397 $this->reset_totals();
1398
1399 if ( $this->is_empty() ) {
1400 $this->session->set_session();
1401 return;
1402 }
1403
1404 do_action( 'woocommerce_before_calculate_totals', $this );
1405
1406 new WC_Cart_Totals( $this );
1407
1408 do_action( 'woocommerce_after_calculate_totals', $this );
1409 }
1410
1411 /**
1412 * Looks at the totals to see if payment is actually required.
1413 *
1414 * @return bool
1415 */
1416 public function needs_payment() {
1417 return apply_filters( 'woocommerce_cart_needs_payment', 0 < $this->get_total( 'edit' ), $this );
1418 }
1419
1420 /*
1421 * Shipping related functions.
1422 */
1423
1424 /**
1425 * Uses the shipping class to calculate shipping then gets the totals when its finished.
1426 */
1427 public function calculate_shipping() {
1428 $this->shipping_methods = $this->needs_shipping() ? $this->get_chosen_shipping_methods( WC()->shipping()->calculate_shipping( $this->get_shipping_packages() ) ) : array();
1429
1430 $shipping_taxes = wp_list_pluck( $this->shipping_methods, 'taxes' );
1431 $merged_taxes = array();
1432 foreach ( $shipping_taxes as $taxes ) {
1433 foreach ( $taxes as $tax_id => $tax_amount ) {
1434 if ( ! isset( $merged_taxes[ $tax_id ] ) ) {
1435 $merged_taxes[ $tax_id ] = 0;
1436 }
1437 $merged_taxes[ $tax_id ] += $tax_amount;
1438 }
1439 }
1440
1441 $this->set_shipping_total( array_sum( wp_list_pluck( $this->shipping_methods, 'cost' ) ) );
1442 $this->set_shipping_tax( array_sum( $merged_taxes ) );
1443 $this->set_shipping_taxes( $merged_taxes );
1444
1445 return $this->shipping_methods;
1446 }
1447
1448 /**
1449 * Given a set of packages with rates, get the chosen ones only.
1450 *
1451 * @since 3.2.0
1452 * @param array $calculated_shipping_packages Array of packages.
1453 * @return array
1454 */
1455 protected function get_chosen_shipping_methods( $calculated_shipping_packages = array() ) {
1456 $chosen_methods = array();
1457 // Get chosen methods for each package to get our totals.
1458 foreach ( $calculated_shipping_packages as $key => $package ) {
1459 $chosen_method = wc_get_chosen_shipping_method_for_package( $key, $package );
1460 if ( $chosen_method ) {
1461 $chosen_methods[ $key ] = $package['rates'][ $chosen_method ];
1462 }
1463 }
1464 return $chosen_methods;
1465 }
1466
1467 /**
1468 * Filter items needing shipping callback.
1469 *
1470 * @since 3.0.0
1471 * @param array $item Item to check for shipping.
1472 * @return bool
1473 */
1474 protected function filter_items_needing_shipping( $item ) {
1475 $product = $item['data'];
1476 return $product && $product->needs_shipping();
1477 }
1478
1479 /**
1480 * Get only items that need shipping.
1481 *
1482 * @since 3.0.0
1483 * @return array
1484 */
1485 protected function get_items_needing_shipping() {
1486 return array_filter( $this->get_cart(), array( $this, 'filter_items_needing_shipping' ) );
1487 }
1488
1489 /**
1490 * Get packages to calculate shipping for.
1491 *
1492 * This lets us calculate costs for carts that are shipped to multiple locations.
1493 *
1494 * Shipping methods are responsible for looping through these packages.
1495 *
1496 * By default we pass the cart itself as a package - plugins can change this.
1497 * through the filter and break it up.
1498 *
1499 * @since 1.5.4
1500 * @return array of cart items
1501 */
1502 public function get_shipping_packages() {
1503 return apply_filters(
1504 'woocommerce_cart_shipping_packages',
1505 array(
1506 array(
1507 'contents' => $this->get_items_needing_shipping(),
1508 'contents_cost' => array_sum( wp_list_pluck( $this->get_items_needing_shipping(), 'line_total' ) ),
1509 'applied_coupons' => $this->get_applied_coupons(),
1510 'user' => array(
1511 'ID' => get_current_user_id(),
1512 ),
1513 'destination' => array(
1514 'country' => $this->get_customer()->get_shipping_country(),
1515 'state' => $this->get_customer()->get_shipping_state(),
1516 'postcode' => $this->get_customer()->get_shipping_postcode(),
1517 'city' => $this->get_customer()->get_shipping_city(),
1518 'address' => $this->get_customer()->get_shipping_address(),
1519 'address_1' => $this->get_customer()->get_shipping_address(), // Provide both address and address_1 for backwards compatibility.
1520 'address_2' => $this->get_customer()->get_shipping_address_2(),
1521 ),
1522 'cart_subtotal' => $this->get_displayed_subtotal(),
1523 ),
1524 )
1525 );
1526 }
1527
1528 /**
1529 * Looks through the cart to see if shipping is actually required.
1530 *
1531 * @return bool whether or not the cart needs shipping
1532 */
1533 public function needs_shipping() {
1534 if ( ! wc_shipping_enabled() || 0 === wc_get_shipping_method_count( true ) ) {
1535 return false;
1536 }
1537 $needs_shipping = false;
1538
1539 foreach ( $this->get_cart_contents() as $cart_item_key => $values ) {
1540 if ( $values['data']->needs_shipping() ) {
1541 $needs_shipping = true;
1542 break;
1543 }
1544 }
1545
1546 return apply_filters( 'woocommerce_cart_needs_shipping', $needs_shipping );
1547 }
1548
1549 /**
1550 * Should the shipping address form be shown.
1551 *
1552 * @return bool
1553 */
1554 public function needs_shipping_address() {
1555 return apply_filters( 'woocommerce_cart_needs_shipping_address', true === $this->needs_shipping() && ! wc_ship_to_billing_address_only() );
1556 }
1557
1558 /**
1559 * Sees if the customer has entered enough data to calc the shipping yet.
1560 *
1561 * @return bool
1562 */
1563 public function show_shipping() {
1564 if ( ! wc_shipping_enabled() || ! $this->get_cart_contents() ) {
1565 return false;
1566 }
1567
1568 if ( 'yes' === get_option( 'woocommerce_shipping_cost_requires_address' ) ) {
1569 $country = $this->get_customer()->get_shipping_country();
1570 if ( ! $country ) {
1571 return false;
1572 }
1573 $country_fields = WC()->countries->get_address_fields( $country, 'shipping_' );
1574 if ( isset( $country_fields['shipping_state'] ) && $country_fields['shipping_state']['required'] && ! $this->get_customer()->get_shipping_state() ) {
1575 return false;
1576 }
1577 if ( isset( $country_fields['shipping_postcode'] ) && $country_fields['shipping_postcode']['required'] && ! $this->get_customer()->get_shipping_postcode() ) {
1578 return false;
1579 }
1580 }
1581
1582 return apply_filters( 'woocommerce_cart_ready_to_calc_shipping', true );
1583 }
1584
1585 /**
1586 * Gets the shipping total (after calculation).
1587 *
1588 * @return string price or string for the shipping total
1589 */
1590 public function get_cart_shipping_total() {
1591
1592 // Default total assumes Free shipping.
1593 $total = __( 'Free!', 'woocommerce' );
1594
1595 if ( 0 < $this->get_shipping_total() ) {
1596
1597 if ( $this->display_prices_including_tax() ) {
1598 $total = wc_price( $this->shipping_total + $this->shipping_tax_total );
1599
1600 if ( $this->shipping_tax_total > 0 && ! wc_prices_include_tax() ) {
1601 $total .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
1602 }
1603 } else {
1604 $total = wc_price( $this->shipping_total );
1605
1606 if ( $this->shipping_tax_total > 0 && wc_prices_include_tax() ) {
1607 $total .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
1608 }
1609 }
1610 }
1611 return apply_filters( 'woocommerce_cart_shipping_total', $total, $this );
1612 }
1613
1614 /**
1615 * Check for user coupons (now that we have billing email). If a coupon is invalid, add an error.
1616 *
1617 * Checks two types of coupons:
1618 * 1. Where a list of customer emails are set (limits coupon usage to those defined).
1619 * 2. Where a usage_limit_per_user is set (limits coupon usage to a number based on user ID and email).
1620 *
1621 * @param array $posted Post data.
1622 */
1623 public function check_customer_coupons( $posted ) {
1624 foreach ( $this->get_applied_coupons() as $code ) {
1625 $coupon = new WC_Coupon( $code );
1626
1627 if ( $coupon->is_valid() ) {
1628
1629 // Get user and posted emails to compare.
1630 $current_user = wp_get_current_user();
1631 $billing_email = isset( $posted['billing_email'] ) ? $posted['billing_email'] : '';
1632 $check_emails = array_unique(
1633 array_filter(
1634 array_map(
1635 'strtolower',
1636 array_map(
1637 'sanitize_email',
1638 array(
1639 $billing_email,
1640 $current_user->user_email,
1641 )
1642 )
1643 )
1644 )
1645 );
1646
1647 // Limit to defined email addresses.
1648 $restrictions = $coupon->get_email_restrictions();
1649
1650 if ( is_array( $restrictions ) && 0 < count( $restrictions ) && ! $this->is_coupon_emails_allowed( $check_emails, $restrictions ) ) {
1651 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED );
1652 $this->remove_coupon( $code );
1653 }
1654
1655 $coupon_usage_limit = $coupon->get_usage_limit_per_user();
1656 if ( 0 < $coupon_usage_limit && 0 === get_current_user_id() ) {
1657 // For guest, usage per user has not been enforced yet. Enforce it now.
1658 $coupon_data_store = $coupon->get_data_store();
1659 $billing_email = strtolower( sanitize_email( $billing_email ) );
1660 if ( $coupon_data_store && $coupon_data_store->get_usage_by_email( $coupon, $billing_email ) >= $coupon_usage_limit ) {
1661 if ( $coupon_data_store->get_tentative_usages_for_user( $coupon->get_id(), array( $billing_email ) ) ) {
1662 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST );
1663 } else {
1664 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED );
1665 }
1666 }
1667 }
1668 }
1669 }
1670 }
1671
1672 /**
1673 * Checks if the given email address(es) matches the ones specified on the coupon.
1674 *
1675 * @param array $check_emails Array of customer email addresses.
1676 * @param array $restrictions Array of allowed email addresses.
1677 * @return bool
1678 */
1679 public function is_coupon_emails_allowed( $check_emails, $restrictions ) {
1680
1681 foreach ( $check_emails as $check_email ) {
1682 // With a direct match we return true.
1683 if ( in_array( $check_email, $restrictions, true ) ) {
1684 return true;
1685 }
1686
1687 // Go through the allowed emails and return true if the email matches a wildcard.
1688 foreach ( $restrictions as $restriction ) {
1689 // Convert to PHP-regex syntax.
1690 $regex = '/^' . str_replace( '*', '(.+)?', $restriction ) . '$/';
1691 preg_match( $regex, $check_email, $match );
1692 if ( ! empty( $match ) ) {
1693 return true;
1694 }
1695 }
1696 }
1697
1698 // No matches, this one isn't allowed.
1699 return false;
1700 }
1701
1702
1703 /**
1704 * Returns whether or not a discount has been applied.
1705 *
1706 * @param string $coupon_code Coupon code to check.
1707 * @return bool
1708 */
1709 public function has_discount( $coupon_code = '' ) {
1710 return $coupon_code ? in_array( wc_format_coupon_code( $coupon_code ), $this->applied_coupons, true ) : count( $this->applied_coupons ) > 0;
1711 }
1712
1713 /**
1714 * Applies a coupon code passed to the method.
1715 *
1716 * @param string $coupon_code - The code to apply.
1717 * @return bool True if the coupon is applied, false if it does not exist or cannot be applied.
1718 */
1719 public function apply_coupon( $coupon_code ) {
1720 // Coupons are globally disabled.
1721 if ( ! wc_coupons_enabled() ) {
1722 return false;
1723 }
1724
1725 // Sanitize coupon code.
1726 $coupon_code = wc_format_coupon_code( $coupon_code );
1727
1728 // Get the coupon.
1729 $the_coupon = new WC_Coupon( $coupon_code );
1730
1731 // Prevent adding coupons by post ID.
1732 if ( $the_coupon->get_code() !== $coupon_code ) {
1733 $the_coupon->set_code( $coupon_code );
1734 $the_coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_EXIST );
1735 return false;
1736 }
1737
1738 // Check it can be used with cart.
1739 if ( ! $the_coupon->is_valid() ) {
1740 wc_add_notice( $the_coupon->get_error_message(), 'error' );
1741 return false;
1742 }
1743
1744 // Check if applied.
1745 if ( $this->has_discount( $coupon_code ) ) {
1746 $the_coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED );
1747 return false;
1748 }
1749
1750 // If its individual use then remove other coupons.
1751 if ( $the_coupon->get_individual_use() ) {
1752 $coupons_to_keep = apply_filters( 'woocommerce_apply_individual_use_coupon', array(), $the_coupon, $this->applied_coupons );
1753
1754 foreach ( $this->applied_coupons as $applied_coupon ) {
1755 $keep_key = array_search( $applied_coupon, $coupons_to_keep, true );
1756 if ( false === $keep_key ) {
1757 $this->remove_coupon( $applied_coupon );
1758 } else {
1759 unset( $coupons_to_keep[ $keep_key ] );
1760 }
1761 }
1762
1763 if ( ! empty( $coupons_to_keep ) ) {
1764 $this->applied_coupons += $coupons_to_keep;
1765 }
1766 }
1767
1768 // Check to see if an individual use coupon is set.
1769 if ( $this->applied_coupons ) {
1770 foreach ( $this->applied_coupons as $code ) {
1771 $coupon = new WC_Coupon( $code );
1772
1773 if ( $coupon->get_individual_use() && false === apply_filters( 'woocommerce_apply_with_individual_use_coupon', false, $the_coupon, $coupon, $this->applied_coupons ) ) {
1774
1775 // Reject new coupon.
1776 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED_INDIV_USE_ONLY );
1777
1778 return false;
1779 }
1780 }
1781 }
1782
1783 $this->applied_coupons[] = $coupon_code;
1784
1785 // Choose free shipping.
1786 if ( $the_coupon->get_free_shipping() ) {
1787 $packages = WC()->shipping()->get_packages();
1788 $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
1789
1790 foreach ( $packages as $i => $package ) {
1791 $chosen_shipping_methods[ $i ] = 'free_shipping';
1792 }
1793
1794 WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
1795 }
1796
1797 $the_coupon->add_coupon_message( WC_Coupon::WC_COUPON_SUCCESS );
1798
1799 do_action( 'woocommerce_applied_coupon', $coupon_code );
1800
1801 return true;
1802 }
1803
1804 /**
1805 * Get array of applied coupon objects and codes.
1806 *
1807 * @param null $deprecated No longer used.
1808 * @return array of applied coupons
1809 */
1810 public function get_coupons( $deprecated = null ) {
1811 $coupons = array();
1812
1813 if ( 'order' === $deprecated ) {
1814 return $coupons;
1815 }
1816
1817 foreach ( $this->get_applied_coupons() as $code ) {
1818 $coupon = new WC_Coupon( $code );
1819 $coupons[ $code ] = $coupon;
1820 }
1821
1822 return $coupons;
1823 }
1824
1825 /**
1826 * Get the discount amount for a used coupon.
1827 *
1828 * @param string $code coupon code.
1829 * @param bool $ex_tax inc or ex tax.
1830 * @return float discount amount
1831 */
1832 public function get_coupon_discount_amount( $code, $ex_tax = true ) {
1833 $totals = $this->get_coupon_discount_totals();
1834 $discount_amount = isset( $totals[ $code ] ) ? $totals[ $code ] : 0;
1835
1836 if ( ! $ex_tax ) {
1837 $discount_amount += $this->get_coupon_discount_tax_amount( $code );
1838 }
1839
1840 return wc_cart_round_discount( $discount_amount, wc_get_price_decimals() );
1841 }
1842
1843 /**
1844 * Get the discount tax amount for a used coupon (for tax inclusive prices).
1845 *
1846 * @param string $code coupon code.
1847 * @return float discount amount
1848 */
1849 public function get_coupon_discount_tax_amount( $code ) {
1850 $totals = $this->get_coupon_discount_tax_totals();
1851 return wc_cart_round_discount( isset( $totals[ $code ] ) ? $totals[ $code ] : 0, wc_get_price_decimals() );
1852 }
1853
1854 /**
1855 * Remove coupons from the cart of a defined type. Type 1 is before tax, type 2 is after tax.
1856 *
1857 * @param null $deprecated No longer used.
1858 */
1859 public function remove_coupons( $deprecated = null ) {
1860 $this->set_coupon_discount_totals( array() );
1861 $this->set_coupon_discount_tax_totals( array() );
1862 $this->set_applied_coupons( array() );
1863 $this->session->set_session();
1864 }
1865
1866 /**
1867 * Remove a single coupon by code.
1868 *
1869 * @param string $coupon_code Code of the coupon to remove.
1870 * @return bool
1871 */
1872 public function remove_coupon( $coupon_code ) {
1873 $coupon_code = wc_format_coupon_code( $coupon_code );
1874 $position = array_search( $coupon_code, array_map( 'wc_format_coupon_code', $this->get_applied_coupons() ), true );
1875
1876 if ( false !== $position ) {
1877 unset( $this->applied_coupons[ $position ] );
1878 }
1879
1880 WC()->session->set( 'refresh_totals', true );
1881
1882 do_action( 'woocommerce_removed_coupon', $coupon_code );
1883
1884 return true;
1885 }
1886
1887 /**
1888 * Trigger an action so 3rd parties can add custom fees.
1889 *
1890 * @since 2.0.0
1891 */
1892 public function calculate_fees() {
1893 do_action( 'woocommerce_cart_calculate_fees', $this );
1894 }
1895
1896 /**
1897 * Return reference to fees API.
1898 *
1899 * @since 3.2.0
1900 * @return WC_Cart_Fees
1901 */
1902 public function fees_api() {
1903 return $this->fees_api;
1904 }
1905
1906 /**
1907 * Add additional fee to the cart.
1908 *
1909 * This method should be called on a callback attached to the
1910 * woocommerce_cart_calculate_fees action during cart/checkout. Fees do not
1911 * persist.
1912 *
1913 * @uses WC_Cart_Fees::add_fee
1914 * @param string $name Unique name for the fee. Multiple fees of the same name cannot be added.
1915 * @param float $amount Fee amount (do not enter negative amounts).
1916 * @param bool $taxable Is the fee taxable? (default: false).
1917 * @param string $tax_class The tax class for the fee if taxable. A blank string is standard tax class. (default: '').
1918 */
1919 public function add_fee( $name, $amount, $taxable = false, $tax_class = '' ) {
1920 $this->fees_api()->add_fee(
1921 array(
1922 'name' => $name,
1923 'amount' => (float) $amount,
1924 'taxable' => $taxable,
1925 'tax_class' => $tax_class,
1926 )
1927 );
1928 }
1929
1930 /**
1931 * Return all added fees from the Fees API.
1932 *
1933 * @uses WC_Cart_Fees::get_fees
1934 * @return array
1935 */
1936 public function get_fees() {
1937 $fees = $this->fees_api()->get_fees();
1938
1939 if ( property_exists( $this, 'fees' ) ) {
1940 $fees = $fees + (array) $this->fees;
1941 }
1942 return $fees;
1943 }
1944
1945 /**
1946 * Gets the total excluding taxes.
1947 *
1948 * @return string formatted price
1949 */
1950 public function get_total_ex_tax() {
1951 return apply_filters( 'woocommerce_cart_total_ex_tax', wc_price( max( 0, $this->get_total( 'edit' ) - $this->get_total_tax() ) ) );
1952 }
1953
1954 /**
1955 * Gets the cart contents total (after calculation).
1956 *
1957 * @return string formatted price
1958 */
1959 public function get_cart_total() {
1960 return apply_filters( 'woocommerce_cart_contents_total', wc_price( wc_prices_include_tax() ? $this->get_cart_contents_total() + $this->get_cart_contents_tax() : $this->get_cart_contents_total() ) );
1961 }
1962
1963 /**
1964 * Gets the sub total (after calculation).
1965 *
1966 * @param bool $compound whether to include compound taxes.
1967 * @return string formatted price
1968 */
1969 public function get_cart_subtotal( $compound = false ) {
1970 /**
1971 * If the cart has compound tax, we want to show the subtotal as cart + shipping + non-compound taxes (after discount).
1972 */
1973 if ( $compound ) {
1974 $cart_subtotal = wc_price( $this->get_cart_contents_total() + $this->get_shipping_total() + $this->get_taxes_total( false, false ) );
1975
1976 } elseif ( $this->display_prices_including_tax() ) {
1977 $cart_subtotal = wc_price( $this->get_subtotal() + $this->get_subtotal_tax() );
1978
1979 if ( $this->get_subtotal_tax() > 0 && ! wc_prices_include_tax() ) {
1980 $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
1981 }
1982 } else {
1983 $cart_subtotal = wc_price( $this->get_subtotal() );
1984
1985 if ( $this->get_subtotal_tax() > 0 && wc_prices_include_tax() ) {
1986 $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
1987 }
1988 }
1989
1990 return apply_filters( 'woocommerce_cart_subtotal', $cart_subtotal, $compound, $this );
1991 }
1992
1993 /**
1994 * Get the product row price per item.
1995 *
1996 * @param WC_Product $product Product object.
1997 * @return string formatted price
1998 */
1999 public function get_product_price( $product ) {
2000 if ( $this->display_prices_including_tax() ) {
2001 $product_price = wc_get_price_including_tax( $product );
2002 } else {
2003 $product_price = wc_get_price_excluding_tax( $product );
2004 }
2005 return apply_filters( 'woocommerce_cart_product_price', wc_price( $product_price ), $product );
2006 }
2007
2008 /**
2009 * Get the product row subtotal.
2010 *
2011 * Gets the tax etc to avoid rounding issues.
2012 *
2013 * When on the checkout (review order), this will get the subtotal based on the customer's tax rate rather than the base rate.
2014 *
2015 * @param WC_Product $product Product object.
2016 * @param int $quantity Quantity being purchased.
2017 * @return string formatted price
2018 */
2019 public function get_product_subtotal( $product, $quantity ) {
2020 $price = $product->get_price();
2021
2022 if ( $product->is_taxable() ) {
2023
2024 if ( $this->display_prices_including_tax() ) {
2025 $row_price = wc_get_price_including_tax( $product, array( 'qty' => $quantity ) );
2026 $product_subtotal = wc_price( $row_price );
2027
2028 if ( ! wc_prices_include_tax() && $this->get_subtotal_tax() > 0 ) {
2029 $product_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
2030 }
2031 } else {
2032 $row_price = wc_get_price_excluding_tax( $product, array( 'qty' => $quantity ) );
2033 $product_subtotal = wc_price( $row_price );
2034
2035 if ( wc_prices_include_tax() && $this->get_subtotal_tax() > 0 ) {
2036 $product_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
2037 }
2038 }
2039 } else {
2040 $row_price = (float) $price * (float) $quantity;
2041 $product_subtotal = wc_price( $row_price );
2042 }
2043
2044 return apply_filters( 'woocommerce_cart_product_subtotal', $product_subtotal, $product, $quantity, $this );
2045 }
2046
2047 /**
2048 * Gets the cart tax (after calculation).
2049 *
2050 * @return string formatted price
2051 */
2052 public function get_cart_tax() {
2053 $cart_total_tax = wc_round_tax_total( $this->get_cart_contents_tax() + $this->get_shipping_tax() + $this->get_fee_tax() );
2054
2055 return apply_filters( 'woocommerce_get_cart_tax', $cart_total_tax ? wc_price( $cart_total_tax ) : '' );
2056 }
2057
2058 /**
2059 * Get a tax amount.
2060 *
2061 * @param string $tax_rate_id ID of the tax rate to get taxes for.
2062 * @return float amount
2063 */
2064 public function get_tax_amount( $tax_rate_id ) {
2065 $taxes = wc_array_merge_recursive_numeric( $this->get_cart_contents_taxes(), $this->get_fee_taxes() );
2066 return isset( $taxes[ $tax_rate_id ] ) ? $taxes[ $tax_rate_id ] : 0;
2067 }
2068
2069 /**
2070 * Get a tax amount.
2071 *
2072 * @param string $tax_rate_id ID of the tax rate to get taxes for.
2073 * @return float amount
2074 */
2075 public function get_shipping_tax_amount( $tax_rate_id ) {
2076 $taxes = $this->get_shipping_taxes();
2077 return isset( $taxes[ $tax_rate_id ] ) ? $taxes[ $tax_rate_id ] : 0;
2078 }
2079
2080 /**
2081 * Get tax row amounts with or without compound taxes includes.
2082 *
2083 * @param bool $compound True if getting compound taxes.
2084 * @param bool $display True if getting total to display.
2085 * @return float price
2086 */
2087 public function get_taxes_total( $compound = true, $display = true ) {
2088 $total = 0;
2089 $taxes = $this->get_taxes();
2090 foreach ( $taxes as $key => $tax ) {
2091 if ( ! $compound && WC_Tax::is_compound( $key ) ) {
2092 continue;
2093 }
2094 $total += $tax;
2095 }
2096 if ( $display ) {
2097 $total = wc_format_decimal( $total, wc_get_price_decimals() );
2098 }
2099 return apply_filters( 'woocommerce_cart_taxes_total', $total, $compound, $display, $this );
2100 }
2101
2102 /**
2103 * Gets the total discount amount.
2104 *
2105 * @return mixed formatted price or false if there are none
2106 */
2107 public function get_total_discount() {
2108 return apply_filters( 'woocommerce_cart_total_discount', $this->get_discount_total() ? wc_price( $this->get_discount_total() ) : false, $this );
2109 }
2110
2111 /**
2112 * Reset cart totals to the defaults. Useful before running calculations.
2113 */
2114 private function reset_totals() {
2115 $this->totals = $this->default_totals;
2116 $this->fees_api->remove_all_fees();
2117 do_action( 'woocommerce_cart_reset', $this, false );
2118 }
2119
2120 /**
2121 * Returns 'incl' if tax should be included in cart, otherwise returns 'excl'.
2122 *
2123 * @return string
2124 */
2125 public function get_tax_price_display_mode() {
2126 if ( $this->get_customer() && $this->get_customer()->get_is_vat_exempt() ) {
2127 return 'excl';
2128 }
2129
2130 return get_option( 'woocommerce_tax_display_cart' );
2131 }
2132
2133 /**
2134 * Returns the hash based on cart contents.
2135 *
2136 * @since 3.6.0
2137 * @return string hash for cart content
2138 */
2139 public function get_cart_hash() {
2140 $cart_session = $this->session->get_cart_for_session();
2141 $hash = $cart_session ? md5( wp_json_encode( $cart_session ) . $this->get_total( 'edit' ) ) : '';
2142 $hash = apply_filters_deprecated( 'woocommerce_add_to_cart_hash', array( $hash, $cart_session ), '3.6.0', 'woocommerce_cart_hash' );
2143
2144 return apply_filters( 'woocommerce_cart_hash', $hash, $cart_session );
2145 }
2146 }
2147