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0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / includes / wc-formatting-functions.php
woocommerce / includes Last commit date
abstracts 2 years ago admin 2 years ago blocks 5 years ago cli 3 years ago customizer 3 years ago data-stores 2 years ago emails 2 years ago export 2 years ago gateways 2 years ago import 3 years ago integrations 4 years ago interfaces 3 years ago legacy 2 years ago libraries 3 years ago log-handlers 4 years ago payment-tokens 5 years ago queue 4 years ago react-admin 2 years ago rest-api 3 years ago shipping 2 years ago shortcodes 2 years ago theme-support 3 years ago tracks 2 years ago traits 5 years ago walkers 5 years ago wccom-site 2 years ago widgets 3 years ago class-wc-ajax.php 2 years ago class-wc-api.php 4 years ago class-wc-auth.php 4 years ago class-wc-autoloader.php 5 years ago class-wc-background-emailer.php 5 years ago class-wc-background-updater.php 5 years ago class-wc-breadcrumb.php 5 years ago class-wc-cache-helper.php 3 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 3 years ago class-wc-cart-totals.php 2 years ago class-wc-cart.php 3 years ago class-wc-checkout.php 3 years ago class-wc-cli.php 3 years ago class-wc-comments.php 3 years ago class-wc-countries.php 2 years ago class-wc-coupon.php 3 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 4 years ago class-wc-customer.php 3 years ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 3 years ago class-wc-datetime.php 4 years ago class-wc-deprecated-action-hooks.php 8 years ago class-wc-deprecated-filter-hooks.php 3 years ago class-wc-discounts.php 3 years ago class-wc-download-handler.php 3 years ago class-wc-emails.php 3 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 3 years ago class-wc-frontend-scripts.php 3 years ago class-wc-geo-ip.php 4 years ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 3 years ago class-wc-https.php 2 years ago class-wc-install.php 2 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 4 years ago class-wc-meta-data.php 4 years ago class-wc-order-factory.php 3 years ago class-wc-order-item-coupon.php 4 years ago class-wc-order-item-fee.php 4 years ago class-wc-order-item-meta.php 4 years ago class-wc-order-item-product.php 4 years ago class-wc-order-item-shipping.php 4 years ago class-wc-order-item-tax.php 4 years ago class-wc-order-item.php 4 years ago class-wc-order-query.php 4 years ago class-wc-order-refund.php 2 years ago class-wc-order.php 2 years ago class-wc-payment-gateways.php 4 years ago class-wc-payment-tokens.php 3 years ago class-wc-post-data.php 3 years ago class-wc-post-types.php 3 years ago class-wc-privacy-background-process.php 5 years ago class-wc-privacy-erasers.php 4 years ago class-wc-privacy-exporters.php 4 years ago class-wc-privacy.php 2 years ago class-wc-product-attribute.php 4 years ago class-wc-product-download.php 4 years ago class-wc-product-external.php 5 years ago class-wc-product-factory.php 5 years ago class-wc-product-grouped.php 8 years ago class-wc-product-query.php 5 years ago class-wc-product-simple.php 3 years ago class-wc-product-variable.php 3 years ago class-wc-product-variation.php 4 years ago class-wc-query.php 3 years ago class-wc-rate-limiter.php 4 years ago class-wc-regenerate-images-request.php 3 years ago class-wc-regenerate-images.php 3 years ago class-wc-register-wp-admin-settings.php 4 years ago class-wc-rest-authentication.php 3 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 2 years ago class-wc-shipping-rate.php 3 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 4 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 3 years ago class-wc-tax.php 2 years ago class-wc-template-loader.php 2 years ago class-wc-tracker.php 2 years ago class-wc-validation.php 3 years ago class-wc-webhook.php 3 years ago class-woocommerce.php 2 years ago wc-account-functions.php 3 years ago wc-attribute-functions.php 3 years ago wc-cart-functions.php 3 years ago wc-conditional-functions.php 3 years ago wc-core-functions.php 2 years ago wc-coupon-functions.php 3 years ago wc-deprecated-functions.php 3 years ago wc-formatting-functions.php 2 years ago wc-notice-functions.php 3 years ago wc-order-functions.php 2 years ago wc-order-item-functions.php 3 years ago wc-page-functions.php 2 years ago wc-product-functions.php 3 years ago wc-rest-functions.php 3 years ago wc-stock-functions.php 3 years ago wc-template-functions.php 2 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 3 years ago wc-update-functions.php 2 years ago wc-user-functions.php 2 years ago wc-webhook-functions.php 4 years ago wc-widget-functions.php 5 years ago
wc-formatting-functions.php
1561 lines
1 <?php
2 /**
3 * WooCommerce Formatting
4 *
5 * Functions for formatting data.
6 *
7 * @package WooCommerce\Functions
8 * @version 2.1.0
9 */
10
11 use Automattic\WooCommerce\Utilities\I18nUtil;
12 use Automattic\WooCommerce\Utilities\NumberUtil;
13
14 defined( 'ABSPATH' ) || exit;
15
16 // Once WooCommerce requires PHP 7.4, the "$x = $x ?? ''" constructs can be replaced with "$x ??= ''".
17
18 /**
19 * Converts a string (e.g. 'yes' or 'no') to a bool.
20 *
21 * @since 3.0.0
22 * @param string|bool $string String to convert. If a bool is passed it will be returned as-is.
23 * @return bool
24 */
25 function wc_string_to_bool( $string ) {
26 $string = $string ?? '';
27 return is_bool( $string ) ? $string : ( 'yes' === strtolower( $string ) || 1 === $string || 'true' === strtolower( $string ) || '1' === $string );
28 }
29
30 /**
31 * Converts a bool to a 'yes' or 'no'.
32 *
33 * @since 3.0.0
34 * @param bool|string $bool Bool to convert. If a string is passed it will first be converted to a bool.
35 * @return string
36 */
37 function wc_bool_to_string( $bool ) {
38 if ( ! is_bool( $bool ) ) {
39 $bool = wc_string_to_bool( $bool );
40 }
41 return true === $bool ? 'yes' : 'no';
42 }
43
44 /**
45 * Explode a string into an array by $delimiter and remove empty values.
46 *
47 * @since 3.0.0
48 * @param string $string String to convert.
49 * @param string $delimiter Delimiter, defaults to ','.
50 * @return array
51 */
52 function wc_string_to_array( $string, $delimiter = ',' ) {
53 $string = $string ?? '';
54 return is_array( $string ) ? $string : array_filter( explode( $delimiter, $string ) );
55 }
56
57 /**
58 * Sanitize taxonomy names. Slug format (no spaces, lowercase).
59 * Urldecode is used to reverse munging of UTF8 characters.
60 *
61 * @param string $taxonomy Taxonomy name.
62 * @return string
63 */
64 function wc_sanitize_taxonomy_name( $taxonomy ) {
65 return apply_filters( 'sanitize_taxonomy_name', urldecode( sanitize_title( urldecode( $taxonomy ?? '' ) ) ), $taxonomy );
66 }
67
68 /**
69 * Sanitize permalink values before insertion into DB.
70 *
71 * Cannot use wc_clean because it sometimes strips % chars and breaks the user's setting.
72 *
73 * @since 2.6.0
74 * @param string $value Permalink.
75 * @return string
76 */
77 function wc_sanitize_permalink( $value ) {
78 global $wpdb;
79
80 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value ?? '' );
81
82 if ( is_wp_error( $value ) ) {
83 $value = '';
84 }
85
86 $value = esc_url_raw( trim( $value ) );
87 $value = str_replace( 'http://', '', $value );
88 return untrailingslashit( $value );
89 }
90
91 /**
92 * Gets the filename part of a download URL.
93 *
94 * @param string $file_url File URL.
95 * @return string
96 */
97 function wc_get_filename_from_url( $file_url ) {
98 $parts = wp_parse_url( $file_url );
99 if ( isset( $parts['path'] ) ) {
100 return basename( $parts['path'] );
101 }
102 }
103
104 /**
105 * Normalise dimensions, unify to cm then convert to wanted unit value.
106 *
107 * Usage:
108 * wc_get_dimension( 55, 'in' );
109 * wc_get_dimension( 55, 'in', 'm' );
110 *
111 * @param int|float $dimension Dimension.
112 * @param string $to_unit Unit to convert to.
113 * Options: 'in', 'mm', 'cm', 'm'.
114 * @param string $from_unit Unit to convert from.
115 * Defaults to ''.
116 * Options: 'in', 'mm', 'cm', 'm'.
117 * @return float
118 */
119 function wc_get_dimension( $dimension, $to_unit, $from_unit = '' ) {
120 $to_unit = strtolower( $to_unit );
121
122 if ( empty( $from_unit ) ) {
123 $from_unit = strtolower( get_option( 'woocommerce_dimension_unit' ) );
124 }
125
126 // Unify all units to cm first.
127 if ( $from_unit !== $to_unit ) {
128 switch ( $from_unit ) {
129 case 'in':
130 $dimension *= 2.54;
131 break;
132 case 'm':
133 $dimension *= 100;
134 break;
135 case 'mm':
136 $dimension *= 0.1;
137 break;
138 case 'yd':
139 $dimension *= 91.44;
140 break;
141 }
142
143 // Output desired unit.
144 switch ( $to_unit ) {
145 case 'in':
146 $dimension *= 0.3937;
147 break;
148 case 'm':
149 $dimension *= 0.01;
150 break;
151 case 'mm':
152 $dimension *= 10;
153 break;
154 case 'yd':
155 $dimension *= 0.010936133;
156 break;
157 }
158 }
159
160 return ( $dimension < 0 ) ? 0 : $dimension;
161 }
162
163 /**
164 * Normalise weights, unify to kg then convert to wanted unit value.
165 *
166 * Usage:
167 * wc_get_weight(55, 'kg');
168 * wc_get_weight(55, 'kg', 'lbs');
169 *
170 * @param int|float $weight Weight.
171 * @param string $to_unit Unit to convert to.
172 * Options: 'g', 'kg', 'lbs', 'oz'.
173 * @param string $from_unit Unit to convert from.
174 * Defaults to ''.
175 * Options: 'g', 'kg', 'lbs', 'oz'.
176 * @return float
177 */
178 function wc_get_weight( $weight, $to_unit, $from_unit = '' ) {
179 $weight = (float) $weight;
180 $to_unit = strtolower( $to_unit );
181
182 if ( empty( $from_unit ) ) {
183 $from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) );
184 }
185
186 // Unify all units to kg first.
187 if ( $from_unit !== $to_unit ) {
188 switch ( $from_unit ) {
189 case 'g':
190 $weight *= 0.001;
191 break;
192 case 'lbs':
193 $weight *= 0.453592;
194 break;
195 case 'oz':
196 $weight *= 0.0283495;
197 break;
198 }
199
200 // Output desired unit.
201 switch ( $to_unit ) {
202 case 'g':
203 $weight *= 1000;
204 break;
205 case 'lbs':
206 $weight *= 2.20462;
207 break;
208 case 'oz':
209 $weight *= 35.274;
210 break;
211 }
212 }
213
214 return ( $weight < 0 ) ? 0 : $weight;
215 }
216
217 /**
218 * Trim trailing zeros off prices.
219 *
220 * @param string|float|int $price Price.
221 * @return string
222 */
223 function wc_trim_zeros( $price ) {
224 return preg_replace( '/' . preg_quote( wc_get_price_decimal_separator(), '/' ) . '0++$/', '', $price ?? '' );
225 }
226
227 /**
228 * Round a tax amount.
229 *
230 * @param double $value Amount to round.
231 * @param int $precision DP to round. Defaults to wc_get_price_decimals.
232 * @return float
233 */
234 function wc_round_tax_total( $value, $precision = null ) {
235 $precision = is_null( $precision ) ? wc_get_price_decimals() : intval( $precision );
236
237 if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) {
238 $rounded_tax = NumberUtil::round( $value, $precision, wc_get_tax_rounding_mode() ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.round_modeFound
239 } elseif ( 2 === wc_get_tax_rounding_mode() ) {
240 $rounded_tax = wc_legacy_round_half_down( $value, $precision );
241 } else {
242 $rounded_tax = NumberUtil::round( $value, $precision );
243 }
244
245 return apply_filters( 'wc_round_tax_total', $rounded_tax, $value, $precision, WC_TAX_ROUNDING_MODE );
246 }
247
248 /**
249 * Round half down in PHP 5.2.
250 *
251 * @since 3.2.6
252 * @param float $value Value to round.
253 * @param int $precision Precision to round down to.
254 * @return float
255 */
256 function wc_legacy_round_half_down( $value, $precision ) {
257 $value = wc_float_to_string( $value ) ?? '';
258
259 if ( false !== strstr( $value, '.' ) ) {
260 $value = explode( '.', $value );
261
262 if ( strlen( $value[1] ) > $precision && substr( $value[1], -1 ) === '5' ) {
263 $value[1] = substr( $value[1], 0, -1 ) . '4';
264 }
265
266 $value = implode( '.', $value );
267 }
268
269 return NumberUtil::round( floatval( $value ), $precision );
270 }
271
272 /**
273 * Make a refund total negative.
274 *
275 * @param float $amount Refunded amount.
276 *
277 * @return float
278 */
279 function wc_format_refund_total( $amount ) {
280 return $amount * -1;
281 }
282
283 /**
284 * Format decimal numbers ready for DB storage.
285 *
286 * Sanitize, optionally remove decimals, and optionally round + trim off zeros.
287 *
288 * This function does not remove thousands - this should be done before passing a value to the function.
289 *
290 * @param float|string $number Expects either a float or a string with a decimal separator only (no thousands).
291 * @param mixed $dp number Number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding.
292 * @param bool $trim_zeros From end of string.
293 * @return string
294 */
295 function wc_format_decimal( $number, $dp = false, $trim_zeros = false ) {
296 $number = $number ?? '';
297
298 $locale = localeconv();
299 $decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
300
301 // Remove locale from string.
302 if ( ! is_float( $number ) ) {
303 $number = str_replace( $decimals, '.', $number );
304
305 // Convert multiple dots to just one.
306 $number = preg_replace( '/\.(?![^.]+$)|[^0-9.-]/', '', wc_clean( $number ) );
307 }
308
309 if ( false !== $dp ) {
310 $dp = intval( '' === $dp ? wc_get_price_decimals() : $dp );
311 $number = number_format( floatval( $number ), $dp, '.', '' );
312 } elseif ( is_float( $number ) ) {
313 // DP is false - don't use number format, just return a string using whatever is given. Remove scientific notation using sprintf.
314 $number = str_replace( $decimals, '.', sprintf( '%.' . wc_get_rounding_precision() . 'f', $number ) );
315 // We already had a float, so trailing zeros are not needed.
316 $trim_zeros = true;
317 }
318
319 if ( $trim_zeros && strstr( $number, '.' ) ) {
320 $number = rtrim( rtrim( $number, '0' ), '.' );
321 }
322
323 return $number;
324 }
325
326 /**
327 * Convert a float to a string without locale formatting which PHP adds when changing floats to strings.
328 *
329 * @param float $float Float value to format.
330 * @return string
331 */
332 function wc_float_to_string( $float ) {
333 if ( ! is_float( $float ) ) {
334 return $float;
335 }
336
337 $locale = localeconv();
338 $string = strval( $float );
339 $string = str_replace( $locale['decimal_point'], '.', $string );
340
341 return $string;
342 }
343
344 /**
345 * Format a price with WC Currency Locale settings.
346 *
347 * @param string $value Price to localize.
348 * @return string
349 */
350 function wc_format_localized_price( $value ) {
351 return apply_filters( 'woocommerce_format_localized_price', str_replace( '.', wc_get_price_decimal_separator(), strval( $value ) ), $value );
352 }
353
354 /**
355 * Format a decimal with the decimal separator for prices or PHP Locale settings.
356 *
357 * @param string $value Decimal to localize.
358 * @return string
359 */
360 function wc_format_localized_decimal( $value ) {
361 $locale = localeconv();
362 $decimal_point = isset( $locale['decimal_point'] ) ? $locale['decimal_point'] : '.';
363 $decimal = ( ! empty( wc_get_price_decimal_separator() ) ) ? wc_get_price_decimal_separator() : $decimal_point;
364 return apply_filters( 'woocommerce_format_localized_decimal', str_replace( '.', $decimal, strval( $value ) ), $value );
365 }
366
367 /**
368 * Format a coupon code.
369 *
370 * @since 3.0.0
371 * @param string $value Coupon code to format.
372 * @return string
373 */
374 function wc_format_coupon_code( $value ) {
375 return apply_filters( 'woocommerce_coupon_code', $value );
376 }
377
378 /**
379 * Sanitize a coupon code.
380 *
381 * Uses sanitize_post_field since coupon codes are stored as
382 * post_titles - the sanitization and escaping must match.
383 *
384 * @since 3.6.0
385 * @param string $value Coupon code to format.
386 * @return string
387 */
388 function wc_sanitize_coupon_code( $value ) {
389 return wp_filter_kses( sanitize_post_field( 'post_title', $value ?? '', 0, 'db' ) );
390 }
391
392 /**
393 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
394 * Non-scalar values are ignored.
395 *
396 * @param string|array $var Data to sanitize.
397 * @return string|array
398 */
399 function wc_clean( $var ) {
400 if ( is_array( $var ) ) {
401 return array_map( 'wc_clean', $var );
402 } else {
403 return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
404 }
405 }
406
407 /**
408 * Function wp_check_invalid_utf8 with recursive array support.
409 *
410 * @param string|array $var Data to sanitize.
411 * @return string|array
412 */
413 function wc_check_invalid_utf8( $var ) {
414 if ( is_array( $var ) ) {
415 return array_map( 'wc_check_invalid_utf8', $var );
416 } else {
417 return wp_check_invalid_utf8( $var );
418 }
419 }
420
421 /**
422 * Run wc_clean over posted textarea but maintain line breaks.
423 *
424 * @since 3.0.0
425 * @param string $var Data to sanitize.
426 * @return string
427 */
428 function wc_sanitize_textarea( $var ) {
429 return implode( "\n", array_map( 'wc_clean', explode( "\n", $var ?? '' ) ) );
430 }
431
432 /**
433 * Sanitize a string destined to be a tooltip.
434 *
435 * @since 2.3.10 Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
436 * @param string $var Data to sanitize.
437 * @return string
438 */
439 function wc_sanitize_tooltip( $var ) {
440 return htmlspecialchars(
441 wp_kses(
442 html_entity_decode( $var ?? '' ),
443 array(
444 'br' => array(),
445 'em' => array(),
446 'strong' => array(),
447 'small' => array(),
448 'span' => array(),
449 'ul' => array(),
450 'li' => array(),
451 'ol' => array(),
452 'p' => array(),
453 )
454 )
455 );
456 }
457
458 /**
459 * Merge two arrays.
460 *
461 * @param array $a1 First array to merge.
462 * @param array $a2 Second array to merge.
463 * @return array
464 */
465 function wc_array_overlay( $a1, $a2 ) {
466 foreach ( $a1 as $k => $v ) {
467 if ( ! array_key_exists( $k, $a2 ) ) {
468 continue;
469 }
470 if ( is_array( $v ) && is_array( $a2[ $k ] ) ) {
471 $a1[ $k ] = wc_array_overlay( $v, $a2[ $k ] );
472 } else {
473 $a1[ $k ] = $a2[ $k ];
474 }
475 }
476 return $a1;
477 }
478
479 /**
480 * Formats a stock amount by running it through a filter.
481 *
482 * @param int|float $amount Stock amount.
483 * @return int|float
484 */
485 function wc_stock_amount( $amount ) {
486 return apply_filters( 'woocommerce_stock_amount', $amount );
487 }
488
489 /**
490 * Get the price format depending on the currency position.
491 *
492 * @return string
493 */
494 function get_woocommerce_price_format() {
495 $currency_pos = get_option( 'woocommerce_currency_pos' );
496 $format = '%1$s%2$s';
497
498 switch ( $currency_pos ) {
499 case 'left':
500 $format = '%1$s%2$s';
501 break;
502 case 'right':
503 $format = '%2$s%1$s';
504 break;
505 case 'left_space':
506 $format = '%1$s&nbsp;%2$s';
507 break;
508 case 'right_space':
509 $format = '%2$s&nbsp;%1$s';
510 break;
511 }
512
513 return apply_filters( 'woocommerce_price_format', $format, $currency_pos );
514 }
515
516 /**
517 * Return the thousand separator for prices.
518 *
519 * @since 2.3
520 * @return string
521 */
522 function wc_get_price_thousand_separator() {
523 return stripslashes( apply_filters( 'wc_get_price_thousand_separator', get_option( 'woocommerce_price_thousand_sep' ) ) );
524 }
525
526 /**
527 * Return the decimal separator for prices.
528 *
529 * @since 2.3
530 * @return string
531 */
532 function wc_get_price_decimal_separator() {
533 $separator = apply_filters( 'wc_get_price_decimal_separator', get_option( 'woocommerce_price_decimal_sep' ) );
534 return $separator ? stripslashes( $separator ) : '.';
535 }
536
537 /**
538 * Return the number of decimals after the decimal point.
539 *
540 * @since 2.3
541 * @return int
542 */
543 function wc_get_price_decimals() {
544 return absint( apply_filters( 'wc_get_price_decimals', get_option( 'woocommerce_price_num_decimals', 2 ) ) );
545 }
546
547 /**
548 * Format the price with a currency symbol.
549 *
550 * @param float $price Raw price.
551 * @param array $args Arguments to format a price {
552 * Array of arguments.
553 * Defaults to empty array.
554 *
555 * @type bool $ex_tax_label Adds exclude tax label.
556 * Defaults to false.
557 * @type string $currency Currency code.
558 * Defaults to empty string (Use the result from get_woocommerce_currency()).
559 * @type string $decimal_separator Decimal separator.
560 * Defaults the result of wc_get_price_decimal_separator().
561 * @type string $thousand_separator Thousand separator.
562 * Defaults the result of wc_get_price_thousand_separator().
563 * @type string $decimals Number of decimals.
564 * Defaults the result of wc_get_price_decimals().
565 * @type string $price_format Price format depending on the currency position.
566 * Defaults the result of get_woocommerce_price_format().
567 * }
568 * @return string
569 */
570 function wc_price( $price, $args = array() ) {
571 $args = apply_filters(
572 'wc_price_args',
573 wp_parse_args(
574 $args,
575 array(
576 'ex_tax_label' => false,
577 'currency' => '',
578 'decimal_separator' => wc_get_price_decimal_separator(),
579 'thousand_separator' => wc_get_price_thousand_separator(),
580 'decimals' => wc_get_price_decimals(),
581 'price_format' => get_woocommerce_price_format(),
582 )
583 )
584 );
585
586 $original_price = $price;
587
588 // Convert to float to avoid issues on PHP 8.
589 $price = (float) $price;
590
591 $unformatted_price = $price;
592 $negative = $price < 0;
593
594 /**
595 * Filter raw price.
596 *
597 * @param float $raw_price Raw price.
598 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
599 */
600 $price = apply_filters( 'raw_woocommerce_price', $negative ? $price * -1 : $price, $original_price );
601
602 /**
603 * Filter formatted price.
604 *
605 * @param float $formatted_price Formatted price.
606 * @param float $price Unformatted price.
607 * @param int $decimals Number of decimals.
608 * @param string $decimal_separator Decimal separator.
609 * @param string $thousand_separator Thousand separator.
610 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
611 */
612 $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'], $original_price );
613
614 if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $args['decimals'] > 0 ) {
615 $price = wc_trim_zeros( $price );
616 }
617
618 $formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $args['currency'] ) . '</span>', $price );
619 $return = '<span class="woocommerce-Price-amount amount"><bdi>' . $formatted_price . '</bdi></span>';
620
621 if ( $args['ex_tax_label'] && wc_tax_enabled() ) {
622 $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
623 }
624
625 /**
626 * Filters the string of price markup.
627 *
628 * @param string $return Price HTML markup.
629 * @param string $price Formatted price.
630 * @param array $args Pass on the args.
631 * @param float $unformatted_price Price as float to allow plugins custom formatting. Since 3.2.0.
632 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
633 */
634 return apply_filters( 'wc_price', $return, $price, $args, $unformatted_price, $original_price );
635 }
636
637 /**
638 * Notation to numbers.
639 *
640 * This function transforms the php.ini notation for numbers (like '2M') to an integer.
641 *
642 * @param string $size Size value.
643 * @return int
644 */
645 function wc_let_to_num( $size ) {
646 $size = $size ?? '';
647
648 $l = substr( $size, -1 );
649 $ret = (int) substr( $size, 0, -1 );
650 switch ( strtoupper( $l ) ) {
651 case 'P':
652 $ret *= 1024;
653 // No break.
654 case 'T':
655 $ret *= 1024;
656 // No break.
657 case 'G':
658 $ret *= 1024;
659 // No break.
660 case 'M':
661 $ret *= 1024;
662 // No break.
663 case 'K':
664 $ret *= 1024;
665 // No break.
666 }
667 return $ret;
668 }
669
670 /**
671 * WooCommerce Date Format - Allows to change date format for everything WooCommerce.
672 *
673 * @return string
674 */
675 function wc_date_format() {
676 $date_format = get_option( 'date_format' );
677 if ( empty( $date_format ) ) {
678 // Return default date format if the option is empty.
679 $date_format = 'F j, Y';
680 }
681 return apply_filters( 'woocommerce_date_format', $date_format );
682 }
683
684 /**
685 * WooCommerce Time Format - Allows to change time format for everything WooCommerce.
686 *
687 * @return string
688 */
689 function wc_time_format() {
690 $time_format = get_option( 'time_format' );
691 if ( empty( $time_format ) ) {
692 // Return default time format if the option is empty.
693 $time_format = 'g:i a';
694 }
695 return apply_filters( 'woocommerce_time_format', $time_format );
696 }
697
698 /**
699 * Convert mysql datetime to PHP timestamp, forcing UTC. Wrapper for strtotime.
700 *
701 * Based on wcs_strtotime_dark_knight() from WC Subscriptions by Prospress.
702 *
703 * @since 3.0.0
704 * @param string $time_string Time string.
705 * @param int|null $from_timestamp Timestamp to convert from.
706 * @return int
707 */
708 function wc_string_to_timestamp( $time_string, $from_timestamp = null ) {
709 $time_string = $time_string ?? '';
710
711 $original_timezone = date_default_timezone_get();
712
713 // @codingStandardsIgnoreStart
714 date_default_timezone_set( 'UTC' );
715
716 if ( null === $from_timestamp ) {
717 $next_timestamp = strtotime( $time_string );
718 } else {
719 $next_timestamp = strtotime( $time_string, $from_timestamp );
720 }
721
722 date_default_timezone_set( $original_timezone );
723 // @codingStandardsIgnoreEnd
724
725 return $next_timestamp;
726 }
727
728 /**
729 * Convert a date string to a WC_DateTime.
730 *
731 * @since 3.1.0
732 * @param string $time_string Time string.
733 * @return WC_DateTime
734 */
735 function wc_string_to_datetime( $time_string ) {
736 $time_string = $time_string ?? '';
737
738 // Strings are defined in local WP timezone. Convert to UTC.
739 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 ) ) {
740 $offset = ! empty( $date_bits[7] ) ? iso8601_timezone_to_offset( $date_bits[7] ) : wc_timezone_offset();
741 $timestamp = gmmktime( $date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1] ) - $offset;
742 } else {
743 $timestamp = wc_string_to_timestamp( get_gmt_from_date( gmdate( 'Y-m-d H:i:s', wc_string_to_timestamp( $time_string ) ) ) );
744 }
745 $datetime = new WC_DateTime( "@{$timestamp}", new DateTimeZone( 'UTC' ) );
746
747 // Set local timezone or offset.
748 if ( get_option( 'timezone_string' ) ) {
749 $datetime->setTimezone( new DateTimeZone( wc_timezone_string() ) );
750 } else {
751 $datetime->set_utc_offset( wc_timezone_offset() );
752 }
753
754 return $datetime;
755 }
756
757 /**
758 * WooCommerce Timezone - helper to retrieve the timezone string for a site until.
759 * a WP core method exists (see https://core.trac.wordpress.org/ticket/24730).
760 *
761 * Adapted from https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
762 *
763 * @since 2.1
764 * @return string PHP timezone string for the site
765 */
766 function wc_timezone_string() {
767 // Added in WordPress 5.3 Ref https://developer.wordpress.org/reference/functions/wp_timezone_string/.
768 if ( function_exists( 'wp_timezone_string' ) ) {
769 return wp_timezone_string();
770 }
771
772 // If site timezone string exists, return it.
773 $timezone = get_option( 'timezone_string' );
774 if ( $timezone ) {
775 return $timezone;
776 }
777
778 // Get UTC offset, if it isn't set then return UTC.
779 $utc_offset = floatval( get_option( 'gmt_offset', 0 ) );
780 if ( ! is_numeric( $utc_offset ) || 0.0 === $utc_offset ) {
781 return 'UTC';
782 }
783
784 // Adjust UTC offset from hours to seconds.
785 $utc_offset = (int) ( $utc_offset * 3600 );
786
787 // Attempt to guess the timezone string from the UTC offset.
788 $timezone = timezone_name_from_abbr( '', $utc_offset );
789 if ( $timezone ) {
790 return $timezone;
791 }
792
793 // Last try, guess timezone string manually.
794 foreach ( timezone_abbreviations_list() as $abbr ) {
795 foreach ( $abbr as $city ) {
796 // WordPress restrict the use of date(), since it's affected by timezone settings, but in this case is just what we need to guess the correct timezone.
797 if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
798 return $city['timezone_id'];
799 }
800 }
801 }
802
803 // Fallback to UTC.
804 return 'UTC';
805 }
806
807 /**
808 * Get timezone offset in seconds.
809 *
810 * @since 3.0.0
811 * @return float
812 */
813 function wc_timezone_offset() {
814 $timezone = get_option( 'timezone_string' );
815
816 if ( $timezone ) {
817 $timezone_object = new DateTimeZone( $timezone );
818 return $timezone_object->getOffset( new DateTime( 'now' ) );
819 } else {
820 return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
821 }
822 }
823
824 /**
825 * Callback which can flatten post meta (gets the first value if it's an array).
826 *
827 * @since 3.0.0
828 * @param array $value Value to flatten.
829 * @return mixed
830 */
831 function wc_flatten_meta_callback( $value ) {
832 return is_array( $value ) ? current( $value ) : $value;
833 }
834
835 if ( ! function_exists( 'wc_rgb_from_hex' ) ) {
836
837 /**
838 * Convert RGB to HEX.
839 *
840 * @param mixed $color Color.
841 *
842 * @return array
843 */
844 function wc_rgb_from_hex( $color ) {
845 $color = str_replace( '#', '', $color ?? '000' );
846 // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF".
847 $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
848
849 $rgb = array();
850 $rgb['R'] = hexdec( $color[0] . $color[1] );
851 $rgb['G'] = hexdec( $color[2] . $color[3] );
852 $rgb['B'] = hexdec( $color[4] . $color[5] );
853
854 return $rgb;
855 }
856 }
857
858 if ( ! function_exists( 'wc_hex_darker' ) ) {
859
860 /**
861 * Make HEX color darker.
862 *
863 * @param mixed $color Color.
864 * @param int $factor Darker factor.
865 * Defaults to 30.
866 * @return string
867 */
868 function wc_hex_darker( $color, $factor = 30 ) {
869 $base = wc_rgb_from_hex( $color );
870 $color = '#';
871
872 foreach ( $base as $k => $v ) {
873 $amount = $v / 100;
874 $amount = NumberUtil::round( $amount * $factor );
875 $new_decimal = $v - $amount;
876
877 $new_hex_component = dechex( $new_decimal );
878 if ( strlen( $new_hex_component ) < 2 ) {
879 $new_hex_component = '0' . $new_hex_component;
880 }
881 $color .= $new_hex_component;
882 }
883
884 return $color;
885 }
886 }
887
888 if ( ! function_exists( 'wc_hex_lighter' ) ) {
889
890 /**
891 * Make HEX color lighter.
892 *
893 * @param mixed $color Color.
894 * @param int $factor Lighter factor.
895 * Defaults to 30.
896 * @return string
897 */
898 function wc_hex_lighter( $color, $factor = 30 ) {
899 $base = wc_rgb_from_hex( $color );
900 $color = '#';
901
902 foreach ( $base as $k => $v ) {
903 $amount = 255 - $v;
904 $amount = $amount / 100;
905 $amount = NumberUtil::round( $amount * $factor );
906 $new_decimal = $v + $amount;
907
908 $new_hex_component = dechex( $new_decimal );
909 if ( strlen( $new_hex_component ) < 2 ) {
910 $new_hex_component = '0' . $new_hex_component;
911 }
912 $color .= $new_hex_component;
913 }
914
915 return $color;
916 }
917 }
918
919 if ( ! function_exists( 'wc_hex_is_light' ) ) {
920
921 /**
922 * Determine whether a hex color is light.
923 *
924 * @param mixed $color Color.
925 * @return bool True if a light color.
926 */
927 function wc_hex_is_light( $color ) {
928 $hex = str_replace( '#', '', $color ?? '' );
929
930 $c_r = hexdec( substr( $hex, 0, 2 ) );
931 $c_g = hexdec( substr( $hex, 2, 2 ) );
932 $c_b = hexdec( substr( $hex, 4, 2 ) );
933
934 $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
935
936 return $brightness > 155;
937 }
938 }
939
940 if ( ! function_exists( 'wc_light_or_dark' ) ) {
941
942 /**
943 * Detect if we should use a light or dark color on a background color.
944 *
945 * @param mixed $color Color.
946 * @param string $dark Darkest reference.
947 * Defaults to '#000000'.
948 * @param string $light Lightest reference.
949 * Defaults to '#FFFFFF'.
950 * @return string
951 */
952 function wc_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
953 return wc_hex_is_light( $color ) ? $dark : $light;
954 }
955 }
956
957 if ( ! function_exists( 'wc_format_hex' ) ) {
958
959 /**
960 * Format string as hex.
961 *
962 * @param string $hex HEX color.
963 * @return string|null
964 */
965 function wc_format_hex( $hex ) {
966 $hex = trim( str_replace( '#', '', $hex ?? '' ) );
967
968 if ( strlen( $hex ) === 3 ) {
969 $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
970 }
971
972 return $hex ? '#' . $hex : null;
973 }
974 }
975
976 /**
977 * Format the postcode according to the country and length of the postcode.
978 *
979 * @param string $postcode Unformatted postcode.
980 * @param string $country Base country.
981 * @return string
982 */
983 function wc_format_postcode( $postcode, $country ) {
984 $postcode = wc_normalize_postcode( $postcode ?? '' );
985
986 switch ( $country ) {
987 case 'CA':
988 case 'GB':
989 $postcode = substr_replace( $postcode, ' ', -3, 0 );
990 break;
991 case 'IE':
992 $postcode = substr_replace( $postcode, ' ', 3, 0 );
993 break;
994 case 'BR':
995 case 'PL':
996 $postcode = substr_replace( $postcode, '-', -3, 0 );
997 break;
998 case 'JP':
999 $postcode = substr_replace( $postcode, '-', 3, 0 );
1000 break;
1001 case 'PT':
1002 $postcode = substr_replace( $postcode, '-', 4, 0 );
1003 break;
1004 case 'PR':
1005 case 'US':
1006 $postcode = rtrim( substr_replace( $postcode, '-', 5, 0 ), '-' );
1007 break;
1008 case 'NL':
1009 $postcode = substr_replace( $postcode, ' ', 4, 0 );
1010 break;
1011 case 'LV':
1012 if ( preg_match( '/(?:LV)?-?(\d+)/i', $postcode, $matches ) ) {
1013 $postcode = count( $matches ) >= 2 ? "LV-$matches[1]" : $postcode;
1014 }
1015 break;
1016 case 'DK':
1017 $postcode = preg_replace( '/^(DK)(.+)$/', '${1}-${2}', $postcode );
1018 break;
1019 }
1020
1021 return apply_filters( 'woocommerce_format_postcode', trim( $postcode ), $country );
1022 }
1023
1024 /**
1025 * Normalize postcodes.
1026 *
1027 * Remove spaces and convert characters to uppercase.
1028 *
1029 * @since 2.6.0
1030 * @param string $postcode Postcode.
1031 * @return string
1032 */
1033 function wc_normalize_postcode( $postcode ) {
1034 return preg_replace( '/[\s\-]/', '', trim( wc_strtoupper( $postcode ?? '' ) ) );
1035 }
1036
1037 /**
1038 * Format phone numbers.
1039 *
1040 * @param string $phone Phone number.
1041 * @return string
1042 */
1043 function wc_format_phone_number( $phone ) {
1044 $phone = $phone ?? '';
1045
1046 if ( ! WC_Validation::is_phone( $phone ) ) {
1047 return '';
1048 }
1049 return preg_replace( '/[^0-9\+\-\(\)\s]/', '-', preg_replace( '/[\x00-\x1F\x7F-\xFF]/', '', $phone ) );
1050 }
1051
1052 /**
1053 * Sanitize phone number.
1054 * Allows only numbers and "+" (plus sign).
1055 *
1056 * @since 3.6.0
1057 * @param string $phone Phone number.
1058 * @return string
1059 */
1060 function wc_sanitize_phone_number( $phone ) {
1061 return preg_replace( '/[^\d+]/', '', $phone ?? '' );
1062 }
1063
1064 /**
1065 * Wrapper for mb_strtoupper which see's if supported first.
1066 *
1067 * @since 3.1.0
1068 * @param string $string String to format.
1069 * @return string
1070 */
1071 function wc_strtoupper( $string ) {
1072 $string = $string ?? '';
1073 return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $string ) : strtoupper( $string );
1074 }
1075
1076 /**
1077 * Make a string lowercase.
1078 * Try to use mb_strtolower() when available.
1079 *
1080 * @since 2.3
1081 * @param string $string String to format.
1082 * @return string
1083 */
1084 function wc_strtolower( $string ) {
1085 $string = $string ?? '';
1086 return function_exists( 'mb_strtolower' ) ? mb_strtolower( $string ) : strtolower( $string );
1087 }
1088
1089 /**
1090 * Trim a string and append a suffix.
1091 *
1092 * @param string $string String to trim.
1093 * @param integer $chars Amount of characters.
1094 * Defaults to 200.
1095 * @param string $suffix Suffix.
1096 * Defaults to '...'.
1097 * @return string
1098 */
1099 function wc_trim_string( $string, $chars = 200, $suffix = '...' ) {
1100 $string = $string ?? '';
1101
1102 if ( strlen( $string ) > $chars ) {
1103 if ( function_exists( 'mb_substr' ) ) {
1104 $string = mb_substr( $string, 0, ( $chars - mb_strlen( $suffix ) ) ) . $suffix;
1105 } else {
1106 $string = substr( $string, 0, ( $chars - strlen( $suffix ) ) ) . $suffix;
1107 }
1108 }
1109 return $string;
1110 }
1111
1112 /**
1113 * Format content to display shortcodes.
1114 *
1115 * @since 2.3.0
1116 * @param string $raw_string Raw string.
1117 * @return string
1118 */
1119 function wc_format_content( $raw_string ) {
1120 $raw_string = $raw_string ?? '';
1121 return apply_filters( 'woocommerce_format_content', apply_filters( 'woocommerce_short_description', $raw_string ), $raw_string );
1122 }
1123
1124 /**
1125 * Format product short description.
1126 * Adds support for Jetpack Markdown.
1127 *
1128 * @codeCoverageIgnore
1129 * @since 2.4.0
1130 * @param string $content Product short description.
1131 * @return string
1132 */
1133 function wc_format_product_short_description( $content ) {
1134 // Add support for Jetpack Markdown.
1135 if ( class_exists( 'WPCom_Markdown' ) ) {
1136 $markdown = WPCom_Markdown::get_instance();
1137
1138 return wpautop(
1139 $markdown->transform(
1140 $content,
1141 array(
1142 'unslash' => false,
1143 )
1144 )
1145 );
1146 }
1147
1148 return $content;
1149 }
1150
1151 /**
1152 * Formats curency symbols when saved in settings.
1153 *
1154 * @codeCoverageIgnore
1155 * @param string $value Option value.
1156 * @param array $option Option name.
1157 * @param string $raw_value Raw value.
1158 * @return string
1159 */
1160 function wc_format_option_price_separators( $value, $option, $raw_value ) {
1161 return wp_kses_post( $raw_value ?? '' );
1162 }
1163 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_decimal_sep', 'wc_format_option_price_separators', 10, 3 );
1164 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_thousand_sep', 'wc_format_option_price_separators', 10, 3 );
1165
1166 /**
1167 * Formats decimals when saved in settings.
1168 *
1169 * @codeCoverageIgnore
1170 * @param string $value Option value.
1171 * @param array $option Option name.
1172 * @param string $raw_value Raw value.
1173 * @return string
1174 */
1175 function wc_format_option_price_num_decimals( $value, $option, $raw_value ) {
1176 return is_null( $raw_value ) ? 2 : absint( $raw_value );
1177 }
1178 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_num_decimals', 'wc_format_option_price_num_decimals', 10, 3 );
1179
1180 /**
1181 * Formats hold stock option and sets cron event up.
1182 *
1183 * @codeCoverageIgnore
1184 * @param string $value Option value.
1185 * @param array $option Option name.
1186 * @param string $raw_value Raw value.
1187 * @return string
1188 */
1189 function wc_format_option_hold_stock_minutes( $value, $option, $raw_value ) {
1190 $value = ! empty( $raw_value ) ? absint( $raw_value ) : ''; // Allow > 0 or set to ''.
1191
1192 wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
1193
1194 if ( '' !== $value ) {
1195 $cancel_unpaid_interval = apply_filters( 'woocommerce_cancel_unpaid_orders_interval_minutes', absint( $value ) );
1196 wp_schedule_single_event( time() + ( absint( $cancel_unpaid_interval ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
1197 }
1198
1199 return $value;
1200 }
1201 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_hold_stock_minutes', 'wc_format_option_hold_stock_minutes', 10, 3 );
1202
1203 /**
1204 * Sanitize terms from an attribute text based.
1205 *
1206 * @since 2.4.5
1207 * @param string $term Term value.
1208 * @return string
1209 */
1210 function wc_sanitize_term_text_based( $term ) {
1211 return trim( wp_strip_all_tags( wp_unslash( $term ?? '' ) ) );
1212 }
1213
1214 if ( ! function_exists( 'wc_make_numeric_postcode' ) ) {
1215 /**
1216 * Make numeric postcode.
1217 *
1218 * Converts letters to numbers so we can do a simple range check on postcodes.
1219 * E.g. PE30 becomes 16050300 (P = 16, E = 05, 3 = 03, 0 = 00)
1220 *
1221 * @since 2.6.0
1222 * @param string $postcode Regular postcode.
1223 * @return string
1224 */
1225 function wc_make_numeric_postcode( $postcode ) {
1226 $postcode = str_replace( array( ' ', '-' ), '', $postcode ?? '' );
1227 $postcode_length = strlen( $postcode );
1228 $letters_to_numbers = array_merge( array( 0 ), range( 'A', 'Z' ) );
1229 $letters_to_numbers = array_flip( $letters_to_numbers );
1230 $numeric_postcode = '';
1231
1232 for ( $i = 0; $i < $postcode_length; $i ++ ) {
1233 if ( is_numeric( $postcode[ $i ] ) ) {
1234 $numeric_postcode .= str_pad( $postcode[ $i ], 2, '0', STR_PAD_LEFT );
1235 } elseif ( isset( $letters_to_numbers[ $postcode[ $i ] ] ) ) {
1236 $numeric_postcode .= str_pad( $letters_to_numbers[ $postcode[ $i ] ], 2, '0', STR_PAD_LEFT );
1237 } else {
1238 $numeric_postcode .= '00';
1239 }
1240 }
1241
1242 return $numeric_postcode;
1243 }
1244 }
1245
1246 /**
1247 * Format the stock amount ready for display based on settings.
1248 *
1249 * @since 3.0.0
1250 * @param WC_Product $product Product object for which the stock you need to format.
1251 * @return string
1252 */
1253 function wc_format_stock_for_display( $product ) {
1254 $display = __( 'In stock', 'woocommerce' );
1255 $stock_amount = $product->get_stock_quantity();
1256
1257 switch ( get_option( 'woocommerce_stock_format' ) ) {
1258 case 'low_amount':
1259 if ( $stock_amount <= wc_get_low_stock_amount( $product ) ) {
1260 /* translators: %s: stock amount */
1261 $display = sprintf( __( 'Only %s left in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1262 }
1263 break;
1264 case '':
1265 /* translators: %s: stock amount */
1266 $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1267 break;
1268 }
1269
1270 if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
1271 $display .= ' ' . __( '(can be backordered)', 'woocommerce' );
1272 }
1273
1274 return $display;
1275 }
1276
1277 /**
1278 * Format the stock quantity ready for display.
1279 *
1280 * @since 3.0.0
1281 * @param int $stock_quantity Stock quantity.
1282 * @param WC_Product $product Product instance so that we can pass through the filters.
1283 * @return string
1284 */
1285 function wc_format_stock_quantity_for_display( $stock_quantity, $product ) {
1286 return apply_filters( 'woocommerce_format_stock_quantity', $stock_quantity, $product );
1287 }
1288
1289 /**
1290 * Format a sale price for display.
1291 *
1292 * @since 3.0.0
1293 * @param string $regular_price Regular price.
1294 * @param string $sale_price Sale price.
1295 * @return string
1296 */
1297 function wc_format_sale_price( $regular_price, $sale_price ) {
1298 $price = '<del aria-hidden="true">' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</ins>';
1299 return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );
1300 }
1301
1302 /**
1303 * Format a price range for display.
1304 *
1305 * @param string $from Price from.
1306 * @param string $to Price to.
1307 * @return string
1308 */
1309 function wc_format_price_range( $from, $to ) {
1310 /* translators: 1: price from 2: price to */
1311 $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 );
1312 return apply_filters( 'woocommerce_format_price_range', $price, $from, $to );
1313 }
1314
1315 /**
1316 * Format a weight for display.
1317 *
1318 * @since 3.0.0
1319 * @param float $weight Weight.
1320 * @return string
1321 */
1322 function wc_format_weight( $weight ) {
1323 $weight_string = wc_format_localized_decimal( $weight );
1324
1325 if ( ! empty( $weight_string ) ) {
1326 $weight_label = I18nUtil::get_weight_unit_label( get_option( 'woocommerce_weight_unit' ) );
1327
1328 $weight_string = sprintf(
1329 // translators: 1. A formatted number; 2. A label for a weight unit of measure. E.g. 2.72 kg.
1330 _x( '%1$s %2$s', 'formatted weight', 'woocommerce' ),
1331 $weight_string,
1332 $weight_label
1333 );
1334 } else {
1335 $weight_string = __( 'N/A', 'woocommerce' );
1336 }
1337
1338 return apply_filters( 'woocommerce_format_weight', $weight_string, $weight );
1339 }
1340
1341 /**
1342 * Format dimensions for display.
1343 *
1344 * @since 3.0.0
1345 * @param array $dimensions Array of dimensions.
1346 * @return string
1347 */
1348 function wc_format_dimensions( $dimensions ) {
1349 $dimension_string = implode( ' &times; ', array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) ) );
1350
1351 if ( ! empty( $dimension_string ) ) {
1352 $dimension_label = I18nUtil::get_dimensions_unit_label( get_option( 'woocommerce_dimension_unit' ) );
1353
1354 $dimension_string = sprintf(
1355 // translators: 1. A formatted number; 2. A label for a dimensions unit of measure. E.g. 3.14 cm.
1356 _x( '%1$s %2$s', 'formatted dimensions', 'woocommerce' ),
1357 $dimension_string,
1358 $dimension_label
1359 );
1360 } else {
1361 $dimension_string = __( 'N/A', 'woocommerce' );
1362 }
1363
1364 return apply_filters( 'woocommerce_format_dimensions', $dimension_string, $dimensions );
1365 }
1366
1367 /**
1368 * Format a date for output.
1369 *
1370 * @since 3.0.0
1371 * @param WC_DateTime $date Instance of WC_DateTime.
1372 * @param string $format Data format.
1373 * Defaults to the wc_date_format function if not set.
1374 * @return string
1375 */
1376 function wc_format_datetime( $date, $format = '' ) {
1377 if ( ! $format ) {
1378 $format = wc_date_format();
1379 }
1380 if ( ! is_a( $date, 'WC_DateTime' ) ) {
1381 return '';
1382 }
1383 return $date->date_i18n( $format );
1384 }
1385
1386 /**
1387 * Process oEmbeds.
1388 *
1389 * @since 3.1.0
1390 * @param string $content Content.
1391 * @return string
1392 */
1393 function wc_do_oembeds( $content ) {
1394 global $wp_embed;
1395
1396 $content = $wp_embed->autoembed( $content ?? '' );
1397
1398 return $content;
1399 }
1400
1401 /**
1402 * Get part of a string before :.
1403 *
1404 * Used for example in shipping methods ids where they take the format
1405 * method_id:instance_id
1406 *
1407 * @since 3.2.0
1408 * @param string $string String to extract.
1409 * @return string
1410 */
1411 function wc_get_string_before_colon( $string ) {
1412 return trim( current( explode( ':', (string) $string ) ) );
1413 }
1414
1415 /**
1416 * Array merge and sum function.
1417 *
1418 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
1419 *
1420 * @since 3.2.0
1421 * @return array
1422 */
1423 function wc_array_merge_recursive_numeric() {
1424 $arrays = func_get_args();
1425
1426 // If there's only one array, it's already merged.
1427 if ( 1 === count( $arrays ) ) {
1428 return $arrays[0];
1429 }
1430
1431 // Remove any items in $arrays that are NOT arrays.
1432 foreach ( $arrays as $key => $array ) {
1433 if ( ! is_array( $array ) ) {
1434 unset( $arrays[ $key ] );
1435 }
1436 }
1437
1438 // We start by setting the first array as our final array.
1439 // We will merge all other arrays with this one.
1440 $final = array_shift( $arrays );
1441
1442 foreach ( $arrays as $b ) {
1443 foreach ( $final as $key => $value ) {
1444 // If $key does not exist in $b, then it is unique and can be safely merged.
1445 if ( ! isset( $b[ $key ] ) ) {
1446 $final[ $key ] = $value;
1447 } else {
1448 // If $key is present in $b, then we need to merge and sum numeric values in both.
1449 if ( is_numeric( $value ) && is_numeric( $b[ $key ] ) ) {
1450 // If both values for these keys are numeric, we sum them.
1451 $final[ $key ] = $value + $b[ $key ];
1452 } elseif ( is_array( $value ) && is_array( $b[ $key ] ) ) {
1453 // If both values are arrays, we recursively call ourself.
1454 $final[ $key ] = wc_array_merge_recursive_numeric( $value, $b[ $key ] );
1455 } else {
1456 // If both keys exist but differ in type, then we cannot merge them.
1457 // In this scenario, we will $b's value for $key is used.
1458 $final[ $key ] = $b[ $key ];
1459 }
1460 }
1461 }
1462
1463 // Finally, we need to merge any keys that exist only in $b.
1464 foreach ( $b as $key => $value ) {
1465 if ( ! isset( $final[ $key ] ) ) {
1466 $final[ $key ] = $value;
1467 }
1468 }
1469 }
1470
1471 return $final;
1472 }
1473
1474 /**
1475 * Implode and escape HTML attributes for output.
1476 *
1477 * @since 3.3.0
1478 * @param array $raw_attributes Attribute name value pairs.
1479 * @return string
1480 */
1481 function wc_implode_html_attributes( $raw_attributes ) {
1482 $attributes = array();
1483 foreach ( $raw_attributes as $name => $value ) {
1484 $attributes[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
1485 }
1486 return implode( ' ', $attributes );
1487 }
1488
1489 /**
1490 * Escape JSON for use on HTML or attribute text nodes.
1491 *
1492 * @since 3.5.5
1493 * @param string $json JSON to escape.
1494 * @param bool $html True if escaping for HTML text node, false for attributes. Determines how quotes are handled.
1495 * @return string Escaped JSON.
1496 */
1497 function wc_esc_json( $json, $html = false ) {
1498 return _wp_specialchars(
1499 $json,
1500 $html ? ENT_NOQUOTES : ENT_QUOTES, // Escape quotes in attribute nodes only.
1501 'UTF-8', // json_encode() outputs UTF-8 (really just ASCII), not the blog's charset.
1502 true // Double escape entities: `&amp;` -> `&amp;amp;`.
1503 );
1504 }
1505
1506 /**
1507 * Parse a relative date option from the settings API into a standard format.
1508 *
1509 * @since 3.4.0
1510 * @param mixed $raw_value Value stored in DB.
1511 * @return array Nicely formatted array with number and unit values.
1512 */
1513 function wc_parse_relative_date_option( $raw_value ) {
1514 $periods = array(
1515 'days' => __( 'Day(s)', 'woocommerce' ),
1516 'weeks' => __( 'Week(s)', 'woocommerce' ),
1517 'months' => __( 'Month(s)', 'woocommerce' ),
1518 'years' => __( 'Year(s)', 'woocommerce' ),
1519 );
1520
1521 $value = wp_parse_args(
1522 (array) $raw_value,
1523 array(
1524 'number' => '',
1525 'unit' => 'days',
1526 )
1527 );
1528
1529 $value['number'] = ! empty( $value['number'] ) ? absint( $value['number'] ) : '';
1530
1531 if ( ! in_array( $value['unit'], array_keys( $periods ), true ) ) {
1532 $value['unit'] = 'days';
1533 }
1534
1535 return $value;
1536 }
1537
1538 /**
1539 * Format the endpoint slug, strip out anything not allowed in a url.
1540 *
1541 * @since 3.5.0
1542 * @param string $raw_value The raw value.
1543 * @return string
1544 */
1545 function wc_sanitize_endpoint_slug( $raw_value ) {
1546 return sanitize_title( $raw_value ?? '' );
1547 }
1548 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_pay_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1549 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_order_received_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1550 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_add_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1551 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_delete_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1552 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_set_default_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1553 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_orders_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1554 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_view_order_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1555 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_downloads_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1556 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_account_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1557 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_address_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1558 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_payment_methods_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1559 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_lost_password_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1560 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_logout_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1561