Test Failed
Push — master ( eece2d...16421a )
by Devin
11:50
created

formatting.php ➔ give_maybe_sanitize_amount()   C

Complexity

Conditions 23
Paths 85

Size

Total Lines 79
Code Lines 44

Duplication

Lines 6
Ratio 7.59 %

Code Coverage

Tests 17
CRAP Score 217.7457

Importance

Changes 0
Metric Value
cc 23
eloc 44
nc 85
nop 2
dl 6
loc 79
rs 5.0403
c 0
b 0
f 0
ccs 17
cts 60
cp 0.2833
crap 217.7457

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 52
30 52
	if ( ! empty( $id_or_currency_code ) ) {
31 52
		$currencies = give_get_currencies( 'all' );
32
33
		// Set default formatting setting only if currency not set as global currency.
34 52
		if (
35
			is_string( $id_or_currency_code ) &&
36
			! empty( $give_options['currency'] ) &&
37
			$id_or_currency_code !== $give_options['currency'] &&
38
			array_key_exists( $id_or_currency_code, $currencies )
39
		) {
40
			$setting = $currencies[ $id_or_currency_code ]['setting'];
41
		} elseif ( is_numeric( $id_or_currency_code ) && 'give_payment' === get_post_type( $id_or_currency_code ) ) {
42 52
			$currency = give_get_meta( $id_or_currency_code, '_give_payment_currency', true );
43
44
			if (
45
				! empty( $currency) &&
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
46 52
				$give_options['currency'] !== $currency
47
			) {
48
				$setting = $currencies[ $currency ]['setting'];
49
			}
50 52
		}
51 52
	}
52 52
53
	if ( empty( $setting ) ) {
54 52
		// Set thousand separator.
55
		$thousand_separator = isset( $give_options['thousands_separator'] ) ? $give_options['thousands_separator'] : ',';
56
		$thousand_separator = empty( $thousand_separator ) ? ' ' : $thousand_separator;
57
58 52
		// Set decimal separator.
59
		$default_decimal_separators = array(
60
			'.' => ',',
61
			',' => '.',
62
		);
63
64
		$default_decimal_separator = in_array( $thousand_separator, $default_decimal_separators ) ?
65
			$default_decimal_separators[ $thousand_separator ] :
66
			'.';
67
68
		$decimal_separator = ! empty( $give_options['decimal_separator'] ) ? $give_options['decimal_separator'] : $default_decimal_separator;
69
70
		$setting = array(
71
			'currency_position'   => give_get_option( 'currency_position', 'before' ),
72
			'thousands_separator' => $thousand_separator,
73 43
			'decimal_separator'   => $decimal_separator,
74 43
			'number_decimals'     => give_get_option( 'number_decimals', 0 ),
75
		);
76
	}
77 43
78
	/**
79
	 * Filter the currency formatting setting.
80
	 *
81
	 * @since 1.8.15
82
	 */
83
	return apply_filters( 'give_get_currency_formatting_settings', $setting, $id_or_currency_code );
84 43
}
85
86
/**
87
 * Get decimal count
88
 *
89 43
 * @since 1.6
90
 *
91
 * @param int|string $id_or_currency_code
92
 *
93
 * @return mixed
94
 */
95 View Code Duplication
function give_get_price_decimals( $id_or_currency_code = null ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
96
	// Set currency on basis of donation id.
97
	if ( empty( $id_or_currency_code ) ) {
98
		$id_or_currency_code = give_get_currency();
99 43
	}
100
101
	$number_of_decimals = 0;
102
103 43
	if ( ! give_is_zero_based_currency( $id_or_currency_code ) ) {
104 2
		$setting            = give_get_currency_formatting_settings( $id_or_currency_code );
105 2
		$number_of_decimals = $setting['number_decimals'];
106
	}
107 43
108
	/**
109 43
	 * Filter the number of decimals
110
	 *
111 43
	 * @since 1.6
112
	 */
113
	return apply_filters( 'give_sanitize_amount_decimals', $number_of_decimals, $id_or_currency_code );
114
}
115
116
/**
117
 * Get thousand separator
118
 *
119
 * @param int|string $id_or_currency_code
120
 *
121
 * @since 1.6
122
 *
123
 * @return mixed
124
 */
