wc-formatting-functions.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. <?php
  2. /**
  3. * WooCommerce Formatting
  4. *
  5. * Functions for formatting data.
  6. *
  7. * @package WooCommerce/Functions
  8. * @version 2.1.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Converts a string (e.g. 'yes' or 'no') to a bool.
  13. *
  14. * @since 3.0.0
  15. * @param string $string String to convert.
  16. * @return bool
  17. */
  18. function wc_string_to_bool( $string ) {
  19. return is_bool( $string ) ? $string : ( 'yes' === $string || 1 === $string || 'true' === $string || '1' === $string );
  20. }
  21. /**
  22. * Converts a bool to a 'yes' or 'no'.
  23. *
  24. * @since 3.0.0
  25. * @param bool $bool String to convert.
  26. * @return string
  27. */
  28. function wc_bool_to_string( $bool ) {
  29. if ( ! is_bool( $bool ) ) {
  30. $bool = wc_string_to_bool( $bool );
  31. }
  32. return true === $bool ? 'yes' : 'no';
  33. }
  34. /**
  35. * Explode a string into an array by $delimiter and remove empty values.
  36. *
  37. * @since 3.0.0
  38. * @param string $string String to convert.
  39. * @param string $delimiter Delimiter, defaults to ','.
  40. * @return array
  41. */
  42. function wc_string_to_array( $string, $delimiter = ',' ) {
  43. return is_array( $string ) ? $string : array_filter( explode( $delimiter, $string ) );
  44. }
  45. /**
  46. * Sanitize taxonomy names. Slug format (no spaces, lowercase).
  47. * Urldecode is used to reverse munging of UTF8 characters.
  48. *
  49. * @param string $taxonomy Taxonomy name.
  50. * @return string
  51. */
  52. function wc_sanitize_taxonomy_name( $taxonomy ) {
  53. return apply_filters( 'sanitize_taxonomy_name', urldecode( sanitize_title( urldecode( $taxonomy ) ) ), $taxonomy );
  54. }
  55. /**
  56. * Sanitize permalink values before insertion into DB.
  57. *
  58. * Cannot use wc_clean because it sometimes strips % chars and breaks the user's setting.
  59. *
  60. * @since 2.6.0
  61. * @param string $value Permalink.
  62. * @return string
  63. */
  64. function wc_sanitize_permalink( $value ) {
  65. global $wpdb;
  66. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  67. if ( is_wp_error( $value ) ) {
  68. $value = '';
  69. }
  70. $value = esc_url_raw( trim( $value ) );
  71. $value = str_replace( 'http://', '', $value );
  72. return untrailingslashit( $value );
  73. }
  74. /**
  75. * Gets the filename part of a download URL.
  76. *
  77. * @param string $file_url File URL.
  78. * @return string
  79. */
  80. function wc_get_filename_from_url( $file_url ) {
  81. $parts = wp_parse_url( $file_url );
  82. if ( isset( $parts['path'] ) ) {
  83. return basename( $parts['path'] );
  84. }
  85. }
  86. /**
  87. * Normalise dimensions, unify to cm then convert to wanted unit value.
  88. *
  89. * Usage:
  90. * wc_get_dimension( 55, 'in' );
  91. * wc_get_dimension( 55, 'in', 'm' );
  92. *
  93. * @param int|float $dimension Dimension.
  94. * @param string $to_unit Unit to convert to.
  95. * Options: 'in', 'm', 'cm', 'm'.
  96. * @param string $from_unit Unit to convert from.
  97. * Defaults to ''.
  98. * Options: 'in', 'm', 'cm', 'm'.
  99. * @return float
  100. */
  101. function wc_get_dimension( $dimension, $to_unit, $from_unit = '' ) {
  102. $to_unit = strtolower( $to_unit );
  103. if ( empty( $from_unit ) ) {
  104. $from_unit = strtolower( get_option( 'woocommerce_dimension_unit' ) );
  105. }
  106. // Unify all units to cm first.
  107. if ( $from_unit !== $to_unit ) {
  108. switch ( $from_unit ) {
  109. case 'in':
  110. $dimension *= 2.54;
  111. break;
  112. case 'm':
  113. $dimension *= 100;
  114. break;
  115. case 'mm':
  116. $dimension *= 0.1;
  117. break;
  118. case 'yd':
  119. $dimension *= 91.44;
  120. break;
  121. }
  122. // Output desired unit.
  123. switch ( $to_unit ) {
  124. case 'in':
  125. $dimension *= 0.3937;
  126. break;
  127. case 'm':
  128. $dimension *= 0.01;
  129. break;
  130. case 'mm':
  131. $dimension *= 10;
  132. break;
  133. case 'yd':
  134. $dimension *= 0.010936133;
  135. break;
  136. }
  137. }
  138. return ( $dimension < 0 ) ? 0 : $dimension;
  139. }
  140. /**
  141. * Normalise weights, unify to kg then convert to wanted unit value.
  142. *
  143. * Usage:
  144. * wc_get_weight(55, 'kg');
  145. * wc_get_weight(55, 'kg', 'lbs');
  146. *
  147. * @param int|float $weight Weight.
  148. * @param string $to_unit Unit to convert to.
  149. * Options: 'g', 'kg', 'lbs', 'oz'.
  150. * @param string $from_unit Unit to convert from.
  151. * Defaults to ''.
  152. * Options: 'g', 'kg', 'lbs', 'oz'.
  153. * @return float
  154. */
  155. function wc_get_weight( $weight, $to_unit, $from_unit = '' ) {
  156. $weight = (float) $weight;
  157. $to_unit = strtolower( $to_unit );
  158. if ( empty( $from_unit ) ) {
  159. $from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) );
  160. }
  161. // Unify all units to kg first.
  162. if ( $from_unit !== $to_unit ) {
  163. switch ( $from_unit ) {
  164. case 'g':
  165. $weight *= 0.001;
  166. break;
  167. case 'lbs':
  168. $weight *= 0.453592;
  169. break;
  170. case 'oz':
  171. $weight *= 0.0283495;
  172. break;
  173. }
  174. // Output desired unit.
  175. switch ( $to_unit ) {
  176. case 'g':
  177. $weight *= 1000;
  178. break;
  179. case 'lbs':
  180. $weight *= 2.20462;
  181. break;
  182. case 'oz':
  183. $weight *= 35.274;
  184. break;
  185. }
  186. }
  187. return ( $weight < 0 ) ? 0 : $weight;
  188. }
  189. /**
  190. * Trim trailing zeros off prices.
  191. *
  192. * @param string|float|int $price Price.
  193. * @return string
  194. */
  195. function wc_trim_zeros( $price ) {
  196. return preg_replace( '/' . preg_quote( wc_get_price_decimal_separator(), '/' ) . '0++$/', '', $price );
  197. }
  198. /**
  199. * Round a tax amount.
  200. *
  201. * @param double $value Amount to round.
  202. * @param int $precision DP to round. Defaults to wc_get_price_decimals.
  203. * @return float
  204. */
  205. function wc_round_tax_total( $value, $precision = null ) {
  206. $precision = is_null( $precision ) ? wc_get_price_decimals() : intval( $precision );
  207. if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) {
  208. $rounded_tax = round( $value, $precision, wc_get_tax_rounding_mode() ); // phpcs:ignore PHPCompatibility.PHP.NewFunctionParameters.round_modeFound
  209. } elseif ( 2 === wc_get_tax_rounding_mode() ) {
  210. $rounded_tax = wc_legacy_round_half_down( $value, $precision );
  211. } else {
  212. $rounded_tax = round( $value, $precision );
  213. }
  214. return apply_filters( 'wc_round_tax_total', $rounded_tax, $value, $precision, WC_TAX_ROUNDING_MODE );
  215. }
  216. /**
  217. * Round half down in PHP 5.2.
  218. *
  219. * @since 3.2.6
  220. * @param float $value Value to round.
  221. * @param int $precision Precision to round down to.
  222. * @return float
  223. */
  224. function wc_legacy_round_half_down( $value, $precision ) {
  225. $value = wc_float_to_string( $value );
  226. if ( false !== strstr( $value, '.' ) ) {
  227. $value = explode( '.', $value );
  228. if ( strlen( $value[1] ) > $precision && substr( $value[1], -1 ) === '5' ) {
  229. $value[1] = substr( $value[1], 0, -1 ) . '4';
  230. }
  231. $value = implode( '.', $value );
  232. }
  233. return round( floatval( $value ), $precision );
  234. }
  235. /**
  236. * Make a refund total negative.
  237. *
  238. * @param float $amount Refunded amount.
  239. *
  240. * @return float
  241. */
  242. function wc_format_refund_total( $amount ) {
  243. return $amount * -1;
  244. }
  245. /**
  246. * Format decimal numbers ready for DB storage.
  247. *
  248. * Sanitize, remove decimals, and optionally round + trim off zeros.
  249. *
  250. * This function does not remove thousands - this should be done before passing a value to the function.
  251. *
  252. * @param float|string $number Expects either a float or a string with a decimal separator only (no thousands).
  253. * @param mixed $dp number Number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding.
  254. * @param bool $trim_zeros From end of string.
  255. * @return string
  256. */
  257. function wc_format_decimal( $number, $dp = false, $trim_zeros = false ) {
  258. $locale = localeconv();
  259. $decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
  260. // Remove locale from string.
  261. if ( ! is_float( $number ) ) {
  262. $number = str_replace( $decimals, '.', $number );
  263. $number = preg_replace( '/[^0-9\.,-]/', '', wc_clean( $number ) );
  264. }
  265. if ( false !== $dp ) {
  266. $dp = intval( '' === $dp ? wc_get_price_decimals() : $dp );
  267. $number = number_format( floatval( $number ), $dp, '.', '' );
  268. } elseif ( is_float( $number ) ) {
  269. // DP is false - don't use number format, just return a string using whatever is given. Remove scientific notation using sprintf.
  270. $number = str_replace( $decimals, '.', sprintf( '%.' . wc_get_rounding_precision() . 'f', $number ) );
  271. // We already had a float, so trailing zeros are not needed.
  272. $trim_zeros = true;
  273. }
  274. if ( $trim_zeros && strstr( $number, '.' ) ) {
  275. $number = rtrim( rtrim( $number, '0' ), '.' );
  276. }
  277. return $number;
  278. }
  279. /**
  280. * Convert a float to a string without locale formatting which PHP adds when changing floats to strings.
  281. *
  282. * @param float $float Float value to format.
  283. * @return string
  284. */
  285. function wc_float_to_string( $float ) {
  286. if ( ! is_float( $float ) ) {
  287. return $float;
  288. }
  289. $locale = localeconv();
  290. $string = strval( $float );
  291. $string = str_replace( $locale['decimal_point'], '.', $string );
  292. return $string;
  293. }
  294. /**
  295. * Format a price with WC Currency Locale settings.
  296. *
  297. * @param string $value Price to localize.
  298. * @return string
  299. */
  300. function wc_format_localized_price( $value ) {
  301. return apply_filters( 'woocommerce_format_localized_price', str_replace( '.', wc_get_price_decimal_separator(), strval( $value ) ), $value );
  302. }
  303. /**
  304. * Format a decimal with PHP Locale settings.
  305. *
  306. * @param string $value Decimal to localize.
  307. * @return string
  308. */
  309. function wc_format_localized_decimal( $value ) {
  310. $locale = localeconv();
  311. return apply_filters( 'woocommerce_format_localized_decimal', str_replace( '.', $locale['decimal_point'], strval( $value ) ), $value );
  312. }
  313. /**
  314. * Format a coupon code.
  315. *
  316. * @since 3.0.0
  317. * @param string $value Coupon code to format.
  318. * @return string
  319. */
  320. function wc_format_coupon_code( $value ) {
  321. return apply_filters( 'woocommerce_coupon_code', $value );
  322. }
  323. /**
  324. * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
  325. * Non-scalar values are ignored.
  326. *
  327. * @param string|array $var Data to sanitize.
  328. * @return string|array
  329. */
  330. function wc_clean( $var ) {
  331. if ( is_array( $var ) ) {
  332. return array_map( 'wc_clean', $var );
  333. } else {
  334. return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
  335. }
  336. }
  337. /**
  338. * Run wc_clean over posted textarea but maintain line breaks.
  339. *
  340. * @since 3.0.0
  341. * @param string $var Data to sanitize.
  342. * @return string
  343. */
  344. function wc_sanitize_textarea( $var ) {
  345. return implode( "\n", array_map( 'wc_clean', explode( "\n", $var ) ) );
  346. }
  347. /**
  348. * Sanitize a string destined to be a tooltip.
  349. *
  350. * @since 2.3.10 Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
  351. * @param string $var Data to sanitize.
  352. * @return string
  353. */
  354. function wc_sanitize_tooltip( $var ) {
  355. return htmlspecialchars(
  356. wp_kses(
  357. html_entity_decode( $var ), array(
  358. 'br' => array(),
  359. 'em' => array(),
  360. 'strong' => array(),
  361. 'small' => array(),
  362. 'span' => array(),
  363. 'ul' => array(),
  364. 'li' => array(),
  365. 'ol' => array(),
  366. 'p' => array(),
  367. )
  368. )
  369. );
  370. }
  371. /**
  372. * Merge two arrays.
  373. *
  374. * @param array $a1 First array to merge.
  375. * @param array $a2 Second array to merge.
  376. * @return array
  377. */
  378. function wc_array_overlay( $a1, $a2 ) {
  379. foreach ( $a1 as $k => $v ) {
  380. if ( ! array_key_exists( $k, $a2 ) ) {
  381. continue;
  382. }
  383. if ( is_array( $v ) && is_array( $a2[ $k ] ) ) {
  384. $a1[ $k ] = wc_array_overlay( $v, $a2[ $k ] );
  385. } else {
  386. $a1[ $k ] = $a2[ $k ];
  387. }
  388. }
  389. return $a1;
  390. }
  391. /**
  392. * Formats a stock amount by running it through a filter.
  393. *
  394. * @param int|float $amount Stock amount.
  395. * @return int|float
  396. */
  397. function wc_stock_amount( $amount ) {
  398. return apply_filters( 'woocommerce_stock_amount', $amount );
  399. }
  400. /**
  401. * Get the price format depending on the currency position.
  402. *
  403. * @return string
  404. */
  405. function get_woocommerce_price_format() {
  406. $currency_pos = get_option( 'woocommerce_currency_pos' );
  407. $format = '%1$s%2$s';
  408. switch ( $currency_pos ) {
  409. case 'left':
  410. $format = '%1$s%2$s';
  411. break;
  412. case 'right':
  413. $format = '%2$s%1$s';
  414. break;
  415. case 'left_space':
  416. $format = '%1$s&nbsp;%2$s';
  417. break;
  418. case 'right_space':
  419. $format = '%2$s&nbsp;%1$s';
  420. break;
  421. }
  422. return apply_filters( 'woocommerce_price_format', $format, $currency_pos );
  423. }
  424. /**
  425. * Return the thousand separator for prices.
  426. *
  427. * @since 2.3
  428. * @return string
  429. */
  430. function wc_get_price_thousand_separator() {
  431. return stripslashes( apply_filters( 'wc_get_price_thousand_separator', get_option( 'woocommerce_price_thousand_sep' ) ) );
  432. }
  433. /**
  434. * Return the decimal separator for prices.
  435. *
  436. * @since 2.3
  437. * @return string
  438. */
  439. function wc_get_price_decimal_separator() {
  440. $separator = apply_filters( 'wc_get_price_decimal_separator', get_option( 'woocommerce_price_decimal_sep' ) );
  441. return $separator ? stripslashes( $separator ) : '.';
  442. }
  443. /**
  444. * Return the number of decimals after the decimal point.
  445. *
  446. * @since 2.3
  447. * @return int
  448. */
  449. function wc_get_price_decimals() {
  450. return absint( apply_filters( 'wc_get_price_decimals', get_option( 'woocommerce_price_num_decimals', 2 ) ) );
  451. }
  452. /**
  453. * Format the price with a currency symbol.
  454. *
  455. * @param float $price Raw price.
  456. * @param array $args Arguments to format a price {
  457. * Array of arguments.
  458. * Defaults to empty array.
  459. *
  460. * @type bool $ex_tax_label Adds exclude tax label.
  461. * Defaults to false.
  462. * @type string $currency Currency code.
  463. * Defaults to empty string (Use the result from get_woocommerce_currency()).
  464. * @type string $decimal_separator Decimal separator.
  465. * Defaults the result of wc_get_price_decimal_separator().
  466. * @type string $thousand_separator Thousand separator.
  467. * Defaults the result of wc_get_price_thousand_separator().
  468. * @type string $decimals Number of decimals.
  469. * Defaults the result of wc_get_price_decimals().
  470. * @type string $price_format Price format depending on the currency position.
  471. * Defaults the result of get_woocommerce_price_format().
  472. * }
  473. * @return string
  474. */
  475. function wc_price( $price, $args = array() ) {
  476. $args = apply_filters(
  477. 'wc_price_args', wp_parse_args(
  478. $args, array(
  479. 'ex_tax_label' => false,
  480. 'currency' => '',
  481. 'decimal_separator' => wc_get_price_decimal_separator(),
  482. 'thousand_separator' => wc_get_price_thousand_separator(),
  483. 'decimals' => wc_get_price_decimals(),
  484. 'price_format' => get_woocommerce_price_format(),
  485. )
  486. )
  487. );
  488. $unformatted_price = $price;
  489. $negative = $price < 0;
  490. $price = apply_filters( 'raw_woocommerce_price', floatval( $negative ? $price * -1 : $price ) );
  491. $price = apply_filters( 'formatted_woocommerce_price', number_format( $price, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'] ), $price, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'] );
  492. if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $args['decimals'] > 0 ) {
  493. $price = wc_trim_zeros( $price );
  494. }
  495. $formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $args['currency'] ) . '</span>', $price );
  496. $return = '<span class="woocommerce-Price-amount amount">' . $formatted_price . '</span>';
  497. if ( $args['ex_tax_label'] && wc_tax_enabled() ) {
  498. $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
  499. }
  500. /**
  501. * Filters the string of price markup.
  502. *
  503. * @param string $return Price HTML markup.
  504. * @param string $price Formatted price.
  505. * @param array $args Pass on the args.
  506. * @param float $unformatted_price Price as float to allow plugins custom formatting. Since 3.2.0.
  507. */
  508. return apply_filters( 'wc_price', $return, $price, $args, $unformatted_price );
  509. }
  510. /**
  511. * Notation to numbers.
  512. *
  513. * This function transforms the php.ini notation for numbers (like '2M') to an integer.
  514. *
  515. * @param string $size Size value.
  516. * @return int
  517. */
  518. function wc_let_to_num( $size ) {
  519. $l = substr( $size, -1 );
  520. $ret = substr( $size, 0, -1 );
  521. $byte = 1024;
  522. switch ( strtoupper( $l ) ) {
  523. case 'P':
  524. $ret *= 1024;
  525. // No break.
  526. case 'T':
  527. $ret *= 1024;
  528. // No break.
  529. case 'G':
  530. $ret *= 1024;
  531. // No break.
  532. case 'M':
  533. $ret *= 1024;
  534. // No break.
  535. case 'K':
  536. $ret *= 1024;
  537. // No break.
  538. }
  539. return $ret;
  540. }
  541. /**
  542. * WooCommerce Date Format - Allows to change date format for everything WooCommerce.
  543. *
  544. * @return string
  545. */
  546. function wc_date_format() {
  547. return apply_filters( 'woocommerce_date_format', get_option( 'date_format' ) );
  548. }
  549. /**
  550. * WooCommerce Time Format - Allows to change time format for everything WooCommerce.
  551. *
  552. * @return string
  553. */
  554. function wc_time_format() {
  555. return apply_filters( 'woocommerce_time_format', get_option( 'time_format' ) );
  556. }
  557. /**
  558. * Convert mysql datetime to PHP timestamp, forcing UTC. Wrapper for strtotime.
  559. *
  560. * Based on wcs_strtotime_dark_knight() from WC Subscriptions by Prospress.
  561. *
  562. * @since 3.0.0
  563. * @param string $time_string Time string.
  564. * @param int|null $from_timestamp Timestamp to convert from.
  565. * @return int
  566. */
  567. function wc_string_to_timestamp( $time_string, $from_timestamp = null ) {
  568. $original_timezone = date_default_timezone_get();
  569. // @codingStandardsIgnoreStart
  570. date_default_timezone_set( 'UTC' );
  571. if ( null === $from_timestamp ) {
  572. $next_timestamp = strtotime( $time_string );
  573. } else {
  574. $next_timestamp = strtotime( $time_string, $from_timestamp );
  575. }
  576. date_default_timezone_set( $original_timezone );
  577. // @codingStandardsIgnoreEnd
  578. return $next_timestamp;
  579. }
  580. /**
  581. * Convert a date string to a WC_DateTime.
  582. *
  583. * @since 3.1.0
  584. * @param string $time_string Time string.
  585. * @return WC_DateTime
  586. */
  587. function wc_string_to_datetime( $time_string ) {
  588. // Strings are defined in local WP timezone. Convert to UTC.
  589. if ( 1 === preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|((-|\+)\d{2}:\d{2}))$/', $time_string, $date_bits ) ) {
  590. $offset = ! empty( $date_bits[7] ) ? iso8601_timezone_to_offset( $date_bits[7] ) : wc_timezone_offset();
  591. $timestamp = gmmktime( $date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1] ) - $offset;
  592. } else {
  593. $timestamp = wc_string_to_timestamp( get_gmt_from_date( gmdate( 'Y-m-d H:i:s', wc_string_to_timestamp( $time_string ) ) ) );
  594. }
  595. $datetime = new WC_DateTime( "@{$timestamp}", new DateTimeZone( 'UTC' ) );
  596. // Set local timezone or offset.
  597. if ( get_option( 'timezone_string' ) ) {
  598. $datetime->setTimezone( new DateTimeZone( wc_timezone_string() ) );
  599. } else {
  600. $datetime->set_utc_offset( wc_timezone_offset() );
  601. }
  602. return $datetime;
  603. }
  604. /**
  605. * WooCommerce Timezone - helper to retrieve the timezone string for a site until.
  606. * a WP core method exists (see https://core.trac.wordpress.org/ticket/24730).
  607. *
  608. * Adapted from https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
  609. *
  610. * @since 2.1
  611. * @return string PHP timezone string for the site
  612. */
  613. function wc_timezone_string() {
  614. // If site timezone string exists, return it.
  615. $timezone = get_option( 'timezone_string' );
  616. if ( $timezone ) {
  617. return $timezone;
  618. }
  619. // Get UTC offset, if it isn't set then return UTC.
  620. $utc_offset = intval( get_option( 'gmt_offset', 0 ) );
  621. if ( 0 === $utc_offset ) {
  622. return 'UTC';
  623. }
  624. // Adjust UTC offset from hours to seconds.
  625. $utc_offset *= 3600;
  626. // Attempt to guess the timezone string from the UTC offset.
  627. $timezone = timezone_name_from_abbr( '', $utc_offset );
  628. if ( $timezone ) {
  629. return $timezone;
  630. }
  631. // Last try, guess timezone string manually.
  632. foreach ( timezone_abbreviations_list() as $abbr ) {
  633. foreach ( $abbr as $city ) {
  634. if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) {
  635. return $city['timezone_id'];
  636. }
  637. }
  638. }
  639. // Fallback to UTC.
  640. return 'UTC';
  641. }
  642. /**
  643. * Get timezone offset in seconds.
  644. *
  645. * @since 3.0.0
  646. * @return float
  647. */
  648. function wc_timezone_offset() {
  649. $timezone = get_option( 'timezone_string' );
  650. if ( $timezone ) {
  651. $timezone_object = new DateTimeZone( $timezone );
  652. return $timezone_object->getOffset( new DateTime( 'now' ) );
  653. } else {
  654. return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
  655. }
  656. }
  657. /**
  658. * Callback which can flatten post meta (gets the first value if it's an array).
  659. *
  660. * @since 3.0.0
  661. * @param array $value Value to flatten.
  662. * @return mixed
  663. */
  664. function wc_flatten_meta_callback( $value ) {
  665. return is_array( $value ) ? current( $value ) : $value;
  666. }
  667. if ( ! function_exists( 'wc_rgb_from_hex' ) ) {
  668. /**
  669. * Convert RGB to HEX.
  670. *
  671. * @param mixed $color Color.
  672. *
  673. * @return array
  674. */
  675. function wc_rgb_from_hex( $color ) {
  676. $color = str_replace( '#', '', $color );
  677. // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF".
  678. $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
  679. $rgb = array();
  680. $rgb['R'] = hexdec( $color{0} . $color{1} );
  681. $rgb['G'] = hexdec( $color{2} . $color{3} );
  682. $rgb['B'] = hexdec( $color{4} . $color{5} );
  683. return $rgb;
  684. }
  685. }
  686. if ( ! function_exists( 'wc_hex_darker' ) ) {
  687. /**
  688. * Make HEX color darker.
  689. *
  690. * @param mixed $color Color.
  691. * @param int $factor Darker factor.
  692. * Defaults to 30.
  693. * @return string
  694. */
  695. function wc_hex_darker( $color, $factor = 30 ) {
  696. $base = wc_rgb_from_hex( $color );
  697. $color = '#';
  698. foreach ( $base as $k => $v ) {
  699. $amount = $v / 100;
  700. $amount = round( $amount * $factor );
  701. $new_decimal = $v - $amount;
  702. $new_hex_component = dechex( $new_decimal );
  703. if ( strlen( $new_hex_component ) < 2 ) {
  704. $new_hex_component = '0' . $new_hex_component;
  705. }
  706. $color .= $new_hex_component;
  707. }
  708. return $color;
  709. }
  710. }
  711. if ( ! function_exists( 'wc_hex_lighter' ) ) {
  712. /**
  713. * Make HEX color lighter.
  714. *
  715. * @param mixed $color Color.
  716. * @param int $factor Lighter factor.
  717. * Defaults to 30.
  718. * @return string
  719. */
  720. function wc_hex_lighter( $color, $factor = 30 ) {
  721. $base = wc_rgb_from_hex( $color );
  722. $color = '#';
  723. foreach ( $base as $k => $v ) {
  724. $amount = 255 - $v;
  725. $amount = $amount / 100;
  726. $amount = round( $amount * $factor );
  727. $new_decimal = $v + $amount;
  728. $new_hex_component = dechex( $new_decimal );
  729. if ( strlen( $new_hex_component ) < 2 ) {
  730. $new_hex_component = '0' . $new_hex_component;
  731. }
  732. $color .= $new_hex_component;
  733. }
  734. return $color;
  735. }
  736. }
  737. if ( ! function_exists( 'wc_is_light' ) ) {
  738. /**
  739. * Determine whether a hex color is light.
  740. *
  741. * @param mixed $color Color.
  742. * @return bool True if a light color.
  743. */
  744. function wc_hex_is_light( $color ) {
  745. $hex = str_replace( '#', '', $color );
  746. $c_r = hexdec( substr( $hex, 0, 2 ) );
  747. $c_g = hexdec( substr( $hex, 2, 2 ) );
  748. $c_b = hexdec( substr( $hex, 4, 2 ) );
  749. $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
  750. return $brightness > 155;
  751. }
  752. }
  753. if ( ! function_exists( 'wc_light_or_dark' ) ) {
  754. /**
  755. * Detect if we should use a light or dark color on a background color.
  756. *
  757. * @param mixed $color Color.
  758. * @param string $dark Darkest reference.
  759. * Defaults to '#000000'.
  760. * @param string $light Lightest reference.
  761. * Defaults to '#FFFFFF'.
  762. * @return string
  763. */
  764. function wc_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
  765. return wc_hex_is_light( $color ) ? $dark : $light;
  766. }
  767. }
  768. if ( ! function_exists( 'wc_format_hex' ) ) {
  769. /**
  770. * Format string as hex.
  771. *
  772. * @param string $hex HEX color.
  773. * @return string|null
  774. */
  775. function wc_format_hex( $hex ) {
  776. $hex = trim( str_replace( '#', '', $hex ) );
  777. if ( strlen( $hex ) === 3 ) {
  778. $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
  779. }
  780. return $hex ? '#' . $hex : null;
  781. }
  782. }
  783. /**
  784. * Format the postcode according to the country and length of the postcode.
  785. *
  786. * @param string $postcode Unformatted postcode.
  787. * @param string $country Base country.
  788. * @return string
  789. */
  790. function wc_format_postcode( $postcode, $country ) {
  791. $postcode = wc_normalize_postcode( $postcode );
  792. switch ( $country ) {
  793. case 'CA':
  794. case 'GB':
  795. $postcode = trim( substr_replace( $postcode, ' ', -3, 0 ) );
  796. break;
  797. case 'BR':
  798. case 'PL':
  799. $postcode = substr_replace( $postcode, '-', -3, 0 );
  800. break;
  801. case 'JP':
  802. $postcode = substr_replace( $postcode, '-', 3, 0 );
  803. break;
  804. case 'PT':
  805. $postcode = substr_replace( $postcode, '-', 4, 0 );
  806. break;
  807. case 'US':
  808. $postcode = rtrim( substr_replace( $postcode, '-', 5, 0 ), '-' );
  809. break;
  810. }
  811. return apply_filters( 'woocommerce_format_postcode', $postcode, $country );
  812. }
  813. /**
  814. * Normalize postcodes.
  815. *
  816. * Remove spaces and convert characters to uppercase.
  817. *
  818. * @since 2.6.0
  819. * @param string $postcode Postcode.
  820. * @return string
  821. */
  822. function wc_normalize_postcode( $postcode ) {
  823. return preg_replace( '/[\s\-]/', '', trim( wc_strtoupper( $postcode ) ) );
  824. }
  825. /**
  826. * Format phone numbers.
  827. *
  828. * @param string $phone Phone number.
  829. * @return string
  830. */
  831. function wc_format_phone_number( $phone ) {
  832. return preg_replace( '/[^0-9\+\-\s]/', '-', preg_replace( '/[\x00-\x1F\x7F-\xFF]/', '', $phone ) );
  833. }
  834. /**
  835. * Wrapper for mb_strtoupper which see's if supported first.
  836. *
  837. * @since 3.1.0
  838. * @param string $string String to format.
  839. * @return string
  840. */
  841. function wc_strtoupper( $string ) {
  842. return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $string ) : strtoupper( $string );
  843. }
  844. /**
  845. * Make a string lowercase.
  846. * Try to use mb_strtolower() when available.
  847. *
  848. * @since 2.3
  849. * @param string $string String to format.
  850. * @return string
  851. */
  852. function wc_strtolower( $string ) {
  853. return function_exists( 'mb_strtolower' ) ? mb_strtolower( $string ) : strtolower( $string );
  854. }
  855. /**
  856. * Trim a string and append a suffix.
  857. *
  858. * @param string $string String to trim.
  859. * @param integer $chars Amount of characters.
  860. * Defaults to 200.
  861. * @param string $suffix Suffix.
  862. * Defaults to '...'.
  863. * @return string
  864. */
  865. function wc_trim_string( $string, $chars = 200, $suffix = '...' ) {
  866. if ( strlen( $string ) > $chars ) {
  867. if ( function_exists( 'mb_substr' ) ) {
  868. $string = mb_substr( $string, 0, ( $chars - mb_strlen( $suffix ) ) ) . $suffix;
  869. } else {
  870. $string = substr( $string, 0, ( $chars - strlen( $suffix ) ) ) . $suffix;
  871. }
  872. }
  873. return $string;
  874. }
  875. /**
  876. * Format content to display shortcodes.
  877. *
  878. * @since 2.3.0
  879. * @param string $raw_string Raw string.
  880. * @return string
  881. */
  882. function wc_format_content( $raw_string ) {
  883. return apply_filters( 'woocommerce_format_content', apply_filters( 'woocommerce_short_description', $raw_string ), $raw_string );
  884. }
  885. /**
  886. * Format product short description.
  887. * Adds support for Jetpack Markdown.
  888. *
  889. * @codeCoverageIgnore
  890. * @since 2.4.0
  891. * @param string $content Product short description.
  892. * @return string
  893. */
  894. function wc_format_product_short_description( $content ) {
  895. // Add support for Jetpack Markdown.
  896. if ( class_exists( 'WPCom_Markdown' ) ) {
  897. $markdown = WPCom_Markdown::get_instance();
  898. return wpautop(
  899. $markdown->transform(
  900. $content, array(
  901. 'unslash' => false,
  902. )
  903. )
  904. );
  905. }
  906. return $content;
  907. }
  908. /**
  909. * Formats curency symbols when saved in settings.
  910. *
  911. * @codeCoverageIgnore
  912. * @param string $value Option value.
  913. * @param array $option Option name.
  914. * @param string $raw_value Raw value.
  915. * @return string
  916. */
  917. function wc_format_option_price_separators( $value, $option, $raw_value ) {
  918. return wp_kses_post( $raw_value );
  919. }
  920. add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_decimal_sep', 'wc_format_option_price_separators', 10, 3 );
  921. add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_thousand_sep', 'wc_format_option_price_separators', 10, 3 );
  922. /**
  923. * Formats decimals when saved in settings.
  924. *
  925. * @codeCoverageIgnore
  926. * @param string $value Option value.
  927. * @param array $option Option name.
  928. * @param string $raw_value Raw value.
  929. * @return string
  930. */
  931. function wc_format_option_price_num_decimals( $value, $option, $raw_value ) {
  932. return is_null( $raw_value ) ? 2 : absint( $raw_value );
  933. }
  934. add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_num_decimals', 'wc_format_option_price_num_decimals', 10, 3 );
  935. /**
  936. * Formats hold stock option and sets cron event up.
  937. *
  938. * @codeCoverageIgnore
  939. * @param string $value Option value.
  940. * @param array $option Option name.
  941. * @param string $raw_value Raw value.
  942. * @return string
  943. */
  944. function wc_format_option_hold_stock_minutes( $value, $option, $raw_value ) {
  945. $value = ! empty( $raw_value ) ? absint( $raw_value ) : ''; // Allow > 0 or set to ''.
  946. wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
  947. if ( '' !== $value ) {
  948. wp_schedule_single_event( time() + ( absint( $value ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
  949. }
  950. return $value;
  951. }
  952. add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_hold_stock_minutes', 'wc_format_option_hold_stock_minutes', 10, 3 );
  953. /**
  954. * Sanitize terms from an attribute text based.
  955. *
  956. * @since 2.4.5
  957. * @param string $term Term value.
  958. * @return string
  959. */
  960. function wc_sanitize_term_text_based( $term ) {
  961. return trim( wp_unslash( strip_tags( $term ) ) );
  962. }
  963. if ( ! function_exists( 'wc_make_numeric_postcode' ) ) {
  964. /**
  965. * Make numeric postcode.
  966. *
  967. * Converts letters to numbers so we can do a simple range check on postcodes.
  968. * E.g. PE30 becomes 16050300 (P = 16, E = 05, 3 = 03, 0 = 00)
  969. *
  970. * @since 2.6.0
  971. * @param string $postcode Regular postcode.
  972. * @return string
  973. */
  974. function wc_make_numeric_postcode( $postcode ) {
  975. $postcode = str_replace( array( ' ', '-' ), '', $postcode );
  976. $postcode_length = strlen( $postcode );
  977. $letters_to_numbers = array_merge( array( 0 ), range( 'A', 'Z' ) );
  978. $letters_to_numbers = array_flip( $letters_to_numbers );
  979. $numeric_postcode = '';
  980. for ( $i = 0; $i < $postcode_length; $i ++ ) {
  981. if ( is_numeric( $postcode[ $i ] ) ) {
  982. $numeric_postcode .= str_pad( $postcode[ $i ], 2, '0', STR_PAD_LEFT );
  983. } elseif ( isset( $letters_to_numbers[ $postcode[ $i ] ] ) ) {
  984. $numeric_postcode .= str_pad( $letters_to_numbers[ $postcode[ $i ] ], 2, '0', STR_PAD_LEFT );
  985. } else {
  986. $numeric_postcode .= '00';
  987. }
  988. }
  989. return $numeric_postcode;
  990. }
  991. }
  992. /**
  993. * Format the stock amount ready for display based on settings.
  994. *
  995. * @since 3.0.0
  996. * @param WC_Product $product Product object for which the stock you need to format.
  997. * @return string
  998. */
  999. function wc_format_stock_for_display( $product ) {
  1000. $display = __( 'In stock', 'woocommerce' );
  1001. $stock_amount = $product->get_stock_quantity();
  1002. switch ( get_option( 'woocommerce_stock_format' ) ) {
  1003. case 'low_amount':
  1004. if ( $stock_amount <= get_option( 'woocommerce_notify_low_stock_amount' ) ) {
  1005. /* translators: %s: stock amount */
  1006. $display = sprintf( __( 'Only %s left in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
  1007. }
  1008. break;
  1009. case '':
  1010. /* translators: %s: stock amount */
  1011. $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
  1012. break;
  1013. }
  1014. if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
  1015. $display .= ' ' . __( '(can be backordered)', 'woocommerce' );
  1016. }
  1017. return $display;
  1018. }
  1019. /**
  1020. * Format the stock quantity ready for display.
  1021. *
  1022. * @since 3.0.0
  1023. * @param int $stock_quantity Stock quantity.
  1024. * @param WC_Product $product Product instance so that we can pass through the filters.
  1025. * @return string
  1026. */
  1027. function wc_format_stock_quantity_for_display( $stock_quantity, $product ) {
  1028. return apply_filters( 'woocommerce_format_stock_quantity', $stock_quantity, $product );
  1029. }
  1030. /**
  1031. * Format a sale price for display.
  1032. *
  1033. * @since 3.0.0
  1034. * @param string $regular_price Regular price.
  1035. * @param string $sale_price Sale price.
  1036. * @return string
  1037. */
  1038. function wc_format_sale_price( $regular_price, $sale_price ) {
  1039. $price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</ins>';
  1040. return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );
  1041. }
  1042. /**
  1043. * Format a price range for display.
  1044. *
  1045. * @param string $from Price from.
  1046. * @param string $to Price to.
  1047. * @return string
  1048. */
  1049. function wc_format_price_range( $from, $to ) {
  1050. /* translators: 1: price from 2: price to */
  1051. $price = sprintf( _x( '%1$s &ndash; %2$s', 'Price range: from-to', 'woocommerce' ), is_numeric( $from ) ? wc_price( $from ) : $from, is_numeric( $to ) ? wc_price( $to ) : $to );
  1052. return apply_filters( 'woocommerce_format_price_range', $price, $from, $to );
  1053. }
  1054. /**
  1055. * Format a weight for display.
  1056. *
  1057. * @since 3.0.0
  1058. * @param float $weight Weight.
  1059. * @return string
  1060. */
  1061. function wc_format_weight( $weight ) {
  1062. $weight_string = wc_format_localized_decimal( $weight );
  1063. if ( ! empty( $weight_string ) ) {
  1064. $weight_string .= ' ' . get_option( 'woocommerce_weight_unit' );
  1065. } else {
  1066. $weight_string = __( 'N/A', 'woocommerce' );
  1067. }
  1068. return apply_filters( 'woocommerce_format_weight', $weight_string, $weight );
  1069. }
  1070. /**
  1071. * Format dimensions for display.
  1072. *
  1073. * @since 3.0.0
  1074. * @param array $dimensions Array of dimensions.
  1075. * @return string
  1076. */
  1077. function wc_format_dimensions( $dimensions ) {
  1078. $dimension_string = implode( ' x ', array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) ) );
  1079. if ( ! empty( $dimension_string ) ) {
  1080. $dimension_string .= ' ' . get_option( 'woocommerce_dimension_unit' );
  1081. } else {
  1082. $dimension_string = __( 'N/A', 'woocommerce' );
  1083. }
  1084. return apply_filters( 'woocommerce_format_dimensions', $dimension_string, $dimensions );
  1085. }
  1086. /**
  1087. * Format a date for output.
  1088. *
  1089. * @since 3.0.0
  1090. * @param WC_DateTime $date Instance of WC_DateTime.
  1091. * @param string $format Data format.
  1092. * Defaults to the wc_date_format function if not set.
  1093. * @return string
  1094. */
  1095. function wc_format_datetime( $date, $format = '' ) {
  1096. if ( ! $format ) {
  1097. $format = wc_date_format();
  1098. }
  1099. if ( ! is_a( $date, 'WC_DateTime' ) ) {
  1100. return '';
  1101. }
  1102. return $date->date_i18n( $format );
  1103. }
  1104. /**
  1105. * Process oEmbeds.
  1106. *
  1107. * @since 3.1.0
  1108. * @param string $content Content.
  1109. * @return string
  1110. */
  1111. function wc_do_oembeds( $content ) {
  1112. global $wp_embed;
  1113. $content = $wp_embed->autoembed( $content );
  1114. return $content;
  1115. }
  1116. /**
  1117. * Get part of a string before :.
  1118. *
  1119. * Used for example in shipping methods ids where they take the format
  1120. * method_id:instance_id
  1121. *
  1122. * @since 3.2.0
  1123. * @param string $string String to extract.
  1124. * @return string
  1125. */
  1126. function wc_get_string_before_colon( $string ) {
  1127. return trim( current( explode( ':', (string) $string ) ) );
  1128. }
  1129. /**
  1130. * Array merge and sum function.
  1131. *
  1132. * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
  1133. *
  1134. * @since 3.2.0
  1135. * @return array
  1136. */
  1137. function wc_array_merge_recursive_numeric() {
  1138. $arrays = func_get_args();
  1139. // If there's only one array, it's already merged.
  1140. if ( 1 === count( $arrays ) ) {
  1141. return $arrays[0];
  1142. }
  1143. // Remove any items in $arrays that are NOT arrays.
  1144. foreach ( $arrays as $key => $array ) {
  1145. if ( ! is_array( $array ) ) {
  1146. unset( $arrays[ $key ] );
  1147. }
  1148. }
  1149. // We start by setting the first array as our final array.
  1150. // We will merge all other arrays with this one.
  1151. $final = array_shift( $arrays );
  1152. foreach ( $arrays as $b ) {
  1153. foreach ( $final as $key => $value ) {
  1154. // If $key does not exist in $b, then it is unique and can be safely merged.
  1155. if ( ! isset( $b[ $key ] ) ) {
  1156. $final[ $key ] = $value;
  1157. } else {
  1158. // If $key is present in $b, then we need to merge and sum numeric values in both.
  1159. if ( is_numeric( $value ) && is_numeric( $b[ $key ] ) ) {
  1160. // If both values for these keys are numeric, we sum them.
  1161. $final[ $key ] = $value + $b[ $key ];
  1162. } elseif ( is_array( $value ) && is_array( $b[ $key ] ) ) {
  1163. // If both values are arrays, we recursively call ourself.
  1164. $final[ $key ] = wc_array_merge_recursive_numeric( $value, $b[ $key ] );
  1165. } else {
  1166. // If both keys exist but differ in type, then we cannot merge them.
  1167. // In this scenario, we will $b's value for $key is used.
  1168. $final[ $key ] = $b[ $key ];
  1169. }
  1170. }
  1171. }
  1172. // Finally, we need to merge any keys that exist only in $b.
  1173. foreach ( $b as $key => $value ) {
  1174. if ( ! isset( $final[ $key ] ) ) {
  1175. $final[ $key ] = $value;
  1176. }
  1177. }
  1178. }
  1179. return $final;
  1180. }
  1181. /**
  1182. * Implode and escape HTML attributes for output.
  1183. *
  1184. * @since 3.3.0
  1185. * @param array $raw_attributes Attribute name value pairs.
  1186. * @return string
  1187. */
  1188. function wc_implode_html_attributes( $raw_attributes ) {
  1189. $attributes = array();
  1190. foreach ( $raw_attributes as $name => $value ) {
  1191. $attributes[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
  1192. }
  1193. return implode( ' ', $attributes );
  1194. }
  1195. /**
  1196. * Parse a relative date option from the settings API into a standard format.
  1197. *
  1198. * @since 3.4.0
  1199. * @param mixed $raw_value Value stored in DB.
  1200. * @return array Nicely formatted array with number and unit values.
  1201. */
  1202. function wc_parse_relative_date_option( $raw_value ) {
  1203. $periods = array(
  1204. 'days' => __( 'Day(s)', 'woocommerce' ),
  1205. 'weeks' => __( 'Week(s)', 'woocommerce' ),
  1206. 'months' => __( 'Month(s)', 'woocommerce' ),
  1207. 'years' => __( 'Year(s)', 'woocommerce' ),
  1208. );
  1209. $value = wp_parse_args( (array) $raw_value, array(
  1210. 'number' => '',
  1211. 'unit' => 'days',
  1212. ) );
  1213. $value['number'] = ! empty( $value['number'] ) ? absint( $value['number'] ) : '';
  1214. if ( ! in_array( $value['unit'], array_keys( $periods ), true ) ) {
  1215. $value['unit'] = 'days';
  1216. }
  1217. return $value;
  1218. }