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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 4 years ago admin 4 years ago blocks 5 years ago cli 4 years ago customizer 4 years ago data-stores 4 years ago emails 4 years ago export 4 years ago gateways 4 years ago import 4 years ago integrations 5 years ago interfaces 4 years ago legacy 5 years ago libraries 6 years ago log-handlers 5 years ago payment-tokens 5 years ago queue 5 years ago rest-api 4 years ago shipping 5 years ago shortcodes 5 years ago theme-support 5 years ago tracks 4 years ago traits 5 years ago walkers 5 years ago wccom-site 5 years ago widgets 4 years ago class-wc-ajax.php 4 years ago class-wc-api.php 5 years ago class-wc-auth.php 5 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 4 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 5 years ago class-wc-cart-totals.php 4 years ago class-wc-cart.php 5 years ago class-wc-checkout.php 4 years ago class-wc-cli.php 4 years ago class-wc-comments.php 5 years ago class-wc-countries.php 4 years ago class-wc-coupon.php 5 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 5 years ago class-wc-customer.php 4 years ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 6 years ago class-wc-datetime.php 5 years ago class-wc-deprecated-action-hooks.php 8 years ago class-wc-deprecated-filter-hooks.php 7 years ago class-wc-discounts.php 4 years ago class-wc-download-handler.php 4 years ago class-wc-emails.php 5 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 5 years ago class-wc-frontend-scripts.php 4 years ago class-wc-geo-ip.php 5 years ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 4 years ago class-wc-https.php 5 years ago class-wc-install.php 4 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 5 years ago class-wc-meta-data.php 7 years ago class-wc-order-factory.php 5 years ago class-wc-order-item-coupon.php 5 years ago class-wc-order-item-fee.php 5 years ago class-wc-order-item-meta.php 5 years ago class-wc-order-item-product.php 5 years ago class-wc-order-item-shipping.php 5 years ago class-wc-order-item-tax.php 5 years ago class-wc-order-item.php 5 years ago class-wc-order-query.php 4 years ago class-wc-order-refund.php 5 years ago class-wc-order.php 4 years ago class-wc-payment-gateways.php 4 years ago class-wc-payment-tokens.php 5 years ago class-wc-post-data.php 4 years ago class-wc-post-types.php 4 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 4 years ago class-wc-product-attribute.php 5 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 5 years ago class-wc-product-variable.php 4 years ago class-wc-product-variation.php 4 years ago class-wc-query.php 4 years ago class-wc-rate-limiter.php 5 years ago class-wc-regenerate-images-request.php 5 years ago class-wc-regenerate-images.php 5 years ago class-wc-register-wp-admin-settings.php 4 years ago class-wc-rest-authentication.php 5 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 5 years ago class-wc-shipping-rate.php 5 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 5 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 5 years ago class-wc-tax.php 5 years ago class-wc-template-loader.php 4 years ago class-wc-tracker.php 4 years ago class-wc-validation.php 5 years ago class-wc-webhook.php 5 years ago class-woocommerce.php 3 months ago wc-account-functions.php 5 years ago wc-attribute-functions.php 5 years ago wc-cart-functions.php 5 years ago wc-conditional-functions.php 5 years ago wc-core-functions.php 4 years ago wc-coupon-functions.php 5 years ago wc-deprecated-functions.php 5 years ago wc-formatting-functions.php 4 years ago wc-notice-functions.php 5 years ago wc-order-functions.php 4 years ago wc-order-item-functions.php 5 years ago wc-page-functions.php 5 years ago wc-product-functions.php 4 years ago wc-rest-functions.php 5 years ago wc-stock-functions.php 5 years ago wc-template-functions.php 4 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 5 years ago wc-update-functions.php 4 years ago wc-user-functions.php 5 years ago wc-webhook-functions.php 5 years ago wc-widget-functions.php 5 years ago
class-wc-cart.php
2139 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
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 persistant 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 }
827 }
828 $cross_sells = array_diff( $cross_sells, $in_cart );
829 return apply_filters( 'woocommerce_cart_crosssell_ids', wp_parse_id_list( $cross_sells ), $this );
830 }
831
832 /**
833 * Gets the url to remove an item from the cart.
834 *
835 * @param string $cart_item_key contains the id of the cart item.
836 * @return string url to page
837 */
838 public function get_remove_url( $cart_item_key ) {
839 wc_deprecated_function( 'WC_Cart::get_remove_url', '3.3', 'wc_get_cart_remove_url' );
840
841 return wc_get_cart_remove_url( $cart_item_key );
842 }
843
844 /**
845 * Gets the url to re-add an item into the cart.
846 *
847 * @param string $cart_item_key Cart item key to undo.
848 * @return string url to page
849 */
850 public function get_undo_url( $cart_item_key ) {
851 wc_deprecated_function( 'WC_Cart::get_undo_url', '3.3', 'wc_get_cart_undo_url' );
852
853 return wc_get_cart_undo_url( $cart_item_key );
854 }
855
856 /**
857 * Get taxes, merged by code, formatted ready for output.
858 *
859 * @return array
860 */
861 public function get_tax_totals() {
862 $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.
863 $taxes = $this->get_taxes();
864 $tax_totals = array();
865
866 foreach ( $taxes as $key => $tax ) {
867 $code = WC_Tax::get_rate_code( $key );
868
869 if ( $code || apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) === $key ) {
870 if ( ! isset( $tax_totals[ $code ] ) ) {
871 $tax_totals[ $code ] = new stdClass();
872 $tax_totals[ $code ]->amount = 0;
873 }
874
875 $tax_totals[ $code ]->tax_rate_id = $key;
876 $tax_totals[ $code ]->is_compound = WC_Tax::is_compound( $key );
877 $tax_totals[ $code ]->label = WC_Tax::get_rate_label( $key );
878
879 if ( isset( $shipping_taxes[ $key ] ) ) {
880 $tax -= $shipping_taxes[ $key ];
881 $tax = wc_round_tax_total( $tax );
882 $tax += NumberUtil::round( $shipping_taxes[ $key ], wc_get_price_decimals() );
883 unset( $shipping_taxes[ $key ] );
884 }
885 $tax_totals[ $code ]->amount += wc_round_tax_total( $tax );
886 $tax_totals[ $code ]->formatted_amount = wc_price( $tax_totals[ $code ]->amount );
887 }
888 }
889
890 if ( apply_filters( 'woocommerce_cart_hide_zero_taxes', true ) ) {
891 $amounts = array_filter( wp_list_pluck( $tax_totals, 'amount' ) );
892 $tax_totals = array_intersect_key( $tax_totals, $amounts );
893 }
894
895 return apply_filters( 'woocommerce_cart_tax_totals', $tax_totals, $this );
896 }
897
898 /**
899 * Get all tax classes for items in the cart.
900 *
901 * @return array
902 */
903 public function get_cart_item_tax_classes() {
904 $found_tax_classes = array();
905
906 foreach ( WC()->cart->get_cart() as $item ) {
907 if ( $item['data'] && ( $item['data']->is_taxable() || $item['data']->is_shipping_taxable() ) ) {
908 $found_tax_classes[] = $item['data']->get_tax_class();
909 }
910 }
911
912 return array_unique( $found_tax_classes );
913 }
914
915 /**
916 * Get all tax classes for shipping based on the items in the cart.
917 *
918 * @return array
919 */
920 public function get_cart_item_tax_classes_for_shipping() {
921 $found_tax_classes = array();
922
923 foreach ( WC()->cart->get_cart() as $item ) {
924 if ( $item['data'] && ( $item['data']->is_shipping_taxable() ) ) {
925 $found_tax_classes[] = $item['data']->get_tax_class();
926 }
927 }
928
929 return array_unique( $found_tax_classes );
930 }
931
932 /**
933 * Determines the value that the customer spent and the subtotal
934 * displayed, used for things like coupon validation.
935 *
936 * Since the coupon lines are displayed based on the TAX DISPLAY value
937 * of cart, this is used to determine the spend.
938 *
939 * If cart totals are shown including tax, use the subtotal.
940 * If cart totals are shown excluding tax, use the subtotal ex tax
941 * (tax is shown after coupons).
942 *
943 * @since 2.6.0
944 * @return string
945 */
946 public function get_displayed_subtotal() {
947 return $this->display_prices_including_tax() ? $this->get_subtotal() + $this->get_subtotal_tax() : $this->get_subtotal();
948 }
949
950 /**
951 * Check if product is in the cart and return cart item key.
952 *
953 * Cart item key will be unique based on the item and its properties, such as variations.
954 *
955 * @param mixed $cart_id id of product to find in the cart.
956 * @return string cart item key
957 */
958 public function find_product_in_cart( $cart_id = false ) {
959 if ( false !== $cart_id ) {
960 if ( is_array( $this->cart_contents ) && isset( $this->cart_contents[ $cart_id ] ) ) {
961 return $cart_id;
962 }
963 }
964 return '';
965 }
966
967 /**
968 * Generate a unique ID for the cart item being added.
969 *
970 * @param int $product_id - id of the product the key is being generated for.
971 * @param int $variation_id of the product the key is being generated for.
972 * @param array $variation data for the cart item.
973 * @param array $cart_item_data other cart item data passed which affects this items uniqueness in the cart.
974 * @return string cart item key
975 */
976 public function generate_cart_id( $product_id, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
977 $id_parts = array( $product_id );
978
979 if ( $variation_id && 0 !== $variation_id ) {
980 $id_parts[] = $variation_id;
981 }
982
983 if ( is_array( $variation ) && ! empty( $variation ) ) {
984 $variation_key = '';
985 foreach ( $variation as $key => $value ) {
986 $variation_key .= trim( $key ) . trim( $value );
987 }
988 $id_parts[] = $variation_key;
989 }
990
991 if ( is_array( $cart_item_data ) && ! empty( $cart_item_data ) ) {
992 $cart_item_data_key = '';
993 foreach ( $cart_item_data as $key => $value ) {
994 if ( is_array( $value ) || is_object( $value ) ) {
995 $value = http_build_query( $value );
996 }
997 $cart_item_data_key .= trim( $key ) . trim( $value );
998
999 }
1000 $id_parts[] = $cart_item_data_key;
1001 }
1002
1003 return apply_filters( 'woocommerce_cart_id', md5( implode( '_', $id_parts ) ), $product_id, $variation_id, $variation, $cart_item_data );
1004 }
1005
1006 /**
1007 * Add a product to the cart.
1008 *
1009 * @throws Exception Plugins can throw an exception to prevent adding to cart.
1010 * @param int $product_id contains the id of the product to add to the cart.
1011 * @param int $quantity contains the quantity of the item to add.
1012 * @param int $variation_id ID of the variation being added to the cart.
1013 * @param array $variation attribute values.
1014 * @param array $cart_item_data extra cart item data we want to pass into the item.
1015 * @return string|bool $cart_item_key
1016 */
1017 public function add_to_cart( $product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
1018 try {
1019 $product_id = absint( $product_id );
1020 $variation_id = absint( $variation_id );
1021
1022 // Ensure we don't add a variation to the cart directly by variation ID.
1023 if ( 'product_variation' === get_post_type( $product_id ) ) {
1024 $variation_id = $product_id;
1025 $product_id = wp_get_post_parent_id( $variation_id );
1026 }
1027
1028 $product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
1029 $quantity = apply_filters( 'woocommerce_add_to_cart_quantity', $quantity, $product_id );
1030
1031 if ( $quantity <= 0 || ! $product_data || 'trash' === $product_data->get_status() ) {
1032 return false;
1033 }
1034
1035 if ( $product_data->is_type( 'variation' ) ) {
1036 $missing_attributes = array();
1037 $parent_data = wc_get_product( $product_data->get_parent_id() );
1038
1039 $variation_attributes = $product_data->get_variation_attributes();
1040 // Filter out 'any' variations, which are empty, as they need to be explicitly specified while adding to cart.
1041 $variation_attributes = array_filter( $variation_attributes );
1042
1043 // Gather posted attributes.
1044 $posted_attributes = array();
1045 foreach ( $parent_data->get_attributes() as $attribute ) {
1046 if ( ! $attribute['is_variation'] ) {
1047 continue;
1048 }
1049 $attribute_key = 'attribute_' . sanitize_title( $attribute['name'] );
1050
1051 if ( isset( $variation[ $attribute_key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1052 if ( $attribute['is_taxonomy'] ) {
1053 // Don't use wc_clean as it destroys sanitized characters.
1054 $value = sanitize_title( wp_unslash( $variation[ $attribute_key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1055 } else {
1056 $value = html_entity_decode( wc_clean( wp_unslash( $variation[ $attribute_key ] ) ), ENT_QUOTES, get_bloginfo( 'charset' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1057 }
1058
1059 // Don't include if it's empty.
1060 if ( ! empty( $value ) || '0' === $value ) {
1061 $posted_attributes[ $attribute_key ] = $value;
1062 }
1063 }
1064 }
1065
1066 // Merge variation attributes and posted attributes.
1067 $posted_and_variation_attributes = array_merge( $variation_attributes, $posted_attributes );
1068
1069 // If no variation ID is set, attempt to get a variation ID from posted attributes.
1070 if ( empty( $variation_id ) ) {
1071 $data_store = WC_Data_Store::load( 'product' );
1072 $variation_id = $data_store->find_matching_product_variation( $parent_data, $posted_attributes );
1073 }
1074
1075 // Do we have a variation ID?
1076 if ( empty( $variation_id ) ) {
1077 throw new Exception( __( 'Please choose product options&hellip;', 'woocommerce' ) );
1078 }
1079
1080 // Check the data we have is valid.
1081 $variation_data = wc_get_product_variation_attributes( $variation_id );
1082 $attributes = array();
1083
1084 foreach ( $parent_data->get_attributes() as $attribute ) {
1085 if ( ! $attribute['is_variation'] ) {
1086 continue;
1087 }
1088
1089 // Get valid value from variation data.
1090 $attribute_key = 'attribute_' . sanitize_title( $attribute['name'] );
1091 $valid_value = isset( $variation_data[ $attribute_key ] ) ? $variation_data[ $attribute_key ] : '';
1092
1093 /**
1094 * If the attribute value was posted, check if it's valid.
1095 *
1096 * If no attribute was posted, only error if the variation has an 'any' attribute which requires a value.
1097 */
1098 if ( isset( $posted_and_variation_attributes[ $attribute_key ] ) ) {
1099 $value = $posted_and_variation_attributes[ $attribute_key ];
1100
1101 // Allow if valid or show error.
1102 if ( $valid_value === $value ) {
1103 $attributes[ $attribute_key ] = $value;
1104 } elseif ( '' === $valid_value && in_array( $value, $attribute->get_slugs(), true ) ) {
1105 // If valid values are empty, this is an 'any' variation so get all possible values.
1106 $attributes[ $attribute_key ] = $value;
1107 } else {
1108 /* translators: %s: Attribute name. */
1109 throw new Exception( sprintf( __( 'Invalid value posted for %s', 'woocommerce' ), wc_attribute_label( $attribute['name'] ) ) );
1110 }
1111 } elseif ( '' === $valid_value ) {
1112 $missing_attributes[] = wc_attribute_label( $attribute['name'] );
1113 }
1114
1115 $variation = $attributes;
1116 }
1117 if ( ! empty( $missing_attributes ) ) {
1118 /* translators: %s: Attribute name. */
1119 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 ) ) );
1120 }
1121 }
1122
1123 // Validate variation ID.
1124 if (
1125 0 < $variation_id && // Only check if there's any variation_id.
1126 (
1127 ! $product_data->is_type( 'variation' ) || // Check if isn't a variation, it suppose to be a variation at this point.
1128 $product_data->get_parent_id() !== $product_id // Check if belongs to the selected variable product.
1129 )
1130 ) {
1131 $product = wc_get_product( $product_id );
1132
1133 /* translators: 1: product link, 2: product name */
1134 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() ) ) );
1135 }
1136
1137 // Load cart item data - may be added by other plugins.
1138 $cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id, $quantity );
1139
1140 // Generate a ID based on product ID, variation ID, variation data, and other cart item data.
1141 $cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );
1142
1143 // Find the cart item key in the existing cart.
1144 $cart_item_key = $this->find_product_in_cart( $cart_id );
1145
1146 // Force quantity to 1 if sold individually and check for existing item in cart.
1147 if ( $product_data->is_sold_individually() ) {
1148 $quantity = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
1149 $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 );
1150
1151 if ( $found_in_cart ) {
1152 /* translators: %s: product name */
1153 $message = sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_name() );
1154
1155 /**
1156 * Filters message about more than 1 product being added to cart.
1157 *
1158 * @since 4.5.0
1159 * @param string $message Message.
1160 * @param WC_Product $product_data Product data.
1161 */
1162 $message = apply_filters( 'woocommerce_cart_product_cannot_add_another_message', $message, $product_data );
1163
1164 throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View cart', 'woocommerce' ), $message ) );
1165 }
1166 }
1167
1168 if ( ! $product_data->is_purchasable() ) {
1169 $message = __( 'Sorry, this product cannot be purchased.', 'woocommerce' );
1170 /**
1171 * Filters message about product unable to be purchased.
1172 *
1173 * @since 3.8.0
1174 * @param string $message Message.
1175 * @param WC_Product $product_data Product data.
1176 */
1177 $message = apply_filters( 'woocommerce_cart_product_cannot_be_purchased_message', $message, $product_data );
1178 throw new Exception( $message );
1179 }
1180
1181 // Stock check - only check if we're managing stock and backorders are not allowed.
1182 if ( ! $product_data->is_in_stock() ) {
1183 /* translators: %s: product name */
1184 $message = sprintf( __( 'You cannot add &quot;%s&quot; to the cart because the product is out of stock.', 'woocommerce' ), $product_data->get_name() );
1185
1186 /**
1187 * Filters message about product being out of stock.
1188 *
1189 * @since 4.5.0
1190 * @param string $message Message.
1191 * @param WC_Product $product_data Product data.
1192 */
1193 $message = apply_filters( 'woocommerce_cart_product_out_of_stock_message', $message, $product_data );
1194 throw new Exception( $message );
1195 }
1196
1197 if ( ! $product_data->has_enough_stock( $quantity ) ) {
1198 $stock_quantity = $product_data->get_stock_quantity();
1199
1200 /* translators: 1: product name 2: quantity in stock */
1201 $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 ) );
1202
1203 /**
1204 * Filters message about product not having enough stock.
1205 *
1206 * @since 4.5.0
1207 * @param string $message Message.
1208 * @param WC_Product $product_data Product data.
1209 * @param int $stock_quantity Quantity remaining.
1210 */
1211 $message = apply_filters( 'woocommerce_cart_product_not_enough_stock_message', $message, $product_data, $stock_quantity );
1212
1213 throw new Exception( $message );
1214 }
1215
1216 // Stock check - this time accounting for whats already in-cart.
1217 if ( $product_data->managing_stock() ) {
1218 $products_qty_in_cart = $this->get_cart_item_quantities();
1219
1220 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 ) ) {
1221 $stock_quantity = $product_data->get_stock_quantity();
1222 $stock_quantity_in_cart = $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ];
1223
1224 $message = sprintf(
1225 '<a href="%s" class="button wc-forward">%s</a> %s',
1226 wc_get_cart_url(),
1227 __( 'View cart', 'woocommerce' ),
1228 /* translators: 1: quantity in stock 2: current quantity */
1229 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 ) )
1230 );
1231
1232 /**
1233 * Filters message about product not having enough stock accounting for what's already in the cart.
1234 *
1235 * @param string $message Message.
1236 * @param WC_Product $product_data Product data.
1237 * @param int $stock_quantity Quantity remaining.
1238 * @param int $stock_quantity_in_cart
1239 *
1240 * @since 5.3.0
1241 */
1242 $message = apply_filters( 'woocommerce_cart_product_not_enough_stock_already_in_cart_message', $message, $product_data, $stock_quantity, $stock_quantity_in_cart );
1243
1244 throw new Exception( $message );
1245 }
1246 }
1247
1248 // If cart_item_key is set, the item is already in the cart.
1249 if ( $cart_item_key ) {
1250 $new_quantity = $quantity + $this->cart_contents[ $cart_item_key ]['quantity'];
1251 $this->set_quantity( $cart_item_key, $new_quantity, false );
1252 } else {
1253 $cart_item_key = $cart_id;
1254
1255 // Add item after merging with $cart_item_data - hook to allow plugins to modify cart item.
1256 $this->cart_contents[ $cart_item_key ] = apply_filters(
1257 'woocommerce_add_cart_item',
1258 array_merge(
1259 $cart_item_data,
1260 array(
1261 'key' => $cart_item_key,
1262 'product_id' => $product_id,
1263 'variation_id' => $variation_id,
1264 'variation' => $variation,
1265 'quantity' => $quantity,
1266 'data' => $product_data,
1267 'data_hash' => wc_get_cart_item_data_hash( $product_data ),
1268 )
1269 ),
1270 $cart_item_key
1271 );
1272 }
1273
1274 $this->cart_contents = apply_filters( 'woocommerce_cart_contents_changed', $this->cart_contents );
1275
1276 do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );
1277
1278 return $cart_item_key;
1279
1280 } catch ( Exception $e ) {
1281 if ( $e->getMessage() ) {
1282 wc_add_notice( $e->getMessage(), 'error' );
1283 }
1284 return false;
1285 }
1286 }
1287
1288 /**
1289 * Remove a cart item.
1290 *
1291 * @since 2.3.0
1292 * @param string $cart_item_key Cart item key to remove from the cart.
1293 * @return bool
1294 */
1295 public function remove_cart_item( $cart_item_key ) {
1296 if ( isset( $this->cart_contents[ $cart_item_key ] ) ) {
1297 $this->removed_cart_contents[ $cart_item_key ] = $this->cart_contents[ $cart_item_key ];
1298
1299 unset( $this->removed_cart_contents[ $cart_item_key ]['data'] );
1300
1301 do_action( 'woocommerce_remove_cart_item', $cart_item_key, $this );
1302
1303 unset( $this->cart_contents[ $cart_item_key ] );
1304
1305 do_action( 'woocommerce_cart_item_removed', $cart_item_key, $this );
1306
1307 return true;
1308 }
1309 return false;
1310 }
1311
1312 /**
1313 * Restore a cart item.
1314 *
1315 * @param string $cart_item_key Cart item key to restore to the cart.
1316 * @return bool
1317 */
1318 public function restore_cart_item( $cart_item_key ) {
1319 if ( isset( $this->removed_cart_contents[ $cart_item_key ] ) ) {
1320 $restore_item = $this->removed_cart_contents[ $cart_item_key ];
1321 $this->cart_contents[ $cart_item_key ] = $restore_item;
1322 $this->cart_contents[ $cart_item_key ]['data'] = wc_get_product( $restore_item['variation_id'] ? $restore_item['variation_id'] : $restore_item['product_id'] );
1323
1324 do_action( 'woocommerce_restore_cart_item', $cart_item_key, $this );
1325
1326 unset( $this->removed_cart_contents[ $cart_item_key ] );
1327
1328 do_action( 'woocommerce_cart_item_restored', $cart_item_key, $this );
1329
1330 return true;
1331 }
1332 return false;
1333 }
1334
1335 /**
1336 * Set the quantity for an item in the cart using it's key.
1337 *
1338 * @param string $cart_item_key contains the id of the cart item.
1339 * @param int $quantity contains the quantity of the item.
1340 * @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.
1341 * @return bool
1342 */
1343 public function set_quantity( $cart_item_key, $quantity = 1, $refresh_totals = true ) {
1344 if ( 0 === $quantity || $quantity < 0 ) {
1345 wc_do_deprecated_action( 'woocommerce_before_cart_item_quantity_zero', array( $cart_item_key, $this ), '3.7.0', 'woocommerce_remove_cart_item' );
1346 // If we're setting qty to 0 we're removing the item from the cart.
1347 return $this->remove_cart_item( $cart_item_key );
1348 }
1349
1350 // Update qty.
1351 $old_quantity = $this->cart_contents[ $cart_item_key ]['quantity'];
1352 $this->cart_contents[ $cart_item_key ]['quantity'] = $quantity;
1353
1354 do_action( 'woocommerce_after_cart_item_quantity_update', $cart_item_key, $quantity, $old_quantity, $this );
1355
1356 if ( $refresh_totals ) {
1357 $this->calculate_totals();
1358 }
1359
1360 /**
1361 * Fired after qty has been changed.
1362 *
1363 * @since 3.6.0
1364 * @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.
1365 * @param int $quantity contains the quantity of the item.
1366 * @param WC_Cart $this Cart class.
1367 */
1368 do_action( 'woocommerce_cart_item_set_quantity', $cart_item_key, $quantity, $this );
1369
1370 return true;
1371 }
1372
1373 /**
1374 * Get cart's owner.
1375 *
1376 * @since 3.2.0
1377 * @return WC_Customer
1378 */
1379 public function get_customer() {
1380 return WC()->customer;
1381 }
1382
1383 /**
1384 * Calculate totals for the items in the cart.
1385 *
1386 * @uses WC_Cart_Totals
1387 */
1388 public function calculate_totals() {
1389 $this->reset_totals();
1390
1391 if ( $this->is_empty() ) {
1392 $this->session->set_session();
1393 return;
1394 }
1395
1396 do_action( 'woocommerce_before_calculate_totals', $this );
1397
1398 new WC_Cart_Totals( $this );
1399
1400 do_action( 'woocommerce_after_calculate_totals', $this );
1401 }
1402
1403 /**
1404 * Looks at the totals to see if payment is actually required.
1405 *
1406 * @return bool
1407 */
1408 public function needs_payment() {
1409 return apply_filters( 'woocommerce_cart_needs_payment', 0 < $this->get_total( 'edit' ), $this );
1410 }
1411
1412 /*
1413 * Shipping related functions.
1414 */
1415
1416 /**
1417 * Uses the shipping class to calculate shipping then gets the totals when its finished.
1418 */
1419 public function calculate_shipping() {
1420 $this->shipping_methods = $this->needs_shipping() ? $this->get_chosen_shipping_methods( WC()->shipping()->calculate_shipping( $this->get_shipping_packages() ) ) : array();
1421
1422 $shipping_taxes = wp_list_pluck( $this->shipping_methods, 'taxes' );
1423 $merged_taxes = array();
1424 foreach ( $shipping_taxes as $taxes ) {
1425 foreach ( $taxes as $tax_id => $tax_amount ) {
1426 if ( ! isset( $merged_taxes[ $tax_id ] ) ) {
1427 $merged_taxes[ $tax_id ] = 0;
1428 }
1429 $merged_taxes[ $tax_id ] += $tax_amount;
1430 }
1431 }
1432
1433 $this->set_shipping_total( array_sum( wp_list_pluck( $this->shipping_methods, 'cost' ) ) );
1434 $this->set_shipping_tax( array_sum( $merged_taxes ) );
1435 $this->set_shipping_taxes( $merged_taxes );
1436
1437 return $this->shipping_methods;
1438 }
1439
1440 /**
1441 * Given a set of packages with rates, get the chosen ones only.
1442 *
1443 * @since 3.2.0
1444 * @param array $calculated_shipping_packages Array of packages.
1445 * @return array
1446 */
1447 protected function get_chosen_shipping_methods( $calculated_shipping_packages = array() ) {
1448 $chosen_methods = array();
1449 // Get chosen methods for each package to get our totals.
1450 foreach ( $calculated_shipping_packages as $key => $package ) {
1451 $chosen_method = wc_get_chosen_shipping_method_for_package( $key, $package );
1452 if ( $chosen_method ) {
1453 $chosen_methods[ $key ] = $package['rates'][ $chosen_method ];
1454 }
1455 }
1456 return $chosen_methods;
1457 }
1458
1459 /**
1460 * Filter items needing shipping callback.
1461 *
1462 * @since 3.0.0
1463 * @param array $item Item to check for shipping.
1464 * @return bool
1465 */
1466 protected function filter_items_needing_shipping( $item ) {
1467 $product = $item['data'];
1468 return $product && $product->needs_shipping();
1469 }
1470
1471 /**
1472 * Get only items that need shipping.
1473 *
1474 * @since 3.0.0
1475 * @return array
1476 */
1477 protected function get_items_needing_shipping() {
1478 return array_filter( $this->get_cart(), array( $this, 'filter_items_needing_shipping' ) );
1479 }
1480
1481 /**
1482 * Get packages to calculate shipping for.
1483 *
1484 * This lets us calculate costs for carts that are shipped to multiple locations.
1485 *
1486 * Shipping methods are responsible for looping through these packages.
1487 *
1488 * By default we pass the cart itself as a package - plugins can change this.
1489 * through the filter and break it up.
1490 *
1491 * @since 1.5.4
1492 * @return array of cart items
1493 */
1494 public function get_shipping_packages() {
1495 return apply_filters(
1496 'woocommerce_cart_shipping_packages',
1497 array(
1498 array(
1499 'contents' => $this->get_items_needing_shipping(),
1500 'contents_cost' => array_sum( wp_list_pluck( $this->get_items_needing_shipping(), 'line_total' ) ),
1501 'applied_coupons' => $this->get_applied_coupons(),
1502 'user' => array(
1503 'ID' => get_current_user_id(),
1504 ),
1505 'destination' => array(
1506 'country' => $this->get_customer()->get_shipping_country(),
1507 'state' => $this->get_customer()->get_shipping_state(),
1508 'postcode' => $this->get_customer()->get_shipping_postcode(),
1509 'city' => $this->get_customer()->get_shipping_city(),
1510 'address' => $this->get_customer()->get_shipping_address(),
1511 'address_1' => $this->get_customer()->get_shipping_address(), // Provide both address and address_1 for backwards compatibility.
1512 'address_2' => $this->get_customer()->get_shipping_address_2(),
1513 ),
1514 'cart_subtotal' => $this->get_displayed_subtotal(),
1515 ),
1516 )
1517 );
1518 }
1519
1520 /**
1521 * Looks through the cart to see if shipping is actually required.
1522 *
1523 * @return bool whether or not the cart needs shipping
1524 */
1525 public function needs_shipping() {
1526 if ( ! wc_shipping_enabled() || 0 === wc_get_shipping_method_count( true ) ) {
1527 return false;
1528 }
1529 $needs_shipping = false;
1530
1531 foreach ( $this->get_cart_contents() as $cart_item_key => $values ) {
1532 if ( $values['data']->needs_shipping() ) {
1533 $needs_shipping = true;
1534 break;
1535 }
1536 }
1537
1538 return apply_filters( 'woocommerce_cart_needs_shipping', $needs_shipping );
1539 }
1540
1541 /**
1542 * Should the shipping address form be shown.
1543 *
1544 * @return bool
1545 */
1546 public function needs_shipping_address() {
1547 return apply_filters( 'woocommerce_cart_needs_shipping_address', true === $this->needs_shipping() && ! wc_ship_to_billing_address_only() );
1548 }
1549
1550 /**
1551 * Sees if the customer has entered enough data to calc the shipping yet.
1552 *
1553 * @return bool
1554 */
1555 public function show_shipping() {
1556 if ( ! wc_shipping_enabled() || ! $this->get_cart_contents() ) {
1557 return false;
1558 }
1559
1560 if ( 'yes' === get_option( 'woocommerce_shipping_cost_requires_address' ) ) {
1561 $country = $this->get_customer()->get_shipping_country();
1562 if ( ! $country ) {
1563 return false;
1564 }
1565 $country_fields = WC()->countries->get_address_fields( $country, 'shipping_' );
1566 if ( isset( $country_fields['shipping_state'] ) && $country_fields['shipping_state']['required'] && ! $this->get_customer()->get_shipping_state() ) {
1567 return false;
1568 }
1569 if ( isset( $country_fields['shipping_postcode'] ) && $country_fields['shipping_postcode']['required'] && ! $this->get_customer()->get_shipping_postcode() ) {
1570 return false;
1571 }
1572 }
1573
1574 return apply_filters( 'woocommerce_cart_ready_to_calc_shipping', true );
1575 }
1576
1577 /**
1578 * Gets the shipping total (after calculation).
1579 *
1580 * @return string price or string for the shipping total
1581 */
1582 public function get_cart_shipping_total() {
1583
1584 // Default total assumes Free shipping.
1585 $total = __( 'Free!', 'woocommerce' );
1586
1587 if ( 0 < $this->get_shipping_total() ) {
1588
1589 if ( $this->display_prices_including_tax() ) {
1590 $total = wc_price( $this->shipping_total + $this->shipping_tax_total );
1591
1592 if ( $this->shipping_tax_total > 0 && ! wc_prices_include_tax() ) {
1593 $total .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
1594 }
1595 } else {
1596 $total = wc_price( $this->shipping_total );
1597
1598 if ( $this->shipping_tax_total > 0 && wc_prices_include_tax() ) {
1599 $total .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
1600 }
1601 }
1602 }
1603 return apply_filters( 'woocommerce_cart_shipping_total', $total, $this );
1604 }
1605
1606 /**
1607 * Check for user coupons (now that we have billing email). If a coupon is invalid, add an error.
1608 *
1609 * Checks two types of coupons:
1610 * 1. Where a list of customer emails are set (limits coupon usage to those defined).
1611 * 2. Where a usage_limit_per_user is set (limits coupon usage to a number based on user ID and email).
1612 *
1613 * @param array $posted Post data.
1614 */
1615 public function check_customer_coupons( $posted ) {
1616 foreach ( $this->get_applied_coupons() as $code ) {
1617 $coupon = new WC_Coupon( $code );
1618
1619 if ( $coupon->is_valid() ) {
1620
1621 // Get user and posted emails to compare.
1622 $current_user = wp_get_current_user();
1623 $billing_email = isset( $posted['billing_email'] ) ? $posted['billing_email'] : '';
1624 $check_emails = array_unique(
1625 array_filter(
1626 array_map(
1627 'strtolower',
1628 array_map(
1629 'sanitize_email',
1630 array(
1631 $billing_email,
1632 $current_user->user_email,
1633 )
1634 )
1635 )
1636 )
1637 );
1638
1639 // Limit to defined email addresses.
1640 $restrictions = $coupon->get_email_restrictions();
1641
1642 if ( is_array( $restrictions ) && 0 < count( $restrictions ) && ! $this->is_coupon_emails_allowed( $check_emails, $restrictions ) ) {
1643 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED );
1644 $this->remove_coupon( $code );
1645 }
1646
1647 $coupon_usage_limit = $coupon->get_usage_limit_per_user();
1648 if ( 0 < $coupon_usage_limit && 0 === get_current_user_id() ) {
1649 // For guest, usage per user has not been enforced yet. Enforce it now.
1650 $coupon_data_store = $coupon->get_data_store();
1651 $billing_email = strtolower( sanitize_email( $billing_email ) );
1652 if ( $coupon_data_store && $coupon_data_store->get_usage_by_email( $coupon, $billing_email ) >= $coupon_usage_limit ) {
1653 if ( $coupon_data_store->get_tentative_usages_for_user( $coupon->get_id(), array( $billing_email ) ) ) {
1654 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST );
1655 } else {
1656 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED );
1657 }
1658 }
1659 }
1660 }
1661 }
1662 }
1663
1664 /**
1665 * Checks if the given email address(es) matches the ones specified on the coupon.
1666 *
1667 * @param array $check_emails Array of customer email addresses.
1668 * @param array $restrictions Array of allowed email addresses.
1669 * @return bool
1670 */
1671 public function is_coupon_emails_allowed( $check_emails, $restrictions ) {
1672
1673 foreach ( $check_emails as $check_email ) {
1674 // With a direct match we return true.
1675 if ( in_array( $check_email, $restrictions, true ) ) {
1676 return true;
1677 }
1678
1679 // Go through the allowed emails and return true if the email matches a wildcard.
1680 foreach ( $restrictions as $restriction ) {
1681 // Convert to PHP-regex syntax.
1682 $regex = '/^' . str_replace( '*', '(.+)?', $restriction ) . '$/';
1683 preg_match( $regex, $check_email, $match );
1684 if ( ! empty( $match ) ) {
1685 return true;
1686 }
1687 }
1688 }
1689
1690 // No matches, this one isn't allowed.
1691 return false;
1692 }
1693
1694
1695 /**
1696 * Returns whether or not a discount has been applied.
1697 *
1698 * @param string $coupon_code Coupon code to check.
1699 * @return bool
1700 */
1701 public function has_discount( $coupon_code = '' ) {
1702 return $coupon_code ? in_array( wc_format_coupon_code( $coupon_code ), $this->applied_coupons, true ) : count( $this->applied_coupons ) > 0;
1703 }
1704
1705 /**
1706 * Applies a coupon code passed to the method.
1707 *
1708 * @param string $coupon_code - The code to apply.
1709 * @return bool True if the coupon is applied, false if it does not exist or cannot be applied.
1710 */
1711 public function apply_coupon( $coupon_code ) {
1712 // Coupons are globally disabled.
1713 if ( ! wc_coupons_enabled() ) {
1714 return false;
1715 }
1716
1717 // Sanitize coupon code.
1718 $coupon_code = wc_format_coupon_code( $coupon_code );
1719
1720 // Get the coupon.
1721 $the_coupon = new WC_Coupon( $coupon_code );
1722
1723 // Prevent adding coupons by post ID.
1724 if ( $the_coupon->get_code() !== $coupon_code ) {
1725 $the_coupon->set_code( $coupon_code );
1726 $the_coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_EXIST );
1727 return false;
1728 }
1729
1730 // Check it can be used with cart.
1731 if ( ! $the_coupon->is_valid() ) {
1732 wc_add_notice( $the_coupon->get_error_message(), 'error' );
1733 return false;
1734 }
1735
1736 // Check if applied.
1737 if ( $this->has_discount( $coupon_code ) ) {
1738 $the_coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED );
1739 return false;
1740 }
1741
1742 // If its individual use then remove other coupons.
1743 if ( $the_coupon->get_individual_use() ) {
1744 $coupons_to_keep = apply_filters( 'woocommerce_apply_individual_use_coupon', array(), $the_coupon, $this->applied_coupons );
1745
1746 foreach ( $this->applied_coupons as $applied_coupon ) {
1747 $keep_key = array_search( $applied_coupon, $coupons_to_keep, true );
1748 if ( false === $keep_key ) {
1749 $this->remove_coupon( $applied_coupon );
1750 } else {
1751 unset( $coupons_to_keep[ $keep_key ] );
1752 }
1753 }
1754
1755 if ( ! empty( $coupons_to_keep ) ) {
1756 $this->applied_coupons += $coupons_to_keep;
1757 }
1758 }
1759
1760 // Check to see if an individual use coupon is set.
1761 if ( $this->applied_coupons ) {
1762 foreach ( $this->applied_coupons as $code ) {
1763 $coupon = new WC_Coupon( $code );
1764
1765 if ( $coupon->get_individual_use() && false === apply_filters( 'woocommerce_apply_with_individual_use_coupon', false, $the_coupon, $coupon, $this->applied_coupons ) ) {
1766
1767 // Reject new coupon.
1768 $coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED_INDIV_USE_ONLY );
1769
1770 return false;
1771 }
1772 }
1773 }
1774
1775 $this->applied_coupons[] = $coupon_code;
1776
1777 // Choose free shipping.
1778 if ( $the_coupon->get_free_shipping() ) {
1779 $packages = WC()->shipping()->get_packages();
1780 $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
1781
1782 foreach ( $packages as $i => $package ) {
1783 $chosen_shipping_methods[ $i ] = 'free_shipping';
1784 }
1785
1786 WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
1787 }
1788
1789 $the_coupon->add_coupon_message( WC_Coupon::WC_COUPON_SUCCESS );
1790
1791 do_action( 'woocommerce_applied_coupon', $coupon_code );
1792
1793 return true;
1794 }
1795
1796 /**
1797 * Get array of applied coupon objects and codes.
1798 *
1799 * @param null $deprecated No longer used.
1800 * @return array of applied coupons
1801 */
1802 public function get_coupons( $deprecated = null ) {
1803 $coupons = array();
1804
1805 if ( 'order' === $deprecated ) {
1806 return $coupons;
1807 }
1808
1809 foreach ( $this->get_applied_coupons() as $code ) {
1810 $coupon = new WC_Coupon( $code );
1811 $coupons[ $code ] = $coupon;
1812 }
1813
1814 return $coupons;
1815 }
1816
1817 /**
1818 * Get the discount amount for a used coupon.
1819 *
1820 * @param string $code coupon code.
1821 * @param bool $ex_tax inc or ex tax.
1822 * @return float discount amount
1823 */
1824 public function get_coupon_discount_amount( $code, $ex_tax = true ) {
1825 $totals = $this->get_coupon_discount_totals();
1826 $discount_amount = isset( $totals[ $code ] ) ? $totals[ $code ] : 0;
1827
1828 if ( ! $ex_tax ) {
1829 $discount_amount += $this->get_coupon_discount_tax_amount( $code );
1830 }
1831
1832 return wc_cart_round_discount( $discount_amount, wc_get_price_decimals() );
1833 }
1834
1835 /**
1836 * Get the discount tax amount for a used coupon (for tax inclusive prices).
1837 *
1838 * @param string $code coupon code.
1839 * @return float discount amount
1840 */
1841 public function get_coupon_discount_tax_amount( $code ) {
1842 $totals = $this->get_coupon_discount_tax_totals();
1843 return wc_cart_round_discount( isset( $totals[ $code ] ) ? $totals[ $code ] : 0, wc_get_price_decimals() );
1844 }
1845
1846 /**
1847 * Remove coupons from the cart of a defined type. Type 1 is before tax, type 2 is after tax.
1848 *
1849 * @param null $deprecated No longer used.
1850 */
1851 public function remove_coupons( $deprecated = null ) {
1852 $this->set_coupon_discount_totals( array() );
1853 $this->set_coupon_discount_tax_totals( array() );
1854 $this->set_applied_coupons( array() );
1855 $this->session->set_session();
1856 }
1857
1858 /**
1859 * Remove a single coupon by code.
1860 *
1861 * @param string $coupon_code Code of the coupon to remove.
1862 * @return bool
1863 */
1864 public function remove_coupon( $coupon_code ) {
1865 $coupon_code = wc_format_coupon_code( $coupon_code );
1866 $position = array_search( $coupon_code, array_map( 'wc_format_coupon_code', $this->get_applied_coupons() ), true );
1867
1868 if ( false !== $position ) {
1869 unset( $this->applied_coupons[ $position ] );
1870 }
1871
1872 WC()->session->set( 'refresh_totals', true );
1873
1874 do_action( 'woocommerce_removed_coupon', $coupon_code );
1875
1876 return true;
1877 }
1878
1879 /**
1880 * Trigger an action so 3rd parties can add custom fees.
1881 *
1882 * @since 2.0.0
1883 */
1884 public function calculate_fees() {
1885 do_action( 'woocommerce_cart_calculate_fees', $this );
1886 }
1887
1888 /**
1889 * Return reference to fees API.
1890 *
1891 * @since 3.2.0
1892 * @return WC_Cart_Fees
1893 */
1894 public function fees_api() {
1895 return $this->fees_api;
1896 }
1897
1898 /**
1899 * Add additional fee to the cart.
1900 *
1901 * This method should be called on a callback attached to the
1902 * woocommerce_cart_calculate_fees action during cart/checkout. Fees do not
1903 * persist.
1904 *
1905 * @uses WC_Cart_Fees::add_fee
1906 * @param string $name Unique name for the fee. Multiple fees of the same name cannot be added.
1907 * @param float $amount Fee amount (do not enter negative amounts).
1908 * @param bool $taxable Is the fee taxable? (default: false).
1909 * @param string $tax_class The tax class for the fee if taxable. A blank string is standard tax class. (default: '').
1910 */
1911 public function add_fee( $name, $amount, $taxable = false, $tax_class = '' ) {
1912 $this->fees_api()->add_fee(
1913 array(
1914 'name' => $name,
1915 'amount' => (float) $amount,
1916 'taxable' => $taxable,
1917 'tax_class' => $tax_class,
1918 )
1919 );
1920 }
1921
1922 /**
1923 * Return all added fees from the Fees API.
1924 *
1925 * @uses WC_Cart_Fees::get_fees
1926 * @return array
1927 */
1928 public function get_fees() {
1929 $fees = $this->fees_api()->get_fees();
1930
1931 if ( property_exists( $this, 'fees' ) ) {
1932 $fees = $fees + (array) $this->fees;
1933 }
1934 return $fees;
1935 }
1936
1937 /**
1938 * Gets the total excluding taxes.
1939 *
1940 * @return string formatted price
1941 */
1942 public function get_total_ex_tax() {
1943 return apply_filters( 'woocommerce_cart_total_ex_tax', wc_price( max( 0, $this->get_total( 'edit' ) - $this->get_total_tax() ) ) );
1944 }
1945
1946 /**
1947 * Gets the cart contents total (after calculation).
1948 *
1949 * @return string formatted price
1950 */
1951 public function get_cart_total() {
1952 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() ) );
1953 }
1954
1955 /**
1956 * Gets the sub total (after calculation).
1957 *
1958 * @param bool $compound whether to include compound taxes.
1959 * @return string formatted price
1960 */
1961 public function get_cart_subtotal( $compound = false ) {
1962 /**
1963 * If the cart has compound tax, we want to show the subtotal as cart + shipping + non-compound taxes (after discount).
1964 */
1965 if ( $compound ) {
1966 $cart_subtotal = wc_price( $this->get_cart_contents_total() + $this->get_shipping_total() + $this->get_taxes_total( false, false ) );
1967
1968 } elseif ( $this->display_prices_including_tax() ) {
1969 $cart_subtotal = wc_price( $this->get_subtotal() + $this->get_subtotal_tax() );
1970
1971 if ( $this->get_subtotal_tax() > 0 && ! wc_prices_include_tax() ) {
1972 $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
1973 }
1974 } else {
1975 $cart_subtotal = wc_price( $this->get_subtotal() );
1976
1977 if ( $this->get_subtotal_tax() > 0 && wc_prices_include_tax() ) {
1978 $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
1979 }
1980 }
1981
1982 return apply_filters( 'woocommerce_cart_subtotal', $cart_subtotal, $compound, $this );
1983 }
1984
1985 /**
1986 * Get the product row price per item.
1987 *
1988 * @param WC_Product $product Product object.
1989 * @return string formatted price
1990 */
1991 public function get_product_price( $product ) {
1992 if ( $this->display_prices_including_tax() ) {
1993 $product_price = wc_get_price_including_tax( $product );
1994 } else {
1995 $product_price = wc_get_price_excluding_tax( $product );
1996 }
1997 return apply_filters( 'woocommerce_cart_product_price', wc_price( $product_price ), $product );
1998 }
1999
2000 /**
2001 * Get the product row subtotal.
2002 *
2003 * Gets the tax etc to avoid rounding issues.
2004 *
2005 * When on the checkout (review order), this will get the subtotal based on the customer's tax rate rather than the base rate.
2006 *
2007 * @param WC_Product $product Product object.
2008 * @param int $quantity Quantity being purchased.
2009 * @return string formatted price
2010 */
2011 public function get_product_subtotal( $product, $quantity ) {
2012 $price = $product->get_price();
2013
2014 if ( $product->is_taxable() ) {
2015
2016 if ( $this->display_prices_including_tax() ) {
2017 $row_price = wc_get_price_including_tax( $product, array( 'qty' => $quantity ) );
2018 $product_subtotal = wc_price( $row_price );
2019
2020 if ( ! wc_prices_include_tax() && $this->get_subtotal_tax() > 0 ) {
2021 $product_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
2022 }
2023 } else {
2024 $row_price = wc_get_price_excluding_tax( $product, array( 'qty' => $quantity ) );
2025 $product_subtotal = wc_price( $row_price );
2026
2027 if ( wc_prices_include_tax() && $this->get_subtotal_tax() > 0 ) {
2028 $product_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
2029 }
2030 }
2031 } else {
2032 $row_price = $price * $quantity;
2033 $product_subtotal = wc_price( $row_price );
2034 }
2035
2036 return apply_filters( 'woocommerce_cart_product_subtotal', $product_subtotal, $product, $quantity, $this );
2037 }
2038
2039 /**
2040 * Gets the cart tax (after calculation).
2041 *
2042 * @return string formatted price
2043 */
2044 public function get_cart_tax() {
2045 $cart_total_tax = wc_round_tax_total( $this->get_cart_contents_tax() + $this->get_shipping_tax() + $this->get_fee_tax() );
2046
2047 return apply_filters( 'woocommerce_get_cart_tax', $cart_total_tax ? wc_price( $cart_total_tax ) : '' );
2048 }
2049
2050 /**
2051 * Get a tax amount.
2052 *
2053 * @param string $tax_rate_id ID of the tax rate to get taxes for.
2054 * @return float amount
2055 */
2056 public function get_tax_amount( $tax_rate_id ) {
2057 $taxes = wc_array_merge_recursive_numeric( $this->get_cart_contents_taxes(), $this->get_fee_taxes() );
2058 return isset( $taxes[ $tax_rate_id ] ) ? $taxes[ $tax_rate_id ] : 0;
2059 }
2060
2061 /**
2062 * Get a tax amount.
2063 *
2064 * @param string $tax_rate_id ID of the tax rate to get taxes for.
2065 * @return float amount
2066 */
2067 public function get_shipping_tax_amount( $tax_rate_id ) {
2068 $taxes = $this->get_shipping_taxes();
2069 return isset( $taxes[ $tax_rate_id ] ) ? $taxes[ $tax_rate_id ] : 0;
2070 }
2071
2072 /**
2073 * Get tax row amounts with or without compound taxes includes.
2074 *
2075 * @param bool $compound True if getting compound taxes.
2076 * @param bool $display True if getting total to display.
2077 * @return float price
2078 */
2079 public function get_taxes_total( $compound = true, $display = true ) {
2080 $total = 0;
2081 $taxes = $this->get_taxes();
2082 foreach ( $taxes as $key => $tax ) {
2083 if ( ! $compound && WC_Tax::is_compound( $key ) ) {
2084 continue;
2085 }
2086 $total += $tax;
2087 }
2088 if ( $display ) {
2089 $total = wc_format_decimal( $total, wc_get_price_decimals() );
2090 }
2091 return apply_filters( 'woocommerce_cart_taxes_total', $total, $compound, $display, $this );
2092 }
2093
2094 /**
2095 * Gets the total discount amount.
2096 *
2097 * @return mixed formatted price or false if there are none
2098 */
2099 public function get_total_discount() {
2100 return apply_filters( 'woocommerce_cart_total_discount', $this->get_discount_total() ? wc_price( $this->get_discount_total() ) : false, $this );
2101 }
2102
2103 /**
2104 * Reset cart totals to the defaults. Useful before running calculations.
2105 */
2106 private function reset_totals() {
2107 $this->totals = $this->default_totals;
2108 $this->fees_api->remove_all_fees();
2109 do_action( 'woocommerce_cart_reset', $this, false );
2110 }
2111
2112 /**
2113 * Returns 'incl' if tax should be included in cart, otherwise returns 'excl'.
2114 *
2115 * @return string
2116 */
2117 public function get_tax_price_display_mode() {
2118 if ( $this->get_customer() && $this->get_customer()->get_is_vat_exempt() ) {
2119 return 'excl';
2120 }
2121
2122 return get_option( 'woocommerce_tax_display_cart' );
2123 }
2124
2125 /**
2126 * Returns the hash based on cart contents.
2127 *
2128 * @since 3.6.0
2129 * @return string hash for cart content
2130 */
2131 public function get_cart_hash() {
2132 $cart_session = $this->session->get_cart_for_session();
2133 $hash = $cart_session ? md5( wp_json_encode( $cart_session ) . $this->get_total( 'edit' ) ) : '';
2134 $hash = apply_filters_deprecated( 'woocommerce_add_to_cart_hash', array( $hash, $cart_session ), '3.6.0', 'woocommerce_cart_hash' );
2135
2136 return apply_filters( 'woocommerce_cart_hash', $hash, $cart_session );
2137 }
2138 }
2139