125
function give_get_price_thousand_separator( $id_or_currency_code = null ) {
126
	$setting = give_get_currency_formatting_settings( $id_or_currency_code );
127
128
	/**
129
	 * Filter the thousand separator
130
	 *
131
	 * @since 1.6
132
	 */
133
	return apply_filters( 'give_get_price_thousand_separator', $setting['thousands_separator'], $id_or_currency_code );
134
}
135
136
/**
137
 * Get decimal separator
138
 *
139
 * @param string $id_or_currency_code
140
 *
141
 * @since 1.6
142
 *
143
 * @return mixed
144
 */
145
function give_get_price_decimal_separator( $id_or_currency_code = null ) {
146 45
	$setting = give_get_currency_formatting_settings( $id_or_currency_code );
147 45
148 45
	/**
149
	 * Filter the thousand separator
150 45
	 *
151
	 * @since 1.6
152 45
	 */
153
	return apply_filters( 'give_get_price_decimal_separator', $setting['decimal_separator'], $id_or_currency_code );
154 45
}
155
156
157
/**
158 45
 * Sanitize Amount before saving to database
159
 *
160 45
 * @since      1.8.12
161
 *
162 45
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
163 45
 *
164 45
 * @return string $amount Newly sanitized amount
165 45
 */
166 45
function give_sanitize_amount_for_db( $number ) {
167 45
	return give_maybe_sanitize_amount( $number, array( 'number_decimals' => 6 ) );
168 45
}
169 45
170 45
/**
171 45
 * Sanitize Amount before saving to database
172 45
 *
173 45
 * @since      1.8.12
174 45
 *
175 45
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
176 45
 * @param  array|bool       $args   It accepts 'number_decimals', 'trim_zeros', 'currency'.
177 45
 *
178 45
 * @return string $amount Newly sanitized amount
179 45
 */
180 45
function give_maybe_sanitize_amount( $number, $args = array() ) {
181 45
	// Bailout.
182 45
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
183 45
		return $number;
184 45
	}
185 45
186 45
	$func_args = func_get_args();
187 45
188 45
	// Backward compatibility.
189 45 View Code Duplication
	if ( isset( $func_args[1] ) && ( is_bool( $func_args[1] ) || is_numeric( $func_args[1] ) ) ) {
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...
190 45
		$args = array(
191 45
			'number_decimals' => $func_args[1],
192
			'trim_zeros'      => isset( $func_args[2] ) ? $func_args[2] : false,
193
		);
194
	}
195
196
	$args = wp_parse_args(
197
		$args,
198
		array(
199 45
			'number_decimals' => false,
200 45
			'trim_zeros'      => false,
201
			'currency'        => give_get_currency(),
202
		)
203
	);
204
205
	$thousand_separator = give_get_price_thousand_separator( $args['currency'] );
206
	$decimal_separator  = give_get_price_decimal_separator( $args['currency'] );
207
	$number_decimals    = is_bool( $args['number_decimals'] ) ?
208
		give_get_price_decimals() :
209
		$args['number_decimals'];
210
211
	// Explode number by . decimal separator.
212
	$number_parts = explode( '.', $number );
213
214
	// Remove currency symbols from number if any.
215
	$number = trim( str_replace( give_currency_symbols( true ), '', $number ) );
216
217
	if (
218
		// Non formatted number.
219
		false === strpos( $number, $thousand_separator )
220
		&& false === strpos( $number, $decimal_separator )
221
	) {
222
		return number_format( $number, $number_decimals, '.', '' );
223
	} elseif (
224
		// Decimal formatted number.
225
		// If number of decimal place set to non zero and
226
		// number only contains `.` as separator, precision set to less then or equal to number of decimal
227
		// then number will be consider as decimal formatted which means number is already sanitized.
228
		$number_decimals
229
		&& '.' === $thousand_separator
230
		&& false !== strpos( $number, $thousand_separator )
231
		&& false === strpos( $number, $decimal_separator )
232
		&& 2 === count( $number_parts )
233
		&& ( $number_decimals >= strlen( $number_parts[1] ) )
234
	){
235
		return number_format( $number, $number_decimals, '.', '' );
236
	}
