Completed
Push — issues-2164 ( b2fc23 )
by Ravinder
696:21 queued 689:48
created

formatting.php ➔ give_get_currency_formatting_settings()   C

Complexity

Conditions 12
Paths 85

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 85
nop 1
dl 0
loc 52
rs 6.9666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Formatting functions for taking care of proper number formats and such
4
 *
5
 * @package     Give
6
 * @subpackage  Functions/Formatting
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Get Currency Formatting Settings for each donation.
19
 *
20
 * @param int|string $id_or_currency_code Donation ID or Currency code.
21
 *
22
 * @since 1.8.15
23
 *
24
 * @return mixed
25
 */
26
function give_get_currency_formatting_settings( $id_or_currency_code = null ) {
27
	$give_options = give_get_settings();
28
	$setting      = array();
29
30
	// Bail out, if donation id is null.
31
	if ( ! empty( $id_or_currency_code ) ) {
32
		$currencies   = give_get_currencies('all');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
33
34
		if( is_string( $id_or_currency_code ) && array_key_exists( $id_or_currency_code, $currencies ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
35
			$setting = $currencies[ $id_or_currency_code ]['setting'];
36
		}elseif ( is_numeric( $id_or_currency_code ) && 'give_payment' === get_post_type( $id_or_currency_code ) ) {
37
			$donation_meta = give_get_meta( $id_or_currency_code, '_give_payment_meta', true );
38
39
			if ( $give_options['currency'] !== $donation_meta['currency'] ) {
40
				$setting = $currencies[ $donation_meta['currency'] ]['setting'];
41
			}
42
		}
43
	}
44
45
	if ( empty( $setting ) ) {
46
		// Set thousand separator.
47
		$thousand_separator = isset( $give_options['thousands_separator'] ) ? $give_options['thousands_separator'] : ',';
48
		$thousand_separator = empty( $thousand_separator ) ? ' ' : $thousand_separator;
49
50
		// Set decimal separator.
51
		$default_decimal_separators = array(
52
			'.' => ',',
53
			',' => '.',
54
		);
55
56
		$default_decimal_separator = in_array( $thousand_separator, $default_decimal_separators ) ?
57
			$default_decimal_separators[ $thousand_separator ] :
58
			'.';
59
60
		$decimal_separator = ! empty( $give_options['decimal_separator'] ) ? $give_options['decimal_separator'] : $default_decimal_separator;
61
62
		$setting = array(
63
			'currency_position'   => give_get_option( 'currency_position', 'before' ),
64
			'thousands_separator' => $thousand_separator,
65
			'decimal_separator'   => $decimal_separator,
66
			'number_decimals'     => give_get_option( 'number_decimals', 0 ),
67
		);
68
	}
69
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
70
71
	/**
72
	 * Filter the currency formatting setting.
73
	 *
74
	 * @since 1.8.15
75
	 */
76
	return apply_filters( 'give_get_currency_formatting_settings', $setting, $id_or_currency_code );
77
}
78
79
/**
80
 * Get decimal count
81
 *
82
 * @param int $donation_id Donation ID.
83
 *
84
 * @since 1.6
85
 *
86
 * @return mixed
87
 */
88
function give_get_price_decimals( $donation_id = null ) {
89
	$setting = give_get_currency_formatting_settings( $donation_id );
90
91
	/**
92
	 * Filter the number of decimals
93
	 *
94
	 * @since 1.6
95
	 */
96
	return apply_filters( 'give_sanitize_amount_decimals', $setting['number_decimals'], $donation_id );
97
}
98
99
/**
100
 * Get thousand separator
101
 *
102
 * @param int $donation_id Donation ID.
103
 *
104
 * @since 1.6
105
 *
106
 * @return mixed
107
 */
108
function give_get_price_thousand_separator( $donation_id = null ) {
109
	$setting = give_get_currency_formatting_settings( $donation_id );
110
111
	/**
112
	 * Filter the thousand separator
113
	 *
114
	 * @since 1.6
115
	 */
116
	return apply_filters( 'give_get_price_thousand_separator', $setting['thousands_separator'], $donation_id );
117
}
118
119
/**
120
 * Get decimal separator
121
 *
122
 * @param int $donation_id Donation ID.
123
 *
124
 * @since 1.6
125
 *
126
 * @return mixed
127
 */
128
function give_get_price_decimal_separator( $donation_id = null ) {
129
	$setting = give_get_currency_formatting_settings( $donation_id );
130
131
	/**
132
	 * Filter the thousand separator
133
	 *
134
	 * @since 1.6
135
	 */
136
	return apply_filters( 'give_get_price_decimal_separator', $setting['decimal_separator'], $donation_id );
137
}
138
139
140
/**
141
 * Sanitize Amount before saving to database
142
 *
143
 * @since      1.8.12
144
 *
145
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
146
 *
147
 * @return string $amount Newly sanitized amount
148
 */
149
function give_sanitize_amount_for_db( $number ) {
150
	return give_maybe_sanitize_amount( $number, 6 );
151
}
152
153
/**
154
 * Sanitize Amount before saving to database
155
 *
156
 * @since      1.8.12
157
 *
158
 * @param  int|float|string $number     Expects either a float or a string with a decimal separator only (no thousands)
159
 * @param  int|bool         $dp         Number of decimals
160
 * @param  bool             $trim_zeros From end of string
161
 *
162
 * @return string $amount Newly sanitized amount
163
 */
164
function give_maybe_sanitize_amount( $number, $dp = false, $trim_zeros = false ) {
165
	$thousand_separator = give_get_price_thousand_separator();
166
	$decimal_separator  = give_get_price_decimal_separator();
167
	$number_decimals    = is_bool( $dp ) ? give_get_price_decimals() : $dp;
168
169
	// Explode number by . decimal separator.
170
	$number_parts = explode( '.', $number );
171
172
	/*
173
	 * Bailout: Quick format number
174
	 */
175
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
176
		return $number;
177
	}
178
179
	// Remove currency symbols from number if any.
180
	$number = trim( str_replace( give_currency_symbols( true ), '', $number ) );
181
182
	if (
183
		// Non formatted number.
184
		(
185
			( false === strpos( $number, $thousand_separator ) ) &&
186
			( false === strpos( $number, $decimal_separator ) )
187
		) ||
188
189
		// Decimal formatted number.
190
191
		// If number of decimal place set to non zero and
192
		// number only contains `.` as separator, precision set to less then or equal to number of decimal
193
		// then number will be consider as decimal formatted which means number is already sanitized.
194
		(
195
			$number_decimals &&
196
			'.' === $thousand_separator &&
197
			false !== strpos( $number, $thousand_separator ) &&
198
			false === strpos( $number, $decimal_separator ) &&
199
			2 === count( $number_parts ) &&
200
			( $number_decimals >= strlen( $number_parts[1] ) )
201
		)
202
	) {
203
		return number_format( $number, $number_decimals, '.', '' );
204
	}
205
206
	// Handle thousand separator as '.'
207
	// Handle sanitize database values.
208
	$is_db_sanitize_val = ( 2 === count( $number_parts ) &&
209
	                        is_numeric( $number_parts[0] ) &&
210
	                        is_numeric( $number_parts[1] ) &&
211
	                        ( 6 === strlen( $number_parts[1] ) ) );
212
213
	if ( $is_db_sanitize_val ) {
214
		// Sanitize database value.
215
		return number_format( $number, $number_decimals, '.', '' );
216
217
	} elseif (
218
		'.' === $thousand_separator &&
219
		false !== strpos( $number, $thousand_separator )
220
	) {
221
		// Fix point thousand separator value.
222
		$number = str_replace( '.', '', $number );
223
	}
224
225
	return give_sanitize_amount( $number, $number_decimals, $trim_zeros );
226
}
227
228
/**
229
 * Sanitize Amount
230
 *
231
 * Note: Use this give_maybe_sanitize_amount function instead for sanitizing number.
232
 *
233
 * Returns a sanitized amount by stripping out thousands separators.
234
 *
235
 * @since      1.0
236
 *
237
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
238
 * @param  int|bool         $dp Number of decimals
239
 * @param  bool             $trim_zeros From end of string
240
 *
241
 * @return string $amount Newly sanitized amount
242
 */
