Aucune description

class-wc-cart.php 65KB

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