237
238 45
	// Handle thousand separator as '.'
239
	// Handle sanitize database values.
240
	$is_db_sanitize_val = ( 2 === count( $number_parts ) &&
241
							is_numeric( $number_parts[0] ) &&
242
							is_numeric( $number_parts[1] ) &&
243 45
							( 6 === strlen( $number_parts[1] ) ) );
244
245
	if ( $is_db_sanitize_val ) {
246
		// Sanitize database value.
247
		return number_format( $number, $number_decimals, '.', '' );
248
249
	} elseif (
250
		'.' === $thousand_separator &&
251
		false !== strpos( $number, $thousand_separator )
252
	) {
253
		// Fix point thousand separator value.
254
		$number = str_replace( '.', '', $number );
255
	}
256
257 55
	return give_sanitize_amount( $number, $args );
258
}
259
260 55
/**
261 55
 * Sanitize Amount
262 55
 *
263 55
 * Note: Do not this function to sanitize amount instead use give_maybe_sanitize_amount function.
264
 *
265
 * Returns a sanitized amount by stripping out thousands separators.
266
 *
267
 * @since      1.0
268
 *
269 55
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
270
 * @param  array|bool       $args   It accepts 'number_decimals', 'trim_zeros', 'currency'.
271
 *
272
 * @return string $amount Newly sanitized amount
273
 */
274
function give_sanitize_amount( $number, $args = array() ) {
275
276
	// Bailout.
277
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
278
		return $number;
279
	}
280
281
	// Get function arguments.
282
	$func_args = func_get_args();
283
284
	// Backward compatibility.
285 View Code Duplication
	if ( isset( $func_args[1] ) && ( is_bool( $func_args[1] ) || is_numeric( $func_args[1] ) ) ) {
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...
286
		$args = array(
287
			'number_decimals' => $func_args[1],
288
			'trim_zeros'      => isset( $func_args[2] ) ? $func_args[2] : false,
289
		);
290
	}
291
292
	$args = wp_parse_args(
293
		$args,
294
		array(
295
			'number_decimals' => false,
296
			'trim_zeros'      => false,
297
			'currency'        => give_get_currency(),
298
		)
299
	);
300
301
	// Remove slash from amount.
302
	// If thousand or decimal separator is set to ' then in $_POST or $_GET param we will get an escaped number.
303
	// To prevent notices and warning remove slash from amount/number.
304
	$number = wp_unslash( $number );
305
306
	$thousand_separator = give_get_price_thousand_separator( $args['currency'] );
307
308
	$locale   = localeconv();
309
	$decimals = array(
310
		give_get_price_decimal_separator( $args['currency'] ),
311
		$locale['decimal_point'],
312
		$locale['mon_decimal_point'],
313
	);
314
315
	// Remove locale from string
316
	if ( ! is_float( $number ) ) {
317
		$number = str_replace( $decimals, '.', $number );
318
	}
319
320
	// Remove thousand amount formatting if amount has.
321
	// This condition use to add backward compatibility to version before 1.6, because before version 1.6 we were saving formatted amount to db.
322
	// Do not replace thousand separator from price if it is same as decimal separator, because it will be already replace by above code.
323
	if ( ! in_array( $thousand_separator, $decimals ) && ( false !== strpos( $number, $thousand_separator ) ) ) {
324
		$number = str_replace( $thousand_separator, '', $number );
325
	} elseif ( in_array( $thousand_separator, $decimals ) ) {
326
		$number = preg_replace( '/\.(?=.*\.)/', '', $number );
327
	}
328
329
	// Remove non numeric entity before decimal separator.
330
	$number     = preg_replace( '/[^0-9\.]/', '', $number );
331
	$default_dp = give_get_price_decimals( $args['currency'] );