243
function give_sanitize_amount( $number, $dp = false, $trim_zeros = false ) {
244
245
	// Bailout.
246
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
247
		return $number;
248
	}
249
250
	// Remove slash from amount.
251
	// If thousand or decimal separator is set to ' then in $_POST or $_GET param we will get an escaped number.
252
	// To prevent notices and warning remove slash from amount/number.
253
	$number = wp_unslash( $number );
254
255
	$thousand_separator = give_get_price_thousand_separator();
256
257
	$locale   = localeconv();
258
	$decimals = array( give_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
259
260
	// Remove locale from string
261
	if ( ! is_float( $number ) ) {
262
		$number = str_replace( $decimals, '.', $number );
263
	}
264
265
	// Remove thousand amount formatting if amount has.
266
	// This condition use to add backward compatibility to version before 1.6, because before version 1.6 we were saving formatted amount to db.
267
	// Do not replace thousand separator from price if it is same as decimal separator, because it will be already replace by above code.
268
	if ( ! in_array( $thousand_separator, $decimals ) && ( false !== strpos( $number, $thousand_separator ) ) ) {
269
		$number = str_replace( $thousand_separator, '', $number );
270
	} elseif ( in_array( $thousand_separator, $decimals ) ) {
271
		$number = preg_replace( '/\.(?=.*\.)/', '', $number );
272
	}
273
274
	// Remove non numeric entity before decimal separator.
275
	$number     = preg_replace( '/[^0-9\.]/', '', $number );
276
	$default_dp = give_get_price_decimals();
277
278
	// Reset negative amount to zero.
279
	if ( 0 > $number ) {
280
		$number = number_format( 0, $default_dp, '.' );
281
	}
282
283
	// If number does not have decimal then add number of decimals to it.
284
	if (
285
		false === strpos( $number, '.' )
286
		|| ( $default_dp > strlen( substr( $number, strpos( $number, '.' ) + 1 ) ) )
287
	) {
288
		$number = number_format( $number, $default_dp, '.', '' );
289
	}
290
291
	// Format number by custom number of decimals.
292
	if ( false !== $dp ) {
293
		$dp     = intval( is_bool( $dp ) ? $default_dp : $dp );
294
		$dp     = apply_filters( 'give_sanitize_amount_decimals', $dp, $number );
295
		$number = number_format( floatval( $number ), $dp, '.', '' );
296
	}
297
298
	// Trim zeros.
299
	if ( $trim_zeros && strstr( $number, '.' ) ) {
300
		$number = rtrim( rtrim( $number, '0' ), '.' );
301
	}
302
303
	return apply_filters( 'give_sanitize_amount', $number );
304
}
305
306
/**
307
 * Returns a nicely formatted amount.
308
 *
309
 * @since 1.0
310
 *
311
 * @param string $amount      Price amount to format
312
 * @param array  $args        Array of arguments.
313
 *
314
 * @return string $amount   Newly formatted amount or Price Not Available
315
 */
