class-wc-tax.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. exit; // Exit if accessed directly
  4. }
  5. /**
  6. * Performs tax calculations and loads tax rates
  7. *
  8. * @class WC_Tax
  9. * @version 2.2.0
  10. * @package WooCommerce/Classes
  11. * @category Class
  12. * @author WooThemes
  13. */
  14. class WC_Tax {
  15. /**
  16. * Precision.
  17. *
  18. * @var int
  19. */
  20. public static $precision;
  21. /**
  22. * Round at subtotal.
  23. *
  24. * @var bool
  25. */
  26. public static $round_at_subtotal = false;
  27. /**
  28. * Load options.
  29. *
  30. * @access public
  31. */
  32. public static function init() {
  33. self::$precision = wc_get_rounding_precision();
  34. self::$round_at_subtotal = 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' );
  35. add_action( 'update_option_woocommerce_tax_classes', array( __CLASS__, 'maybe_remove_tax_class_rates' ), 10, 2 );
  36. }
  37. /**
  38. * When the woocommerce_tax_classes option is changed, remove any orphan rates.
  39. * @param string $old_value
  40. * @param string $value
  41. */
  42. public static function maybe_remove_tax_class_rates( $old_value, $value ) {
  43. $old = array_filter( array_map( 'trim', explode( "\n", $old_value ) ) );
  44. $new = array_filter( array_map( 'trim', explode( "\n", $value ) ) );
  45. $removed = array_filter( array_map( 'sanitize_title', array_diff( $old, $new ) ) );
  46. if ( $removed ) {
  47. global $wpdb;
  48. foreach ( $removed as $removed_tax_class ) {
  49. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_class = %s;", $removed_tax_class ) );
  50. $wpdb->query( "DELETE locations FROM {$wpdb->prefix}woocommerce_tax_rate_locations locations LEFT JOIN {$wpdb->prefix}woocommerce_tax_rates rates ON rates.tax_rate_id = locations.tax_rate_id WHERE rates.tax_rate_id IS NULL;" );
  51. }
  52. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  53. }
  54. }
  55. /**
  56. * Calculate tax for a line.
  57. *
  58. * @param float $price Price to calc tax on.
  59. * @param array $rates Rates to apply.
  60. * @param boolean $price_includes_tax Whether the passed price has taxes included.
  61. * @param boolean $deprecated Whether to suppress any rounding from taking place. No longer used here.
  62. * @return array Array of rates + prices after tax.
  63. */
  64. public static function calc_tax( $price, $rates, $price_includes_tax = false, $deprecated = false ) {
  65. if ( $price_includes_tax ) {
  66. $taxes = self::calc_inclusive_tax( $price, $rates );
  67. } else {
  68. $taxes = self::calc_exclusive_tax( $price, $rates );
  69. }
  70. return apply_filters( 'woocommerce_calc_tax', $taxes, $price, $rates, $price_includes_tax, $deprecated );
  71. }
  72. /**
  73. * Calculate the shipping tax using a passed array of rates.
  74. *
  75. * @param float Price
  76. * @param array Taxation Rate
  77. * @return array
  78. */
  79. public static function calc_shipping_tax( $price, $rates ) {
  80. $taxes = self::calc_exclusive_tax( $price, $rates );
  81. return apply_filters( 'woocommerce_calc_shipping_tax', $taxes, $price, $rates );
  82. }
  83. /**
  84. * Round to precision.
  85. *
  86. * Filter example: to return rounding to .5 cents you'd use:
  87. *
  88. * function euro_5cent_rounding( $in ) {
  89. * return round( $in / 5, 2 ) * 5;
  90. * }
  91. * add_filter( 'woocommerce_tax_round', 'euro_5cent_rounding' );
  92. *
  93. * @param float|int $in
  94. *
  95. * @return float
  96. */
  97. public static function round( $in ) {
  98. return apply_filters( 'woocommerce_tax_round', round( $in, wc_get_rounding_precision() ), $in );
  99. }
  100. /**
  101. * Calc tax from inclusive price.
  102. *
  103. * @param float $price Price to calculate tax for.
  104. * @param array $rates Array of tax rates.
  105. * @return array
  106. */
  107. public static function calc_inclusive_tax( $price, $rates ) {
  108. $taxes = array();
  109. $compound_rates = array();
  110. $regular_rates = array();
  111. // Index array so taxes are output in correct order and see what compound/regular rates we have to calculate.
  112. foreach ( $rates as $key => $rate ) {
  113. $taxes[ $key ] = 0;
  114. if ( 'yes' === $rate['compound'] ) {
  115. $compound_rates[ $key ] = $rate['rate'];
  116. } else {
  117. $regular_rates[ $key ] = $rate['rate'];
  118. }
  119. }
  120. $compound_rates = array_reverse( $compound_rates, true ); // Working backwards.
  121. $non_compound_price = $price;
  122. foreach ( $compound_rates as $key => $compound_rate ) {
  123. $tax_amount = apply_filters( 'woocommerce_price_inc_tax_amount', $non_compound_price - ( $non_compound_price / ( 1 + ( $compound_rate / 100 ) ) ), $key, $rates[ $key ], $price );
  124. $taxes[ $key ] += $tax_amount;
  125. $non_compound_price = $non_compound_price - $tax_amount;
  126. }
  127. // Regular taxes.
  128. $regular_tax_rate = 1 + ( array_sum( $regular_rates ) / 100 );
  129. foreach ( $regular_rates as $key => $regular_rate ) {
  130. $the_rate = ( $regular_rate / 100 ) / $regular_tax_rate;
  131. $net_price = $price - ( $the_rate * $non_compound_price );
  132. $tax_amount = apply_filters( 'woocommerce_price_inc_tax_amount', $price - $net_price, $key, $rates[ $key ], $price );
  133. $taxes[ $key ] += $tax_amount;
  134. }
  135. return $taxes;
  136. }
  137. /**
  138. * Calc tax from exclusive price.
  139. *
  140. * @param float $price Price to calculate tax for.
  141. * @param array $rates Array of tax rates.
  142. * @return array
  143. */
  144. public static function calc_exclusive_tax( $price, $rates ) {
  145. $taxes = array();
  146. if ( ! empty( $rates ) ) {
  147. foreach ( $rates as $key => $rate ) {
  148. if ( 'yes' === $rate['compound'] ) {
  149. continue;
  150. }
  151. $tax_amount = $price * ( $rate['rate'] / 100 );
  152. $tax_amount = apply_filters( 'woocommerce_price_ex_tax_amount', $tax_amount, $key, $rate, $price ); // ADVANCED: Allow third parties to modify this rate.
  153. if ( ! isset( $taxes[ $key ] ) ) {
  154. $taxes[ $key ] = $tax_amount;
  155. } else {
  156. $taxes[ $key ] += $tax_amount;
  157. }
  158. }
  159. $pre_compound_total = array_sum( $taxes );
  160. // Compound taxes.
  161. foreach ( $rates as $key => $rate ) {
  162. if ( 'no' === $rate['compound'] ) {
  163. continue;
  164. }
  165. $the_price_inc_tax = $price + ( $pre_compound_total );
  166. $tax_amount = $the_price_inc_tax * ( $rate['rate'] / 100 );
  167. $tax_amount = apply_filters( 'woocommerce_price_ex_tax_amount', $tax_amount, $key, $rate, $price, $the_price_inc_tax, $pre_compound_total ); // ADVANCED: Allow third parties to modify this rate.
  168. if ( ! isset( $taxes[ $key ] ) ) {
  169. $taxes[ $key ] = $tax_amount;
  170. } else {
  171. $taxes[ $key ] += $tax_amount;
  172. }
  173. $pre_compound_total = array_sum( $taxes );
  174. }
  175. }
  176. return $taxes;
  177. }
  178. /**
  179. * Searches for all matching country/state/postcode tax rates.
  180. *
  181. * @param array $args
  182. * @return array
  183. */
  184. public static function find_rates( $args = array() ) {
  185. $args = wp_parse_args( $args, array(
  186. 'country' => '',
  187. 'state' => '',
  188. 'city' => '',
  189. 'postcode' => '',
  190. 'tax_class' => '',
  191. ) );
  192. extract( $args, EXTR_SKIP );
  193. if ( ! $country ) {
  194. return array();
  195. }
  196. $postcode = wc_normalize_postcode( wc_clean( $postcode ) );
  197. $cache_key = WC_Cache_Helper::get_cache_prefix( 'taxes' ) . 'wc_tax_rates_' . md5( sprintf( '%s+%s+%s+%s+%s', $country, $state, $city, $postcode, $tax_class ) );
  198. $matched_tax_rates = wp_cache_get( $cache_key, 'taxes' );
  199. if ( false === $matched_tax_rates ) {
  200. $matched_tax_rates = self::get_matched_tax_rates( $country, $state, $postcode, $city, $tax_class );
  201. wp_cache_set( $cache_key, $matched_tax_rates, 'taxes' );
  202. }
  203. return apply_filters( 'woocommerce_find_rates', $matched_tax_rates, $args );
  204. }
  205. /**
  206. * Searches for all matching country/state/postcode tax rates.
  207. *
  208. * @param array $args
  209. * @return array
  210. */
  211. public static function find_shipping_rates( $args = array() ) {
  212. $rates = self::find_rates( $args );
  213. $shipping_rates = array();
  214. if ( is_array( $rates ) ) {
  215. foreach ( $rates as $key => $rate ) {
  216. if ( 'yes' === $rate['shipping'] ) {
  217. $shipping_rates[ $key ] = $rate;
  218. }
  219. }
  220. }
  221. return $shipping_rates;
  222. }
  223. /**
  224. * Does the sort comparison. Compares (in this order):
  225. * - Priority
  226. * - Country
  227. * - State
  228. * - Number of postcodes
  229. * - Number of cities
  230. * - ID
  231. *
  232. * @param object $rate1 First rate to compare.
  233. * @param object $rate2 Second rate to compare.
  234. * @return int
  235. */
  236. private static function sort_rates_callback( $rate1, $rate2 ) {
  237. if ( $rate1->tax_rate_priority !== $rate2->tax_rate_priority ) {
  238. return $rate1->tax_rate_priority < $rate2->tax_rate_priority ? -1 : 1; // ASC
  239. }
  240. if ( $rate1->tax_rate_country !== $rate2->tax_rate_country ) {
  241. if ( '' === $rate1->tax_rate_country ) {
  242. return 1;
  243. }
  244. if ( '' === $rate2->tax_rate_country ) {
  245. return -1;
  246. }
  247. return strcmp( $rate1->tax_rate_country, $rate2->tax_rate_country ) > 0 ? 1 : -1;
  248. }
  249. if ( $rate1->tax_rate_state !== $rate2->tax_rate_state ) {
  250. if ( '' === $rate1->tax_rate_state ) {
  251. return 1;
  252. }
  253. if ( '' === $rate2->tax_rate_state ) {
  254. return -1;
  255. }
  256. return strcmp( $rate1->tax_rate_state, $rate2->tax_rate_state ) > 0 ? 1 : -1;
  257. }
  258. if ( isset( $rate1->postcode_count, $rate2->postcode_count ) && $rate1->postcode_count !== $rate2->postcode_count ) {
  259. return $rate1->postcode_count < $rate2->postcode_count ? 1 : -1;
  260. }
  261. if ( isset( $rate1->city_count, $rate2->city_count ) && $rate1->city_count !== $rate2->city_count ) {
  262. return $rate1->city_count < $rate2->city_count ? 1 : -1;
  263. }
  264. return $rate1->tax_rate_id < $rate2->tax_rate_id ? -1 : 1;
  265. }
  266. /**
  267. * Logical sort order for tax rates based on the following in order of priority.
  268. *
  269. * @param array $rates Rates to be sorted.
  270. * @return array
  271. */
  272. private static function sort_rates( $rates ) {
  273. uasort( $rates, __CLASS__ . '::sort_rates_callback' );
  274. $i = 0;
  275. foreach ( $rates as $key => $rate ) {
  276. $rates[ $key ]->tax_rate_order = $i++;
  277. }
  278. return $rates;
  279. }
  280. /**
  281. * Loop through a set of tax rates and get the matching rates (1 per priority).
  282. *
  283. * @param string $country Country code to match against.
  284. * @param string $state State code to match against.
  285. * @param string $postcode Postcode to match against.
  286. * @param string $city City to match against.
  287. * @param string $tax_class Tax class to match against.
  288. * @return array
  289. */
  290. private static function get_matched_tax_rates( $country, $state, $postcode, $city, $tax_class ) {
  291. global $wpdb;
  292. // Query criteria - these will be ANDed.
  293. $criteria = array();
  294. $criteria[] = $wpdb->prepare( "tax_rate_country IN ( %s, '' )", strtoupper( $country ) );
  295. $criteria[] = $wpdb->prepare( "tax_rate_state IN ( %s, '' )", strtoupper( $state ) );
  296. $criteria[] = $wpdb->prepare( 'tax_rate_class = %s', sanitize_title( $tax_class ) );
  297. // Pre-query postcode ranges for PHP based matching.
  298. $postcode_search = wc_get_wildcard_postcodes( $postcode, $country );
  299. $postcode_ranges = $wpdb->get_results( "SELECT tax_rate_id, location_code FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE location_type = 'postcode' AND location_code LIKE '%...%';" );
  300. if ( $postcode_ranges ) {
  301. $matches = wc_postcode_location_matcher( $postcode, $postcode_ranges, 'tax_rate_id', 'location_code', $country );
  302. if ( ! empty( $matches ) ) {
  303. foreach ( $matches as $matched_postcodes ) {
  304. $postcode_search = array_merge( $postcode_search, $matched_postcodes );
  305. }
  306. }
  307. }
  308. $postcode_search = array_unique( $postcode_search );
  309. /**
  310. * Location matching criteria - ORed
  311. * Needs to match:
  312. * - rates with no postcodes and cities
  313. * - rates with a matching postcode and city
  314. * - rates with matching postcode, no city
  315. * - rates with matching city, no postcode
  316. */
  317. $locations_criteria = array();
  318. $locations_criteria[] = 'locations.location_type IS NULL';
  319. $locations_criteria[] = "
  320. locations.location_type = 'postcode' AND locations.location_code IN ('" . implode( "','", array_map( 'esc_sql', $postcode_search ) ) . "')
  321. AND (
  322. ( locations2.location_type = 'city' AND locations2.location_code = '" . esc_sql( strtoupper( $city ) ) . "' )
  323. OR NOT EXISTS (
  324. SELECT sub.tax_rate_id FROM {$wpdb->prefix}woocommerce_tax_rate_locations as sub
  325. WHERE sub.location_type = 'city'
  326. AND sub.tax_rate_id = tax_rates.tax_rate_id
  327. )
  328. )
  329. ";
  330. $locations_criteria[] = "
  331. locations.location_type = 'city' AND locations.location_code = '" . esc_sql( strtoupper( $city ) ) . "'
  332. AND NOT EXISTS (
  333. SELECT sub.tax_rate_id FROM {$wpdb->prefix}woocommerce_tax_rate_locations as sub
  334. WHERE sub.location_type = 'postcode'
  335. AND sub.tax_rate_id = tax_rates.tax_rate_id
  336. )
  337. ";
  338. $criteria[] = '( ( ' . implode( ' ) OR ( ', $locations_criteria ) . ' ) )';
  339. $found_rates = $wpdb->get_results( "
  340. SELECT tax_rates.*, COUNT( locations.location_id ) as postcode_count, COUNT( locations2.location_id ) as city_count
  341. FROM {$wpdb->prefix}woocommerce_tax_rates as tax_rates
  342. LEFT OUTER JOIN {$wpdb->prefix}woocommerce_tax_rate_locations as locations ON tax_rates.tax_rate_id = locations.tax_rate_id
  343. LEFT OUTER JOIN {$wpdb->prefix}woocommerce_tax_rate_locations as locations2 ON tax_rates.tax_rate_id = locations2.tax_rate_id
  344. WHERE 1=1 AND " . implode( ' AND ', $criteria ) . "
  345. GROUP BY tax_rates.tax_rate_id
  346. ORDER BY tax_rates.tax_rate_priority
  347. " );
  348. $found_rates = self::sort_rates( $found_rates );
  349. $matched_tax_rates = array();
  350. $found_priority = array();
  351. foreach ( $found_rates as $found_rate ) {
  352. if ( in_array( $found_rate->tax_rate_priority, $found_priority, true ) ) {
  353. continue;
  354. }
  355. $matched_tax_rates[ $found_rate->tax_rate_id ] = array(
  356. 'rate' => $found_rate->tax_rate,
  357. 'label' => $found_rate->tax_rate_name,
  358. 'shipping' => $found_rate->tax_rate_shipping ? 'yes' : 'no',
  359. 'compound' => $found_rate->tax_rate_compound ? 'yes' : 'no',
  360. );
  361. $found_priority[] = $found_rate->tax_rate_priority;
  362. }
  363. return apply_filters( 'woocommerce_matched_tax_rates', $matched_tax_rates, $country, $state, $postcode, $city, $tax_class );
  364. }
  365. /**
  366. * Get the customer tax location based on their status and the current page.
  367. *
  368. * Used by get_rates(), get_shipping_rates().
  369. *
  370. * @param $tax_class string Optional, passed to the filter for advanced tax setups.
  371. * @param object $customer Override the customer object to get their location.
  372. * @return array
  373. */
  374. public static function get_tax_location( $tax_class = '', $customer = null ) {
  375. $location = array();
  376. if ( is_null( $customer ) && ! empty( WC()->customer ) ) {
  377. $customer = WC()->customer;
  378. }
  379. if ( ! empty( $customer ) ) {
  380. $location = $customer->get_taxable_address();
  381. } elseif ( wc_prices_include_tax() || 'base' === get_option( 'woocommerce_default_customer_address' ) || 'base' === get_option( 'woocommerce_tax_based_on' ) ) {
  382. $location = array(
  383. WC()->countries->get_base_country(),
  384. WC()->countries->get_base_state(),
  385. WC()->countries->get_base_postcode(),
  386. WC()->countries->get_base_city(),
  387. );
  388. }
  389. return apply_filters( 'woocommerce_get_tax_location', $location, $tax_class, $customer );
  390. }
  391. /**
  392. * Get's an array of matching rates for a tax class.
  393. *
  394. * @param string $tax_class Tax class to get rates for.
  395. * @param object $customer Override the customer object to get their location.
  396. * @return array
  397. */
  398. public static function get_rates( $tax_class = '', $customer = null ) {
  399. $tax_class = sanitize_title( $tax_class );
  400. $location = self::get_tax_location( $tax_class, $customer );
  401. $matched_tax_rates = array();
  402. if ( sizeof( $location ) === 4 ) {
  403. list( $country, $state, $postcode, $city ) = $location;
  404. $matched_tax_rates = self::find_rates( array(
  405. 'country' => $country,
  406. 'state' => $state,
  407. 'postcode' => $postcode,
  408. 'city' => $city,
  409. 'tax_class' => $tax_class,
  410. ) );
  411. }
  412. return apply_filters( 'woocommerce_matched_rates', $matched_tax_rates, $tax_class );
  413. }
  414. /**
  415. * Get's an array of matching rates for the shop's base country.
  416. *
  417. * @param string Tax Class
  418. * @return array
  419. */
  420. public static function get_base_tax_rates( $tax_class = '' ) {
  421. return apply_filters( 'woocommerce_base_tax_rates', self::find_rates( array(
  422. 'country' => WC()->countries->get_base_country(),
  423. 'state' => WC()->countries->get_base_state(),
  424. 'postcode' => WC()->countries->get_base_postcode(),
  425. 'city' => WC()->countries->get_base_city(),
  426. 'tax_class' => $tax_class,
  427. ) ), $tax_class );
  428. }
  429. /**
  430. * Alias for get_base_tax_rates().
  431. *
  432. * @deprecated 2.3
  433. * @param string Tax Class
  434. * @return array
  435. */
  436. public static function get_shop_base_rate( $tax_class = '' ) {
  437. return self::get_base_tax_rates( $tax_class );
  438. }
  439. /**
  440. * Gets an array of matching shipping tax rates for a given class.
  441. *
  442. * @param string $tax_class Tax class to get rates for.
  443. * @param object $customer Override the customer object to get their location.
  444. * @return mixed
  445. */
  446. public static function get_shipping_tax_rates( $tax_class = null, $customer = null ) {
  447. // See if we have an explicitly set shipping tax class
  448. $shipping_tax_class = get_option( 'woocommerce_shipping_tax_class' );
  449. if ( 'inherit' !== $shipping_tax_class ) {
  450. $tax_class = $shipping_tax_class;
  451. }
  452. $location = self::get_tax_location( $tax_class, $customer );
  453. $matched_tax_rates = array();
  454. if ( sizeof( $location ) === 4 ) {
  455. list( $country, $state, $postcode, $city ) = $location;
  456. if ( ! is_null( $tax_class ) ) {
  457. // This will be per item shipping
  458. $matched_tax_rates = self::find_shipping_rates( array(
  459. 'country' => $country,
  460. 'state' => $state,
  461. 'postcode' => $postcode,
  462. 'city' => $city,
  463. 'tax_class' => $tax_class,
  464. ) );
  465. } elseif ( WC()->cart->get_cart() ) {
  466. // This will be per order shipping - loop through the order and find the highest tax class rate
  467. $cart_tax_classes = WC()->cart->get_cart_item_tax_classes_for_shipping();
  468. // No tax classes = no taxable items.
  469. if ( empty( $cart_tax_classes ) ) {
  470. return array();
  471. }
  472. // If multiple classes are found, use the first one found unless a standard rate item is found. This will be the first listed in the 'additional tax class' section.
  473. if ( sizeof( $cart_tax_classes ) > 1 && ! in_array( '', $cart_tax_classes ) ) {
  474. $tax_classes = self::get_tax_class_slugs();
  475. foreach ( $tax_classes as $tax_class ) {
  476. if ( in_array( $tax_class, $cart_tax_classes ) ) {
  477. $matched_tax_rates = self::find_shipping_rates( array(
  478. 'country' => $country,
  479. 'state' => $state,
  480. 'postcode' => $postcode,
  481. 'city' => $city,
  482. 'tax_class' => $tax_class,
  483. ) );
  484. break;
  485. }
  486. }
  487. // If a single tax class is found, use it
  488. } elseif ( sizeof( $cart_tax_classes ) == 1 ) {
  489. $matched_tax_rates = self::find_shipping_rates( array(
  490. 'country' => $country,
  491. 'state' => $state,
  492. 'postcode' => $postcode,
  493. 'city' => $city,
  494. 'tax_class' => $cart_tax_classes[0],
  495. ) );
  496. }
  497. }
  498. // Get standard rate if no taxes were found
  499. if ( ! sizeof( $matched_tax_rates ) ) {
  500. $matched_tax_rates = self::find_shipping_rates( array(
  501. 'country' => $country,
  502. 'state' => $state,
  503. 'postcode' => $postcode,
  504. 'city' => $city,
  505. ) );
  506. }
  507. }
  508. return $matched_tax_rates;
  509. }
  510. /**
  511. * Return true/false depending on if a rate is a compound rate.
  512. *
  513. * @param mixed $key_or_rate Tax rate ID, or the db row itself in object format
  514. * @return bool
  515. */
  516. public static function is_compound( $key_or_rate ) {
  517. global $wpdb;
  518. if ( is_object( $key_or_rate ) ) {
  519. $key = $key_or_rate->tax_rate_id;
  520. $compound = $key_or_rate->tax_rate_compound;
  521. } else {
  522. $key = $key_or_rate;
  523. $compound = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_compound FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $key ) );
  524. }
  525. return (bool) apply_filters( 'woocommerce_rate_compound', $compound, $key );
  526. }
  527. /**
  528. * Return a given rates label.
  529. *
  530. * @param mixed $key_or_rate Tax rate ID, or the db row itself in object format
  531. * @return string
  532. */
  533. public static function get_rate_label( $key_or_rate ) {
  534. global $wpdb;
  535. if ( is_object( $key_or_rate ) ) {
  536. $key = $key_or_rate->tax_rate_id;
  537. $rate_name = $key_or_rate->tax_rate_name;
  538. } else {
  539. $key = $key_or_rate;
  540. $rate_name = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_name FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $key ) );
  541. }
  542. if ( ! $rate_name ) {
  543. $rate_name = WC()->countries->tax_or_vat();
  544. }
  545. return apply_filters( 'woocommerce_rate_label', $rate_name, $key );
  546. }
  547. /**
  548. * Return a given rates percent.
  549. *
  550. * @param mixed $key_or_rate Tax rate ID, or the db row itself in object format
  551. * @return string
  552. */
  553. public static function get_rate_percent( $key_or_rate ) {
  554. global $wpdb;
  555. if ( is_object( $key_or_rate ) ) {
  556. $key = $key_or_rate->tax_rate_id;
  557. $tax_rate = $key_or_rate->tax_rate;
  558. } else {
  559. $key = $key_or_rate;
  560. $tax_rate = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $key ) );
  561. }
  562. return apply_filters( 'woocommerce_rate_percent', floatval( $tax_rate ) . '%', $key );
  563. }
  564. /**
  565. * Get a rates code. Code is made up of COUNTRY-STATE-NAME-Priority. E.g GB-VAT-1, US-AL-TAX-1.
  566. *
  567. * @access public
  568. * @param mixed $key_or_rate Tax rate ID, or the db row itself in object format
  569. * @return string
  570. */
  571. public static function get_rate_code( $key_or_rate ) {
  572. global $wpdb;
  573. if ( is_object( $key_or_rate ) ) {
  574. $key = $key_or_rate->tax_rate_id;
  575. $rate = $key_or_rate;
  576. } else {
  577. $key = $key_or_rate;
  578. $rate = $wpdb->get_row( $wpdb->prepare( "SELECT tax_rate_country, tax_rate_state, tax_rate_name, tax_rate_priority FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $key ) );
  579. }
  580. $code_string = '';
  581. if ( null !== $rate ) {
  582. $code = array();
  583. $code[] = $rate->tax_rate_country;
  584. $code[] = $rate->tax_rate_state;
  585. $code[] = $rate->tax_rate_name ? $rate->tax_rate_name : 'TAX';
  586. $code[] = absint( $rate->tax_rate_priority );
  587. $code_string = strtoupper( implode( '-', array_filter( $code ) ) );
  588. }
  589. return apply_filters( 'woocommerce_rate_code', $code_string, $key );
  590. }
  591. /**
  592. * Round tax lines and return the sum.
  593. *
  594. * @param array
  595. * @return float
  596. */
  597. public static function get_tax_total( $taxes ) {
  598. return array_sum( array_map( array( __CLASS__, 'round' ), $taxes ) );
  599. }
  600. /**
  601. * Get store tax classes.
  602. *
  603. * @return array Array of class names ("Reduced rate", "Zero rate", etc).
  604. */
  605. public static function get_tax_classes() {
  606. return array_filter( array_map( 'trim', explode( "\n", get_option( 'woocommerce_tax_classes' ) ) ), array( __CLASS__, 'is_valid_tax_class' ) );
  607. }
  608. /**
  609. * Filter out invalid tax classes.
  610. *
  611. * @param string $tax_class Tax class name.
  612. * @return boolean
  613. */
  614. private static function is_valid_tax_class( $tax_class ) {
  615. return ! empty( $tax_class ) && sanitize_title( $tax_class );
  616. }
  617. /**
  618. * Get store tax classes as slugs.
  619. *
  620. * @since 3.0.0
  621. * @return array Array of class slugs ("reduced-rate", "zero-rate", etc).
  622. */
  623. public static function get_tax_class_slugs() {
  624. return array_filter( array_map( 'sanitize_title', self::get_tax_classes() ) );
  625. }
  626. /**
  627. * format the city.
  628. * @param string $city
  629. * @return string
  630. */
  631. private static function format_tax_rate_city( $city ) {
  632. return strtoupper( trim( $city ) );
  633. }
  634. /**
  635. * format the state.
  636. * @param string $state
  637. * @return string
  638. */
  639. private static function format_tax_rate_state( $state ) {
  640. $state = strtoupper( $state );
  641. return ( '*' === $state ) ? '' : $state;
  642. }
  643. /**
  644. * format the country.
  645. * @param string $country
  646. * @return string
  647. */
  648. private static function format_tax_rate_country( $country ) {
  649. $country = strtoupper( $country );
  650. return ( '*' === $country ) ? '' : $country;
  651. }
  652. /**
  653. * format the tax rate name.
  654. * @param string $name
  655. * @return string
  656. */
  657. private static function format_tax_rate_name( $name ) {
  658. return $name ? $name : __( 'Tax', 'woocommerce' );
  659. }
  660. /**
  661. * format the rate.
  662. * @param double $rate
  663. * @return string
  664. */
  665. private static function format_tax_rate( $rate ) {
  666. return number_format( (double) $rate, 4, '.', '' );
  667. }
  668. /**
  669. * format the priority.
  670. * @param string $priority
  671. * @return int
  672. */
  673. private static function format_tax_rate_priority( $priority ) {
  674. return absint( $priority );
  675. }
  676. /**
  677. * format the class.
  678. * @param string $class
  679. * @return string
  680. */
  681. public static function format_tax_rate_class( $class ) {
  682. $class = sanitize_title( $class );
  683. $classes = self::get_tax_class_slugs();
  684. if ( ! in_array( $class, $classes ) ) {
  685. $class = '';
  686. }
  687. return ( 'standard' === $class ) ? '' : $class;
  688. }
  689. /**
  690. * Prepare and format tax rate for DB insertion.
  691. * @param array $tax_rate
  692. * @return array
  693. */
  694. private static function prepare_tax_rate( $tax_rate ) {
  695. foreach ( $tax_rate as $key => $value ) {
  696. if ( method_exists( __CLASS__, 'format_' . $key ) ) {
  697. if ( 'tax_rate_state' === $key ) {
  698. $tax_rate[ $key ] = call_user_func( array( __CLASS__, 'format_' . $key ), sanitize_key( $value ) );
  699. } else {
  700. $tax_rate[ $key ] = call_user_func( array( __CLASS__, 'format_' . $key ), $value );
  701. }
  702. }
  703. }
  704. return $tax_rate;
  705. }
  706. /**
  707. * Insert a new tax rate.
  708. *
  709. * Internal use only.
  710. *
  711. * @since 2.3.0
  712. * @access private
  713. *
  714. * @param array $tax_rate
  715. *
  716. * @return int tax rate id
  717. */
  718. public static function _insert_tax_rate( $tax_rate ) {
  719. global $wpdb;
  720. $wpdb->insert( $wpdb->prefix . 'woocommerce_tax_rates', self::prepare_tax_rate( $tax_rate ) );
  721. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  722. do_action( 'woocommerce_tax_rate_added', $wpdb->insert_id, $tax_rate );
  723. return $wpdb->insert_id;
  724. }
  725. /**
  726. * Get tax rate.
  727. *
  728. * Internal use only.
  729. *
  730. * @since 2.5.0
  731. * @access private
  732. *
  733. * @param int $tax_rate_id
  734. * @param string $output_type
  735. *
  736. * @return array|object
  737. */
  738. public static function _get_tax_rate( $tax_rate_id, $output_type = ARRAY_A ) {
  739. global $wpdb;
  740. return $wpdb->get_row( $wpdb->prepare( "
  741. SELECT *
  742. FROM {$wpdb->prefix}woocommerce_tax_rates
  743. WHERE tax_rate_id = %d
  744. ", $tax_rate_id ), $output_type );
  745. }
  746. /**
  747. * Update a tax rate.
  748. *
  749. * Internal use only.
  750. *
  751. * @since 2.3.0
  752. * @access private
  753. *
  754. * @param int $tax_rate_id
  755. * @param array $tax_rate
  756. */
  757. public static function _update_tax_rate( $tax_rate_id, $tax_rate ) {
  758. global $wpdb;
  759. $tax_rate_id = absint( $tax_rate_id );
  760. $wpdb->update(
  761. $wpdb->prefix . "woocommerce_tax_rates",
  762. self::prepare_tax_rate( $tax_rate ),
  763. array(
  764. 'tax_rate_id' => $tax_rate_id,
  765. )
  766. );
  767. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  768. do_action( 'woocommerce_tax_rate_updated', $tax_rate_id, $tax_rate );
  769. }
  770. /**
  771. * Delete a tax rate from the database.
  772. *
  773. * Internal use only.
  774. *
  775. * @since 2.3.0
  776. * @access private
  777. *
  778. * @param int $tax_rate_id
  779. */
  780. public static function _delete_tax_rate( $tax_rate_id ) {
  781. global $wpdb;
  782. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d;", $tax_rate_id ) );
  783. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %d;", $tax_rate_id ) );
  784. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  785. do_action( 'woocommerce_tax_rate_deleted', $tax_rate_id );
  786. }
  787. /**
  788. * Update postcodes for a tax rate in the DB.
  789. *
  790. * Internal use only.
  791. *
  792. * @since 2.3.0
  793. * @access private
  794. *
  795. * @param int $tax_rate_id
  796. * @param string $postcodes String of postcodes separated by ; characters
  797. */
  798. public static function _update_tax_rate_postcodes( $tax_rate_id, $postcodes ) {
  799. if ( ! is_array( $postcodes ) ) {
  800. $postcodes = explode( ';', $postcodes );
  801. }
  802. // No normalization - postcodes are matched against both normal and formatted versions to support wildcards.
  803. foreach ( $postcodes as $key => $postcode ) {
  804. $postcodes[ $key ] = strtoupper( trim( str_replace( chr( 226 ) . chr( 128 ) . chr( 166 ), '...', $postcode ) ) );
  805. }
  806. self::_update_tax_rate_locations( $tax_rate_id, array_diff( array_filter( $postcodes ), array( '*' ) ), 'postcode' );
  807. }
  808. /**
  809. * Update cities for a tax rate in the DB.
  810. *
  811. * Internal use only.
  812. *
  813. * @since 2.3.0
  814. * @access private
  815. *
  816. * @param int $tax_rate_id
  817. * @param string $cities
  818. */
  819. public static function _update_tax_rate_cities( $tax_rate_id, $cities ) {
  820. if ( ! is_array( $cities ) ) {
  821. $cities = explode( ';', $cities );
  822. }
  823. $cities = array_filter( array_diff( array_map( array( __CLASS__, 'format_tax_rate_city' ), $cities ), array( '*' ) ) );
  824. self::_update_tax_rate_locations( $tax_rate_id, $cities, 'city' );
  825. }
  826. /**
  827. * Updates locations (postcode and city).
  828. *
  829. * Internal use only.
  830. *
  831. * @since 2.3.0
  832. * @access private
  833. *
  834. * @param int $tax_rate_id
  835. * @param array $values
  836. * @param string $type
  837. */
  838. private static function _update_tax_rate_locations( $tax_rate_id, $values, $type ) {
  839. global $wpdb;
  840. $tax_rate_id = absint( $tax_rate_id );
  841. $wpdb->query(
  842. $wpdb->prepare( "
  843. DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d AND location_type = %s;
  844. ", $tax_rate_id, $type
  845. )
  846. );
  847. if ( sizeof( $values ) > 0 ) {
  848. $sql = "( '" . implode( "', $tax_rate_id, '" . esc_sql( $type ) . "' ),( '", array_map( 'esc_sql', $values ) ) . "', $tax_rate_id, '" . esc_sql( $type ) . "' )";
  849. $wpdb->query( "
  850. INSERT INTO {$wpdb->prefix}woocommerce_tax_rate_locations ( location_code, tax_rate_id, location_type ) VALUES $sql;
  851. " );
  852. }
  853. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  854. }
  855. /**
  856. * Used by admin settings page.
  857. *
  858. * @param string $tax_class
  859. *
  860. * @return array|null|object
  861. */
  862. public static function get_rates_for_tax_class( $tax_class ) {
  863. global $wpdb;
  864. // Get all the rates and locations. Snagging all at once should significantly cut down on the number of queries.
  865. $rates = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}woocommerce_tax_rates` WHERE `tax_rate_class` = %s;", sanitize_title( $tax_class ) ) );
  866. $locations = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}woocommerce_tax_rate_locations`" );
  867. if ( ! empty( $rates ) ) {
  868. // Set the rates keys equal to their ids.
  869. $rates = array_combine( wp_list_pluck( $rates, 'tax_rate_id' ), $rates );
  870. }
  871. // Drop the locations into the rates array.
  872. foreach ( $locations as $location ) {
  873. // Don't set them for unexistent rates.
  874. if ( ! isset( $rates[ $location->tax_rate_id ] ) ) {
  875. continue;
  876. }
  877. // If the rate exists, initialize the array before appending to it.
  878. if ( ! isset( $rates[ $location->tax_rate_id ]->{$location->location_type} ) ) {
  879. $rates[ $location->tax_rate_id ]->{$location->location_type} = array();
  880. }
  881. $rates[ $location->tax_rate_id ]->{$location->location_type}[] = $location->location_code;
  882. }
  883. foreach ( $rates as $rate_id => $rate ) {
  884. $rates[ $rate_id ]->postcode_count = isset( $rates[ $rate_id ]->postcode ) ? count( $rates[ $rate_id ]->postcode ) : 0;
  885. $rates[ $rate_id ]->city_count = isset( $rates[ $rate_id ]->city ) ? count( $rates[ $rate_id ]->city ) : 0;
  886. }
  887. $rates = self::sort_rates( $rates );
  888. return $rates;
  889. }
  890. }
  891. WC_Tax::init();