332
333
	// Reset negative amount to zero.
334
	if ( 0 > $number ) {
335
		$number = number_format( 0, $default_dp, '.' );
336
	}
337
338
	// If number does not have decimal then add number of decimals to it.
339
	if (
340
		false === strpos( $number, '.' )
341
		|| ( $default_dp > strlen( substr( $number, strpos( $number, '.' ) + 1 ) ) )
342
	) {
343
		$number = number_format( $number, $default_dp, '.', '' );
344
	}
345
346
	// Format number by custom number of decimals.
347
	if ( false !== $args['number_decimals'] ) {
348
		$dp     = intval( is_bool( $args['number_decimals'] ) ? $default_dp : $args['number_decimals'] );
349
		$dp     = apply_filters( 'give_sanitize_amount_decimals', $dp, $number );
350
		$number = number_format( floatval( $number ), $dp, '.', '' );
351
	}
352
353
	// Trim zeros.
354
	if ( $args['trim_zeros'] && strstr( $number, '.' ) ) {
355
		$number = rtrim( rtrim( $number, '0' ), '.' );
356
	}
357
358
	/**
359
	 * Filter the sanitize amount
360
	 *
361
	 * @since 1.0
362
	 */
363
	return apply_filters( 'give_sanitize_amount', $number );
364
}
365
366
/**
367
 * Returns a nicely formatted amount.
368
 *
369
 * @since 1.0
370
 *
371
 * @param string $amount Price amount to format
372
 * @param array  $args   Array of arguments.
373
 *
374
 * @return string $amount   Newly formatted amount or Price Not Available
375
 */
376
function give_format_amount( $amount, $args = array() ) {
377
	// Backward compatibility.
378
	if ( is_bool( $args ) ) {
379
		$args = array(
380
			'decimal' => $args,
381
		);
382
	}
383
384
	$default_args = array(
385
		'decimal'     => true,
386
		'sanitize'    => true,
387
		'donation_id' => 0,
388
		'currency'    => '',
389
	);
390
391
	$args = wp_parse_args( $args, $default_args );
392
393
	// Set Currency based on donation id, if required.
394
	if ( $args['donation_id'] && empty( $args['currency'] ) ) {
395
		$args['currency'] = give_get_meta( $args['donation_id'], '_give_payment_currency', true );
396
	}
397
398
	$formatted     = 0;
399
	$currency      = ! empty( $args['currency'] ) ? $args['currency'] : give_get_currency( $args['donation_id'] );
400
	$thousands_sep = give_get_price_thousand_separator( $currency );
401
	$decimal_sep   = give_get_price_decimal_separator( $currency );
402
	$decimals      = ! empty( $args['decimal'] ) ? give_get_price_decimals( $currency ) : 0;
403
404
	if ( ! empty( $amount ) ) {
405
		// Sanitize amount before formatting.
406
		$amount = ! empty( $args['sanitize'] ) ?
407
			give_maybe_sanitize_amount( $amount, array( 'number_decimals' => $decimals, 'currency' => $currency ) ) :
408
			number_format( $amount, $decimals, '.', '' );
409
410
		switch ( $currency ) {
411
			case 'INR':
412
				$decimal_amount = '';
413
414
				// Extract decimals from amount
415
				if ( ( $pos = strpos( $amount, '.' ) ) !== false ) {
0 ignored issues
show
introduced by
Found "!== false". Use Yoda Condition checks, you must
Loading history...
416
					if ( ! empty( $decimals ) ) {
417
						$decimal_amount = substr( round( substr( $amount, $pos ), $decimals ), 1 );
418
						$amount         = substr( $amount, 0, $pos );
419
420
						if ( ! $decimal_amount ) {
421
							$decimal_amount = substr( "{$decimal_sep}0000000000", 0, ( $decimals + 1 ) );
422
						} elseif ( ( $decimals + 1 ) > strlen( $decimal_amount ) ) {
423
							$decimal_amount = substr( "{$decimal_amount}000000000", 0, ( $decimals + 1 ) );
424
						}
425
					} else {
426
						$amount = number_format( $amount, $decimals, $decimal_sep, '' );
427
					}
428
				}
429
430
				// Extract last 3 from amount
431
				$result = substr( $amount, - 3 );
432
				$amount = substr( $amount, 0, - 3 );
433
434
				// Apply digits 2 by 2
435
				while ( strlen( $amount ) > 0 ) {
436
					$result = substr( $amount, - 2 ) . $thousands_sep . $result;
437
					$amount = substr( $amount, 0, - 2 );
438
				}
439
440
				$formatted = $result . $decimal_amount;
441
				break;
442
443
			default:
444
				$formatted = number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
445
		}
446
	}
447
448
	/**
449
	 * Filter the formatted amount
450
	 *
451
	 * @since 1.0
452
	 */
453
	return apply_filters( 'give_format_amount', $formatted, $amount, $decimals, $decimal_sep, $thousands_sep, $currency, $args );
454
}
455
456
457
/**
458
 * Get human readable amount.
459
 *
460
 * Note: This function only support large number formatting from million to trillion
461
 *
462
 * @since 1.6
463
 *
464
 * @use   give_get_price_thousand_separator Get thousand separator.
465
 *
466
 * @param string $amount formatted amount number.
467
 * @param array  $args   Array of arguments.
468
 *
469
 * @return string  formatted amount number with large number names.
470
 */