316
function give_format_amount( $amount, $args = array() ) {
317
	// Backward compatibility.
318
	if( is_bool( $args ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
319
		$args = array( 'decimal' => $args );
320
	}
321
322
	$default_args = array(
323
		'decimal'     => true,
324
		'sanitize'    => true,
325
		'donation_id' => 0
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
326
	);
327
328
	$args = wp_parse_args( $args, $default_args );
329
330
	// Set Currency based on donation id, if required.
331
	if( $args['donation_id'] ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
332
		$donation_meta =  give_get_meta( $args['donation_id'], '_give_payment_meta', true );
0 ignored issues
show
introduced by
Expected 1 space after "="; 2 found
Loading history...
333
		$args['currency'] = $donation_meta['currency'];
334
	}
335
336
	$formatted     = 0;
337
	$thousands_sep = give_get_price_thousand_separator( $args['donation_id'] );
338
	$decimal_sep   = give_get_price_decimal_separator( $args['donation_id'] );
339
	$decimals      = ! empty( $args['decimal'] ) ? give_get_price_decimals( $args['donation_id'] ) : 0;
340
	$currency      = ! empty( $args['currency'] ) ? $args['currency'] : give_get_currency();
341
342
	if ( ! empty( $amount ) ) {
343
		// Sanitize amount before formatting.
344
		$amount = ! empty( $args['sanitize'] ) ?
345
			give_maybe_sanitize_amount( $amount, $decimals ) :
346
			number_format( $amount, $decimals, '.', '' );
347
348
		switch ( $currency ) {
349
			case 'INR':
350
				$decimal_amount = '';
351
352
				// Extract decimals from amount
353
				if ( ( $pos = strpos( $amount, '.' ) ) !== false ) {
0 ignored issues
show
introduced by
Found "!== false". Use Yoda Condition checks, you must
Loading history...
354
					if ( ! empty( $decimals ) ) {
355
						$decimal_amount = substr( round( substr( $amount, $pos ), $decimals ), 1 );
356
						$amount         = substr( $amount, 0, $pos );
357
358
						if ( ! $decimal_amount ) {
359
							$decimal_amount = substr( '.0000000000', 0, ( $decimals + 1 ) );
360
						} elseif ( ( $decimals + 1 ) > strlen( $decimal_amount ) ) {
361
							$decimal_amount = substr( "{$decimal_amount}000000000", 0, ( $decimals + 1 ) );
362
						}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
363
364
					} else {
365
						$amount = number_format( $amount, $decimals, $decimal_sep, '' );
366
					}
367
				}
368
369
				// Extract last 3 from amount
370
				$result = substr( $amount, - 3 );
371
				$amount = substr( $amount, 0, - 3 );
372
373
				// Apply digits 2 by 2
374
				while ( strlen( $amount ) > 0 ) {
375
					$result = substr( $amount, - 2 ) . $thousands_sep . $result;
376
					$amount = substr( $amount, 0, - 2 );
377
				}
378
379
				$formatted = $result . $decimal_amount;
380
				break;
381
382
			default:
383
				$formatted = number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
384
		}
385
	}
386
387
	return apply_filters( 'give_format_amount', $formatted, $amount, $decimals, $decimal_sep, $thousands_sep, $currency, $args );
388
}
389
390
391
/**
392
 * Get human readable amount.
393
 *
394
 * Note: This function only support large number formatting from million to trillion
395
 *
396
 * @since 1.6
397
 *
398
 * @use   give_get_price_thousand_separator Get thousand separator.
399
 *
400
 * @param string $amount formatted amount number.
401
 * @param array  $args   Array of arguments.
402
 *
403
 * @return float|string  formatted amount number with large number names.
404
 */
405
function give_human_format_large_amount( $amount, $args = array() ) {
406
	$default_args = array(
407
		'currency' => give_get_currency(),
408
	);
409
410
	$args = wp_parse_args( $args, $default_args );
411
412
	// Get thousand separator.
413
	$thousands_sep = give_get_price_thousand_separator();
414
415
	// Sanitize amount.
416
	$sanitize_amount = give_maybe_sanitize_amount( $amount );
417
418
	// Explode amount to calculate name of large numbers.
419
	$amount_array = explode( $thousands_sep, $amount );
420
421
	// Calculate amount parts count.
422
	$amount_count_parts = count( $amount_array );
423
424
	// Human format amount (default).
425
	$human_format_amount = $amount;
426
427
	switch ( $args['currency'] ) {
428 View Code Duplication
		case 'INR':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
429
			// Calculate large number formatted amount.
430
			if ( 4 < $amount_count_parts ) {
431
				$human_format_amount = sprintf( esc_html__( '%s arab', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
432
			} elseif ( 3 < $amount_count_parts ) {
433
				$human_format_amount = sprintf( esc_html__( '%s crore', 'give' ), round( ( $sanitize_amount / 10000000 ), 2 ) );
434
			} elseif ( 2 < $amount_count_parts ) {
435
				$human_format_amount = sprintf( esc_html__( '%s lakh', 'give' ), round( ( $sanitize_amount / 100000 ), 2 ) );
436
			}
437
			break;
438 View Code Duplication
		default:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
439
			// Calculate large number formatted amount.
440
			if ( 4 < $amount_count_parts ) {
441
				$human_format_amount = sprintf( esc_html__( '%s trillion', 'give' ), round( ( $sanitize_amount / 1000000000000 ), 2 ) );
442
			} elseif ( 3 < $amount_count_parts ) {
443
				$human_format_amount = sprintf( esc_html__( '%s billion', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
444
			} elseif ( 2 < $amount_count_parts ) {
445
				$human_format_amount = sprintf( esc_html__( '%s million', 'give' ), round( ( $sanitize_amount / 1000000 ), 2 ) );
446
			}
447
	}
448
449
	return apply_filters( 'give_human_format_large_amount', $human_format_amount, $amount, $sanitize_amount );
450
}
451
452
/**
453
 * Returns a nicely formatted amount with custom decimal separator.
454
 *
455
 * @since 1.0
456
 *
457
 * @param int|float|string $amount   Formatted or sanitized price
458
 * @param int|bool         $dp       number of decimals
459
 * @param bool             $sanitize Whether or not sanitize number
460
 *
461
 * @return string $amount Newly formatted amount or Price Not Available
462
 */
463
function give_format_decimal( $amount, $dp = false, $sanitize = true ) {
464
	$decimal_separator = give_get_price_decimal_separator();
465
	$formatted_amount  = $sanitize ?
466
		give_maybe_sanitize_amount( $amount, $dp ) :
467
		number_format( $amount, ( is_bool( $dp ) ? give_get_price_decimals() : $dp ), '.', '' );
468
469
	if ( false !== strpos( $formatted_amount, '.' ) ) {
470
		$formatted_amount = str_replace( '.', $decimal_separator, $formatted_amount );
471
	}
472
473
	return apply_filters( 'give_format_decimal', $formatted_amount, $amount, $decimal_separator );
474
}
475
476
/**
477
 * Formats the currency displayed.
478
 *
479
 * @since 1.0
480
 *
481
 * @param string $price The donation amount.
482
 * @param string $currency The currency code.
483
 * @param bool   $decode_currency Whether to decode the currency HTML format or not.
484
 *
485
 * @return mixed|string
486
 */
487
function give_currency_filter( $price = '', $currency = '', $decode_currency = false ) {
488
489
	if ( empty( $currency ) || ! array_key_exists( (string) $currency, give_get_currencies() ) ) {
490
		$currency = give_get_currency();
491
	}
492
493
	$position = give_get_option( 'currency_position', 'before' );
494
495
	$negative = $price < 0;
496
497
	if ( $negative ) {
498
		// Remove proceeding "-".
499
		$price = substr( $price, 1 );
500
	}
501
502
	$symbol = give_currency_symbol( $currency, $decode_currency );
503
504
	switch ( $currency ) :
505
		case 'GBP' :
506
		case 'BRL' :
507
		case 'EUR' :
508
		case 'USD' :
509
		case 'AUD' :
510
		case 'CAD' :
511
		case 'HKD' :
512
		case 'MXN' :
513
		case 'NZD' :
514
		case 'SGD' :
515
		case 'JPY' :
516
		case 'THB' :
517
		case 'INR' :
518
		case 'RIAL' :
519
		case 'TRY' :
520
		case 'RUB' :
521
		case 'SEK' :
522
		case 'PLN' :
523
		case 'PHP' :
524
		case 'TWD' :
525
		case 'MYR' :
526
		case 'CZK' :
527
		case 'DKK' :
528
		case 'HUF' :
529
		case 'ILS' :
530
		case 'MAD' :
531
		case 'KRW' :
532
		case 'ZAR' :
533
			$formatted = ( 'before' === $position ? $symbol . $price : $price . $symbol );
534
			break;
535 View Code Duplication
		case 'NOK' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
536
			$formatted = ( 'before' === $position ? $symbol . ' ' . $price : $price . ' ' . $symbol );
537
			break;
538 View Code Duplication
		default :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
539
			$formatted = ( 'before' === $position ? $currency . ' ' . $price : $price . ' ' . $currency );
540
			break;
541
	endswitch;
542
543
	/**
544
	 * Filter formatted amount with currency
545
	 *
546
	 * Filter name depends upon current value of currency and currency position.
547
	 * For example :
548
	 *           if currency is USD and currency position is before then
549
	 *           filter name will be give_usd_currency_filter_before
550
	 *
551
	 *           and if currency is USD and currency position is after then
552
	 *           filter name will be give_usd_currency_filter_after
553
	 */
554
	$formatted = apply_filters( 'give_' . strtolower( $currency ) . "_currency_filter_{$position}", $formatted, $currency, $price );
555
556
	if ( $negative ) {
557
		// Prepend the minus sign before the currency sign.
558
		$formatted = '-' . $formatted;
559
	}
560
561
	return $formatted;
562
}
563
564
565
/**
566
 * Get date format string on basis of given context.
567
 *
568
 * @since 1.7
569
 *
570
 * @param  string $date_context Date format context name.
571
 *
572
 * @return string                  Date format string
573
 */
574
function give_date_format( $date_context = '' ) {
575
	/**
576
	 * Filter the date context
577
	 *
578
	 * You can add your own date context or use already exist context.
579
	 * For example:
580
	 *    add_filter( 'give_date_format_contexts', 'add_new_date_contexts' );
581
	 *    function add_new_date_contexts( $date_format_contexts ) {
582
	 *        // You can add single context like this $date_format_contexts['checkout'] = 'F j, Y';
583
	 *        // Instead add multiple date context at once.
584
	 *        $new_date_format_contexts = array(
585
	 *            'checkout' => 'F j, Y',
586
	 *            'report'   => 'Y-m-d',
587
	 *            'email'    => 'm/d/Y',
588
	 *        );
589
	 *
590
	 *       // Merge date contexts array only if you are adding multiple date contexts at once otherwise return  $date_format_contexts.
591
	 *       return array_merge( $new_date_format_contexts, $date_format_contexts );
592
	 *
593
	 *    }
594
	 */
595
	$date_format_contexts = apply_filters( 'give_date_format_contexts', array() );
596
597
	// Set date format to default date format.
598
	$date_format = get_option( 'date_format' );
599
600
	// Update date format if we have non empty date format context array and non empty date format string for that context.
601
	if ( $date_context && ! empty( $date_format_contexts ) && array_key_exists( $date_context, $date_format_contexts ) ) {
602
		$date_format = ! empty( $date_format_contexts[ $date_context ] )
603
			? $date_format_contexts[ $date_context ]
604
			: $date_format;
605
	}
606
607
	return apply_filters( 'give_date_format', $date_format );
608
}
609
610
/**
611
 * Get cache key.
612
 *
613
 * @since  1.7
614
 * @deprecated 1.8.7 You can access this function from Give_Cache.
615
 *
616
 * @param  string $action Cache key prefix.
617
 * @param array  $query_args Query array.
618
 *
619
 * @return string
620
 */
621
function give_get_cache_key( $action, $query_args ) {
622
	return Give_Cache::get_key( $action, $query_args );
623
}
624
625
/**
626
 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
627
 * Non-scalar values are ignored.
628
 *
629
 * @since  1.8
630
 *
631
 * @param  string|array $var
632
 *
633
 * @return string|array
634
 */
635
function give_clean( $var ) {
636
	if ( is_array( $var ) ) {
637
		return array_map( 'give_clean', $var );
638
	} else {
639
		return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
640
	}
641
}
642
643
/**
644
 * Transforms php.ini notation for numbers (like '2M') to an integer.
645
 *
646
 * @since 1.8
647
 *
648
 * @param $size
649
 *
650
 * @return int
651
 */
652
function give_let_to_num( $size ) {
653
	$l   = substr( $size, - 1 );
654
	$ret = substr( $size, 0, - 1 );
655
	switch ( strtoupper( $l ) ) {
656
		case 'P':
657
			$ret *= 1024;
658
		case 'T':
659
			$ret *= 1024;
660
		case 'G':
661
			$ret *= 1024;
662
		case 'M':
663
			$ret *= 1024;
664
		case 'K':
665
			$ret *= 1024;
666
	}
667
668
	return $ret;
669
}
670
671
/**
672
 * Verify nonce.
673
 *
674
 * @since 1.8
675
 *
676
 * @param        $nonce
677
 * @param int   $action
678
 * @param array $wp_die_args
679
 */
680
function give_validate_nonce( $nonce, $action = - 1, $wp_die_args = array() ) {
681
682
	$default_wp_die_args = array(
683
		'message' => esc_html__( 'Nonce verification has failed.', 'give' ),
684
		'title'   => esc_html__( 'Error', 'give' ),
685
		'args'    => array(
686
			'response' => 403,
687
		),
688
	);
689
690
	$wp_die_args = wp_parse_args( $wp_die_args, $default_wp_die_args );
691
692
	if ( ! wp_verify_nonce( $nonce, $action ) ) {
693
		wp_die(
694
			$wp_die_args['message'],
695
			$wp_die_args['title'],
696
			$wp_die_args['args']
697
		);
698
	}
699
}
700
701
/**
702
 * Check variable and get default or valid value.
703
 *
704
 * Helper function to check if a variable is set, empty, etc.
705
 *
706
 * @since 1.8
707
 *
708
 * @param                   $variable
709
 * @param string (optional) $conditional , default value: isset
710
 * @param bool (optional)   $default , default value: false
711
 *
712
 * @return mixed
713
 */
714
function give_check_variable( $variable, $conditional = '', $default = false ) {
715
716
	switch ( $conditional ) {
717
		case 'isset_empty':
718
			$variable = ( isset( $variable ) && ! empty( $variable ) ) ? $variable : $default;
719
			break;
720
721
		case 'empty':
722
			$variable = ! empty( $variable ) ? $variable : $default;
723
			break;
724
725
		case 'null':
726
			$variable = ! is_null( $variable ) ? $variable : $default;
727
			break;
728
729
		default:
730
			$variable = isset( $variable ) ? $variable : $default;
731
732
	}
733
734
	return $variable;
735
736
}
737