471
function give_human_format_large_amount( $amount, $args = array() ) {
472
	// Sanitize amount.
473
	$sanitize_amount = give_maybe_sanitize_amount( $amount );
474
475
	// Bailout.
476
	if ( ! floatval( $sanitize_amount ) ) {
477
		return '0';
478
	};
479
480
	// Set default currency;
481
	if ( empty( $args['currency'] ) ) {
482
		$args['currency'] = give_get_currency();
483
	}
484
485
	// Get thousand separator.
486
	$thousands_sep = give_get_price_thousand_separator();
487
488
	// Explode amount to calculate name of large numbers.
489
	$amount_array = explode( $thousands_sep, $amount );
490
491
	// Calculate amount parts count.
492
	$amount_count_parts = count( $amount_array );
493
494
	// Human format amount (default).
495
	$human_format_amount = $amount;
496
497
	switch ( $args['currency'] ) {
498 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...
499
			// Calculate large number formatted amount.
500
			if ( 4 < $amount_count_parts ) {
501
				$human_format_amount = sprintf( esc_html__( '%s arab', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
502
			} elseif ( 3 < $amount_count_parts ) {
503
				$human_format_amount = sprintf( esc_html__( '%s crore', 'give' ), round( ( $sanitize_amount / 10000000 ), 2 ) );
504
			} elseif ( 2 < $amount_count_parts ) {
505
				$human_format_amount = sprintf( esc_html__( '%s lakh', 'give' ), round( ( $sanitize_amount / 100000 ), 2 ) );
506
			}
507
			break;
508 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...
509
			// Calculate large number formatted amount.
510
			if ( 4 < $amount_count_parts ) {
511
				$human_format_amount = sprintf( esc_html__( '%s trillion', 'give' ), round( ( $sanitize_amount / 1000000000000 ), 2 ) );
512
			} elseif ( 3 < $amount_count_parts ) {
513
				$human_format_amount = sprintf( esc_html__( '%s billion', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
514
			} elseif ( 2 < $amount_count_parts ) {
515
				$human_format_amount = sprintf( esc_html__( '%s million', 'give' ), round( ( $sanitize_amount / 1000000 ), 2 ) );
516
			}
517
	}
518
519
	return apply_filters( 'give_human_format_large_amount', $human_format_amount, $amount, $sanitize_amount );
520
}
521
522
/**
523
 * Returns a nicely formatted amount with custom decimal separator.
524
 *
525
 * @since 1.0
526
 *
527
 * @param int|float|string $amount   Formatted or sanitized price
528
 * @param int|bool         $dp       number of decimals
529
 * @param bool             $sanitize Whether or not sanitize number
530
 *
531
 * @return string $amount Newly formatted amount or Price Not Available
532
 */
533
function give_format_decimal( $amount, $dp = false, $sanitize = true ) {
534
	$decimal_separator = give_get_price_decimal_separator();
535
	$formatted_amount  = $sanitize ?
536
		give_maybe_sanitize_amount( $amount, array( 'number_decimals' => $dp ) ) :
537
		number_format( $amount, ( is_bool( $dp ) ? give_get_price_decimals() : $dp ), '.', '' );
538
539
	if ( false !== strpos( $formatted_amount, '.' ) ) {
540
		$formatted_amount = str_replace( '.', $decimal_separator, $formatted_amount );
541
	}
542
543
	return apply_filters( 'give_format_decimal', $formatted_amount, $amount, $decimal_separator );
544
}
545
546
/**
547
 * Get date format string on basis of given context.
548
 *
549
 * @since 1.7
550
 *
551
 * @param  string $date_context Date format context name.
552
 *
553
 * @return string                  Date format string
554
 */
555
function give_date_format( $date_context = '' ) {
556
	/**
557
	 * Filter the date context
558
	 *
559
	 * You can add your own date context or use already exist context.
560
	 * For example:
561
	 *    add_filter( 'give_date_format_contexts', 'add_new_date_contexts' );
562
	 *    function add_new_date_contexts( $date_format_contexts ) {
563
	 *        // You can add single context like this $date_format_contexts['checkout'] = 'F j, Y';
564
	 *        // Instead add multiple date context at once.
565
	 *        $new_date_format_contexts = array(
566
	 *            'checkout' => 'F j, Y',
567
	 *            'report'   => 'Y-m-d',
568
	 *            'email'    => 'm/d/Y',
569
	 *        );
570
	 *
571
	 *       // Merge date contexts array only if you are adding multiple date contexts at once otherwise return  $date_format_contexts.
572
	 *       return array_merge( $new_date_format_contexts, $date_format_contexts );
573
	 *
574
	 *    }
575
	 */
576
	$date_format_contexts = apply_filters( 'give_date_format_contexts', array() );
577
578
	// Set date format to default date format.
579
	$date_format = get_option( 'date_format' );
580
581
	// Update date format if we have non empty date format context array and non empty date format string for that context.
582
	if ( $date_context && ! empty( $date_format_contexts ) && array_key_exists( $date_context, $date_format_contexts ) ) {
583
		$date_format = ! empty( $date_format_contexts[ $date_context ] )
584
			? $date_format_contexts[ $date_context ]
585
			: $date_format;
586
	}
587
588
	return apply_filters( 'give_date_format', $date_format );
589
}
590
591
/**
592
 * Get cache key.
593
 *
594
 * @since      1.7
595
 * @deprecated 1.8.7 You can access this function from Give_Cache.
596
 *
597
 * @param  string $action     Cache key prefix.
598
 * @param array  $query_args Query array.
599
 *
600
 * @return string
601
 */
602
function give_get_cache_key( $action, $query_args ) {
603
	return Give_Cache::get_key( $action, $query_args );
604
}
605
606
/**
607
 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
608
 * Non-scalar values are ignored.
609
 *
610
 * @since  1.8
611
 *
612
 * @param  string|array $var
613
 *
614
 * @return string|array
615
 */
616
function give_clean( $var ) {
617
	if ( is_array( $var ) ) {
618
		return array_map( 'give_clean', $var );
619
	} else {
620
		return is_scalar( $var ) ? sanitize_text_field( wp_unslash( $var ) ) : $var;
621
	}
622
}
623
624
/**
625
 * Transforms php.ini notation for numbers (like '2M') to an integer.
626
 *
627
 * @since 1.8
628
 *
629
 * @param $size
630
 *
631
 * @return int
632
 */
633
function give_let_to_num( $size ) {
634
	$l   = substr( $size, - 1 );
635
	$ret = substr( $size, 0, - 1 );
636
	switch ( strtoupper( $l ) ) {
637
		case 'P':
638
			$ret *= 1024;
639
		case 'T':
640
			$ret *= 1024;
641
		case 'G':
642
			$ret *= 1024;
643
		case 'M':
644
			$ret *= 1024;
645
		case 'K':
646
			$ret *= 1024;
647
	}
648
649
	return $ret;
650
}
651
652
/**
653
 * Verify nonce.
654
 *
655
 * @since 1.8
656
 *
657
 * @param string $nonce       Nonce Hash.
658
 * @param int    $action      Nonce verification action.
659
 * @param array  $wp_die_args Nonce fail arguments.
660
 *
661
 * @return bool
662
 */
663
function give_validate_nonce( $nonce, $action = - 1, $wp_die_args = array() ) {
664
665
	// Verify nonce.
666
	$verify_nonce = wp_verify_nonce( $nonce, $action );
667
668
	// On ajax request send nonce verification status.
669
	if ( wp_doing_ajax() ) {
670
		return $verify_nonce;
671
	}
672
673
	if ( ! $verify_nonce ) {
674
		$wp_die_args = wp_parse_args(
675
			$wp_die_args,
676
			array(
677
				'message' => __( 'Nonce verification has failed.', 'give' ),
678
				'title'   => __( 'Error', 'give' ),
679
				'args'    => array(
680
					'response' => 403,
681
				),
682
			)
683
		);
684
685
		wp_die(
686
			$wp_die_args['message'],
687
			$wp_die_args['title'],
688
			$wp_die_args['args']
689
		);
690
	}
691
692
	return true;
693
}
694
695
/**
696
 * Verify nonce while processing donation form.
697
 *
698
 * @since 2.0
699
 *
700
 * @param string $nonce   Nonce value.
701
 * @param int    $form_id Donation Form ID.
702
 *
703
 * @return bool
704
 */
705
function give_verify_donation_form_nonce( $nonce = '', $form_id ) {
706
707
	// Form nonce action.
708
	$nonce_action = "give_donation_form_nonce_{$form_id}";
709
710
	// Nonce validation.
711
	$verify_nonce = give_validate_nonce( $nonce, $nonce_action );
712
713
	if ( ! $verify_nonce ) {
714
		give_set_error( 'donation_form_nonce', __( 'Nonce verification has failed.', 'give' ) );
715
	}
716
717
	return $verify_nonce;
718
}
719
720
/**
721
 * Check variable and get default or valid value.
722
 *
723
 * Helper function to check if a variable is set, empty, etc.
724
 *
725
 * @since 1.8
726
 *
727
 * @param                   $variable
728
 * @param string (optional) $conditional    default value: isset
729
 * @param mixed (optional)  $default        default value: false
730
 * @param string (optional) $array_key_name default value: false
731
 *
732
 * @return mixed
733
 */
734
function give_check_variable( $variable, $conditional = '', $default = false, $array_key_name = '' ) {
735
	// Get value from array if array key non empty.
736
	if( empty( $array_key_name ) ) {
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...
737
		switch ( $conditional ) {
738
			case 'isset_empty':
739
				$variable = ( isset( $variable ) && ! empty( $variable ) ) ? $variable : $default;
740
				break;
741
742
			case 'empty':
743
				$variable = ! empty( $variable ) ? $variable : $default;
744
				break;
745
746
			case 'null':
747
				$variable = ! is_null( $variable ) ? $variable : $default;
748
				break;
749
750
			default:
751
				$variable = isset( $variable ) ? $variable : $default;
752
		}
753
	} else {
754
		$isset = array_key_exists( $array_key_name, $variable );
755
756
		switch ( $conditional ) {
757
			case 'isset_empty':
758
				$variable = ( $isset && ! empty( $variable[ $array_key_name ] ) ) ? $variable[ $array_key_name ] : $default;
759
				break;
760
761
			case 'empty':
762
				$variable = ! empty( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
763
				break;
764
765
			case 'null':
766
				$variable = $isset && ! is_null( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
767
				break;
768
769
			default:
770
				$variable = $isset && isset( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
771
		}
772
	}
773
774
	return $variable;
775
776
}
777