Test Setup Failed
Push — master ( 546b5d...f4e9ab )
by Ravinder
07:43
created

functions.php ➔ give_is_history_page()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 7
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Give Form Functions
4
 *
5
 * @package     WordImpress
6
 * @subpackage  Includes/Forms
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.1
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Filter: Do not show the Give shortcut button on Give Forms CPT
19
 *
20
 * @return bool
21
 */
22
function give_shortcode_button_condition() {
23
24
	global $typenow;
25
26
	if ( $typenow != 'give_forms' ) {
0 ignored issues
show
introduced by
Found "!= '". Use Yoda Condition checks, you must
Loading history...
27
		return true;
28
	}
29
30
	return false;
31
}
32
33
add_filter( 'give_shortcode_button_condition', 'give_shortcode_button_condition' );
34
35
36
/**
37
 * Get the form ID from the form $args
38
 *
39
 * @param array $args
40
 *
41
 * @return int|false
42
 */
43
function get_form_id_from_args( $args ) {
44
45
	if ( isset( $args['form_id'] ) && $args['form_id'] != 0 ) {
0 ignored issues
show
introduced by
Found "!= 0". Use Yoda Condition checks, you must
Loading history...
46
47
		return intval( $args['form_id'] );
48
	}
49
50
	return false;
51
}
52
53
/**
54
 * Checks whether floating labels is enabled for the form ID in $args
55
 *
56
 * @since 1.1
57
 *
58
 * @param array $args
59
 *
60
 * @return bool
61
 */
62
function give_is_float_labels_enabled( $args ) {
63
64
	$float_labels = '';
65
66
	if ( ! empty( $args['float_labels'] ) ) {
67
		$float_labels = $args['float_labels'];
68
	}
69
70
	if ( empty( $float_labels ) ) {
71
		$float_labels = give_get_meta( $args['form_id'], '_give_form_floating_labels', true );
72
	}
73
74
	if ( empty( $float_labels ) || ( 'global' === $float_labels ) ) {
75
		$float_labels = give_get_option( 'floatlabels', 'disabled' );
76
	}
77
78
	return give_is_setting_enabled( $float_labels );
79
}
80
81
/**
82
 * Determines if a user can checkout or not
83
 *
84
 * Allows themes and plugins to set donation checkout conditions
85
 *
86
 * @since 1.0
87
 *
88
 * @return bool Can user checkout?
89
 */
90
function give_can_checkout() {
91
92
	$can_checkout = true;
93
94
	return (bool) apply_filters( 'give_can_checkout', $can_checkout );
95
}
96
97
/**
98
 * Retrieve the Success page URI
99
 *
100
 * @access      public
101
 * @since       1.0
102
 *
103
 * @return      string
104
 */
105 View Code Duplication
function give_get_success_page_uri() {
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...
106
	$give_options = give_get_settings();
107
108
	$success_page = isset( $give_options['success_page'] ) ? get_permalink( absint( $give_options['success_page'] ) ) : get_bloginfo( 'url' );
109
110
	return apply_filters( 'give_get_success_page_uri', $success_page );
111
}
112
113
/**
114
 * Determines if we're currently on the Success page.
115
 *
116
 * @since 1.0
117
 *
118
 * @return bool True if on the Success page, false otherwise.
119
 */
120
function give_is_success_page() {
121
	return apply_filters( 'give_is_success_page', is_page( give_get_success_page_uri() ) );
122
}
123
124
/**
125
 * Send To Success Page
126
 *
127
 * Sends the user to the success page.
128
 *
129
 * @param string $query_string
130
 *
131
 * @access      public
132
 * @since       1.0
133
 * @return      void
134
 */
135
function give_send_to_success_page( $query_string = null ) {
136
137
	$redirect = give_get_success_page_uri();
138
139
	if ( $query_string ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query_string of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
		$redirect .= $query_string;
141
	}
142
143
	$gateway = isset( $_REQUEST['give-gateway'] ) ? $_REQUEST['give-gateway'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
144
145
	wp_redirect( apply_filters( 'give_success_page_redirect', $redirect, $gateway, $query_string ) );
146
	give_die();
147
}
148
149
150
/**
151
 * Send back to donation form.
152
 *
153
 * Used to redirect a user back to the donation form if there are errors present.
154
 *
155
 * @param array|string $args
156
 *
157
 * @access public
158
 * @since  1.0
159
 * @return Void
160
 */
161
function give_send_back_to_checkout( $args = array() ) {
162
163
	$url     = isset( $_POST['give-current-url'] ) ? sanitize_text_field( $_POST['give-current-url'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
164
	$form_id = 0;
165
166
	// Set the form_id.
167
	if ( isset( $_POST['give-form-id'] ) ) {
168
		$form_id = sanitize_text_field( $_POST['give-form-id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
169
	}
170
171
	// Need a URL to continue. If none, redirect back to single form.
172
	if ( empty( $url ) ) {
173
		wp_safe_redirect( get_permalink( $form_id ) );
174
		give_die();
175
	}
176
177
	$defaults = array(
178
		'form-id' => (int) $form_id,
179
	);
180
181
	// Set the $level_id.
182
	if ( isset( $_POST['give-price-id'] ) ) {
183
		$defaults['level-id'] = sanitize_text_field( $_POST['give-price-id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
184
	}
185
186
	// Check for backward compatibility.
187
	if ( is_string( $args ) ) {
188
		$args = str_replace( '?', '', $args );
189
	}
190
191
	$args = wp_parse_args( $args, $defaults );
192
193
	// Merge URL query with $args to maintain third-party URL parameters after redirect.
194
	$url_data = wp_parse_url( $url );
195
196
	// Check if an array to prevent notices before parsing.
197
	if ( isset( $url_data['query'] ) && ! empty( $url_data['query'] ) ) {
198
		parse_str( $url_data['query'], $query );
199
200
		// Precaution: don't allow any CC info.
201
		unset( $query['card_number'] );
202
		unset( $query['card_cvc'] );
203
204
	} else {
205
		// No $url_data so pass empty array.
206
		$query = array();
207
	}
208
209
	$new_query        = array_merge( $args, $query );
210
	$new_query_string = http_build_query( $new_query );
211
212
	// Assemble URL parts.
213
	$redirect = home_url( '/' . $url_data['path'] . '?' . $new_query_string . '#give-form-' . $form_id . '-wrap' );
214
215
	// Redirect them.
216
	wp_safe_redirect( apply_filters( 'give_send_back_to_checkout', $redirect, $args ) );
217
	give_die();
218
219
}
220
221
/**
222
 * Get Success Page URL
223
 *
224
 * Gets the success page URL.
225
 *
226
 * @param string $query_string
227
 *
228
 * @access      public
229
 * @since       1.0
230
 * @return      string
231
 */
232
function give_get_success_page_url( $query_string = null ) {
233
234
	$success_page = give_get_option( 'success_page', 0 );
235
	$success_page = get_permalink( $success_page );
236
237
	if ( $query_string ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query_string of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
238
		$success_page .= $query_string;
239
	}
240
241
	return apply_filters( 'give_success_page_url', $success_page );
242
243
}
244
245
/**
246
 * Get the URL of the Failed Donation Page.
247
 *
248
 * @since 1.0
249
 *
250
 * @param bool $extras Extras to append to the URL.
251
 *
252
 * @return mixed Full URL to the Failed Donation Page, if present, home page if it doesn't exist.
253
 */
254
function give_get_failed_transaction_uri( $extras = false ) {
255
	$give_options = give_get_settings();
256
257
	// Remove question mark.
258
	if ( 0 === strpos( $extras, '?' ) ) {
259
		$extras = substr( $extras, 1 );
260
	}
261
262
	$extras_args = wp_parse_args( $extras );
263
264
	// Set nonce if payment id exist in extra params.
265
	if ( array_key_exists( 'payment-id', $extras_args ) ) {
266
		$extras_args['_wpnonce'] = wp_create_nonce( "give-failed-donation-{$extras_args['payment-id']}" );
267
		$extras                  = http_build_query( $extras_args );
268
	}
269
270
	$uri = ! empty( $give_options['failure_page'] ) ?
271
		trailingslashit( get_permalink( $give_options['failure_page'] ) ) :
272
		home_url();
273
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
274
275
	if ( $extras ) {
276
		$uri .= "?{$extras}";
277
	}
278
279
	return apply_filters( 'give_get_failed_transaction_uri', $uri );
280
}
281
282
/**
283
 * Determines if we're currently on the Failed Donation Page.
284
 *
285
 * @since 1.0
286
 * @return bool True if on the Failed Donation Page, false otherwise.
287
 */
288
function give_is_failed_transaction_page() {
289
	$give_options = give_get_settings();
290
	$ret          = isset( $give_options['failure_page'] ) ? is_page( $give_options['failure_page'] ) : false;
291
292
	return apply_filters( 'give_is_failure_page', $ret );
293
}
294
295
/**
296
 * Mark payments as Failed when returning to the Failed Donation Page
297
 *
298
 * @since  1.0
299
 * @since  1.8.16 Add security check
300
 *
301
 * @return bool
302
 */
303
function give_listen_for_failed_payments() {
304
305
	$failed_page = give_get_option( 'failure_page', 0 );
306
	$payment_id  = ! empty( $_GET['payment-id'] ) ? absint( $_GET['payment-id'] ) : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
307
	$nonce       = ! empty( $_GET['_wpnonce'] ) ? give_clean( $_GET['_wpnonce'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
308
309
	// Bailout.
310
	if ( ! $failed_page || ! is_page( $failed_page ) || ! $payment_id || ! $nonce ) {
311
		return false;
312
	}
313
314
	// Security check.
315
	if ( ! wp_verify_nonce( $nonce, "give-failed-donation-{$payment_id}" ) ) {
316
		wp_die( __( 'Nonce verification failed.', 'give' ), __( 'Error', 'give' ) );
317
	}
318
319
	// Set payment status to failure
320
	give_update_payment_status( $payment_id, 'failed' );
321
}
322
323
add_action( 'template_redirect', 'give_listen_for_failed_payments' );
324
325
/**
326
 * Retrieve the Donation History page URI
327
 *
328
 * @access      public
329
 * @since       1.7
330
 *
331
 * @return      string
332
 */
333 View Code Duplication
function give_get_history_page_uri() {
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...
334
	$give_options = give_get_settings();
335
336
	$history_page = isset( $give_options['history_page'] ) ? get_permalink( absint( $give_options['history_page'] ) ) : get_bloginfo( 'url' );
337
338
	return apply_filters( 'give_get_history_page_uri', $history_page );
339
}
340
341
/**
342
 * Determines if we're currently on the History page.
343
 *
344
 * @since 1.0
345
 *
346
 * @return bool True if on the History page, false otherwise.
347
 */
348 View Code Duplication
function give_is_history_page() {
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...
349
	$give_options = give_get_settings();
350
351
	$history_page = isset( $give_options['history_page'] ) ? absint( $give_options['history_page'] ) : 0;
352
353
	return apply_filters( 'give_is_history_page', is_page( $history_page ) );
354
}
355
356
/**
357
 * Check if a field is required
358
 *
359
 * @param string $field
360
 * @param int    $form_id
361
 *
362
 * @access      public
363
 * @since       1.0
364
 * @return      bool
365
 */
366
function give_field_is_required( $field = '', $form_id ) {
367
368
	$required_fields = give_get_required_fields( $form_id );
369
370
	return array_key_exists( $field, $required_fields );
371
}
372
373
/**
374
 * Record Donation In Log
375
 *
376
 * Stores log information for a donation.
377
 *
378
 * @since 1.0
379
 *
380
 * @param int         $give_form_id  Give Form ID.
381
 * @param int         $payment_id    Payment ID.
382
 * @param bool|int    $price_id      Price ID, if any.
383
 * @param string|null $donation_date The date of the donation.
384
 *
385
 * @return void
386
 */
387
function give_record_donation_in_log( $give_form_id = 0, $payment_id, $price_id = false, $donation_date = null ) {
388
	$log_data = array(
389
		'log_parent'   => $payment_id,
390
		'log_type'     => 'sale',
391
		'log_date'     => isset( $donation_date ) ? $donation_date : null,
392
		'log_date_gmt' => isset( $donation_date ) ? $donation_date : null,
393
	);
394
395
	$log_meta = array(
396
		'form_id'  => $give_form_id,
397
		'price_id' => (int) $price_id,
398
	);
399
400
	Give()->logs->insert_log( $log_data, $log_meta );
401
}
402
403
404
/**
405
 * Increases the donation total count of a donation form.
406
 *
407
 * @since 1.0
408
 *
409
 * @param int $form_id  Give Form ID
410
 * @param int $quantity Quantity to increase donation count by
411
 *
412
 * @return bool|int
413
 */
414
function give_increase_donation_count( $form_id = 0, $quantity = 1 ) {
415
	$quantity = (int) $quantity;
416
417
	/** @var \Give_Donate_Form $form */
418
	$form = new Give_Donate_Form( $form_id );
419
420
	return $form->increase_sales( $quantity );
421
}
422
423
/**
424
 * Decreases the sale count of a form. Primarily for when a donation is refunded.
425
 *
426
 * @since 1.0
427
 *
428
 * @param int $form_id  Give Form ID
429
 * @param int $quantity Quantity to increase donation count by
430
 *
431
 * @return bool|int
432
 */
433
function give_decrease_donation_count( $form_id = 0, $quantity = 1 ) {
434
	$quantity = (int) $quantity;
435
436
	/** @var \Give_Donate_Form $form */
437
	$form = new Give_Donate_Form( $form_id );
438
439
	return $form->decrease_sales( $quantity );
440
}
441
442
/**
443
 * Increases the total earnings of a form.
444
 *
445
 * @since 1.0
446
 *
447
 * @since 2.1 Pass donation id.
448
 *
449
 * @param int $give_form_id Give Form ID
450
 * @param int $amount       Earnings
451
 * @param int $payment_id   Donation ID.
452
 *
453
 * @return bool|int
454
 */
455
function give_increase_earnings( $give_form_id = 0, $amount, $payment_id = 0 ) {
456
	/** @var \Give_Donate_Form $form */
457
	$form = new Give_Donate_Form( $give_form_id );
458
459
	return $form->increase_earnings( $amount, $payment_id );
460
}
461
462
/**
463
 * Decreases the total earnings of a form.
464
 *
465
 * Primarily for when a donation is refunded.
466
 *
467
 * @since 1.0
468
 *
469
 * @since 2.1 Pass donation id.
470
 *
471
 * @param int $form_id    Give Form ID
472
 * @param int $amount     Earnings
473
 * @param int $payment_id Donation ID.
474
 *
475
 * @return bool|int
476
 */
477
function give_decrease_form_earnings( $form_id = 0, $amount, $payment_id = 0 ) {
478
	/** @var \Give_Donate_Form $form */
479
	$form = new Give_Donate_Form( $form_id );
480
481
	return $form->decrease_earnings( $amount, $payment_id );
482
}
483
484
485
/**
486
 * Returns the total earnings for a form.
487
 *
488
 * @since 1.0
489
 *
490
 * @param int $form_id Give Form ID
491
 *
492
 * @return int $earnings Earnings for a certain form
493
 */
494
function give_get_form_earnings_stats( $form_id = 0 ) {
495
	$give_form = new Give_Donate_Form( $form_id );
496
497
	/**
498
	 * Filter the form earnings
499
	 *
500
	 * @since 1.8.17
501
	 */
502
	return apply_filters( 'give_get_form_earnings_stats', $give_form->earnings, $form_id, $give_form );
503
}
504
505
506
/**
507
 * Return the sales number for a form.
508
 *
509
 * @since 1.0
510
 *
511
 * @param int $give_form_id Give Form ID
512
 *
513
 * @return int $sales Amount of sales for a certain form
514
 */
515
function give_get_form_sales_stats( $give_form_id = 0 ) {
516
	$give_form = new Give_Donate_Form( $give_form_id );
517
518
	return $give_form->sales;
519
}
520
521
522
/**
523
 * Retrieves the average monthly sales for a specific donation form
524
 *
525
 * @since 1.0
526
 *
527
 * @param int $form_id Form ID
528
 *
529
 * @return float $sales Average monthly sales
530
 */
531 View Code Duplication
function give_get_average_monthly_form_sales( $form_id = 0 ) {
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...
532
	$sales        = give_get_form_sales_stats( $form_id );
533
	$release_date = get_post_field( 'post_date', $form_id );
534
535
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
536
537
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
538
539
	if ( $months > 0 ) {
540
		$sales = ( $sales / $months );
541
	}
542
543
	return $sales;
544
}
545
546
547
/**
548
 * Retrieves the average monthly earnings for a specific form
549
 *
550
 * @since 1.0
551
 *
552
 * @param int $form_id Form ID
553
 *
554
 * @return float $earnings Average monthly earnings
555
 */
556 View Code Duplication
function give_get_average_monthly_form_earnings( $form_id = 0 ) {
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...
557
	$earnings     = give_get_form_earnings_stats( $form_id );
558
	$release_date = get_post_field( 'post_date', $form_id );
559
560
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
561
562
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
563
564
	if ( $months > 0 ) {
565
		$earnings = ( $earnings / $months );
566
	}
567
568
	return $earnings < 0 ? 0 : $earnings;
569
}
570
571
572
/**
573
 * Get Price Option Name (Text)
574
 *
575
 * Retrieves the name of a variable price option.
576
 *
577
 * @since       1.0
578
 *
579
 * @param int  $form_id      ID of the donation form.
580
 * @param int  $price_id     ID of the price option.
581
 * @param int  $payment_id   payment ID for use in filters ( optional ).
582
 * @param bool $use_fallback Outputs the level amount if no level text is provided.
583
 *
584
 * @return string $price_name Name of the price option
585
 */
586
function give_get_price_option_name( $form_id = 0, $price_id = 0, $payment_id = 0, $use_fallback = true ) {
587
588
	$prices     = give_get_variable_prices( $form_id );
589
	$price_name = '';
590
591
	if ( false === $prices ) {
592
		return $price_name;
593
	}
594
595
	foreach ( $prices as $price ) {
596
597
		if ( intval( $price['_give_id']['level_id'] ) === intval( $price_id ) ) {
598
599
			$price_text     = isset( $price['_give_text'] ) ? $price['_give_text'] : '';
600
			$price_fallback = $use_fallback ?
601
				give_currency_filter(
602
					give_format_amount(
603
						$price['_give_amount'],
604
						array( 'sanitize' => false )
605
					),
606
					array( 'decode_currency' => true )
607
				) : '';
608
			$price_name     = ! empty( $price_text ) ? $price_text : $price_fallback;
609
610
		}
611
	}
612
613
	return apply_filters( 'give_get_price_option_name', $price_name, $form_id, $payment_id, $price_id );
614
}
615
616
617
/**
618
 * Retrieves a price from from low to high of a variable priced form
619
 *
620
 * @since 1.0
621
 *
622
 * @param int  $form_id   ID of the form
623
 * @param bool $formatted Flag to decide which type of price range string return
624
 *
625
 * @return string $range A fully formatted price range
626
 */
627
function give_price_range( $form_id = 0, $formatted = true ) {
628
	$low        = give_get_lowest_price_option( $form_id );
629
	$high       = give_get_highest_price_option( $form_id );
630
	$order_type = ! empty( $_REQUEST['order'] ) ? $_REQUEST['order'] : 'asc';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
631
632
	$range = sprintf(
633
		'<span class="give_price_range_%1$s">%2$s</span><span class="give_price_range_sep">&nbsp;&ndash;&nbsp;</span><span class="give_price_range_%3$s">%4$s</span>',
634
		'asc' === $order_type ? 'low' : 'high',
635
		'asc' === $order_type ? give_currency_filter( give_format_amount( $low, array( 'sanitize' => false ) ) ) : give_currency_filter( give_format_amount( $high, array( 'sanitize' => false ) ) ),
636
		'asc' === $order_type ? 'high' : 'low',
637
		'asc' === $order_type ? give_currency_filter( give_format_amount( $high, array( 'sanitize' => false ) ) ) : give_currency_filter( give_format_amount( $low, array( 'sanitize' => false ) ) )
638
0 ignored issues
show
Coding Style introduced by
There should be no empty lines in a multi-line function call.
Loading history...
639
	);
640
641
	if ( ! $formatted ) {
642
		$range = wp_strip_all_tags( $range );
643
	}
644
645
	return apply_filters( 'give_price_range', $range, $form_id, $low, $high );
646
}
647
648
649
/**
650
 * Get Lowest Price ID
651
 *
652
 * Retrieves the ID for the cheapest price option of a variable donation form
653
 *
654
 * @since 1.5
655
 *
656
 * @param int $form_id ID of the donation
657
 *
658
 * @return int ID of the lowest price
659
 */
660
function give_get_lowest_price_id( $form_id = 0 ) {
661
662
	if ( empty( $form_id ) ) {
663
		$form_id = get_the_ID();
664
	}
665
666
	if ( ! give_has_variable_prices( $form_id ) ) {
667
		return give_get_form_price( $form_id );
668
	}
669
670
	$prices = give_get_variable_prices( $form_id );
671
672
	$min = $min_id = 0;
673
674
	if ( ! empty( $prices ) ) {
675
676
		foreach ( $prices as $key => $price ) {
677
678
			if ( empty( $price['_give_amount'] ) ) {
679
				continue;
680
			}
681
682
			if ( ! isset( $min ) ) {
683
				$min = $price['_give_amount'];
684
			} else {
685
				$min = min( $min, $price['_give_amount'] );
686
			}
687
688
			if ( $price['_give_amount'] == $min ) {
689
				$min_id = $price['_give_id']['level_id'];
690
			}
691
		}
692
	}
693
694
	return (int) $min_id;
695
}
696
697
/**
698
 * Retrieves cheapest price option of a variable priced form
699
 *
700
 * @since 1.0
701
 *
702
 * @param int $form_id ID of the form
703
 *
704
 * @return float Amount of the lowest price
705
 */
706 View Code Duplication
function give_get_lowest_price_option( $form_id = 0 ) {
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...
707
	if ( empty( $form_id ) ) {
708
		$form_id = get_the_ID();
709
	}
710
711
	if ( ! give_has_variable_prices( $form_id ) ) {
712
		return give_get_form_price( $form_id );
713
	}
714
715
	if ( ! ( $low = get_post_meta( $form_id, '_give_levels_minimum_amount', true ) ) ) {
716
		// Backward compatibility.
717
		$prices = wp_list_pluck( give_get_variable_prices( $form_id ), '_give_amount' );
718
		$low    = ! empty( $prices ) ? min( $prices ) : 0;
719
	}
720
721
	return give_maybe_sanitize_amount( $low );
722
}
723
724
/**
725
 * Retrieves most expensive price option of a variable priced form
726
 *
727
 * @since 1.0
728
 *
729
 * @param int $form_id ID of the form
730
 *
731
 * @return float Amount of the highest price
732
 */
733 View Code Duplication
function give_get_highest_price_option( $form_id = 0 ) {
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...
734
735
	if ( empty( $form_id ) ) {
736
		$form_id = get_the_ID();
737
	}
738
739
	if ( ! give_has_variable_prices( $form_id ) ) {
740
		return give_get_form_price( $form_id );
741
	}
742
743
	if ( ! ( $high = get_post_meta( $form_id, '_give_levels_maximum_amount', true ) ) ) {
744
		// Backward compatibility.
745
		$prices = wp_list_pluck( give_get_variable_prices( $form_id ), '_give_amount' );
746
		$high   = ! empty( $prices ) ? max( $prices ) : 0;
747
	}
748
749
	return give_maybe_sanitize_amount( $high );
750
}
751
752
/**
753
 * Returns the price of a form, but only for non-variable priced forms.
754
 *
755
 * @since 1.0
756
 *
757
 * @param int $form_id ID number of the form to retrieve a price for
758
 *
759
 * @return mixed string|int Price of the form
760
 */
761
function give_get_form_price( $form_id = 0 ) {
762
763
	if ( empty( $form_id ) ) {
764
		return false;
765
	}
766
767
	$form = new Give_Donate_Form( $form_id );
768
769
	return $form->__get( 'price' );
770
}
771
772
/**
773
 * Returns the minimum price amount of a form, only enforced for the custom amount input.
774
 *
775
 * @since 1.3.6
776
 *
777
 * @param int $form_id ID number of the form to retrieve the minimum price for
778
 *
779
 * @return mixed string|int Minimum price of the form
780
 */
781
function give_get_form_minimum_price( $form_id = 0 ) {
782
783
	if ( empty( $form_id ) ) {
784
		return false;
785
	}
786
787
	$form = new Give_Donate_Form( $form_id );
788
789
	return $form->get_minimum_price();
790
791
}
792
793
/**
794
 * Return the maximum price amount of form.
795
 *
796
 * @since 2.1
797
 *
798
 * @param int $form_id Donate Form ID
799
 *
800
 * @return bool|float
801
 */
802
function give_get_form_maximum_price( $form_id = 0 ) {
803
804
	if ( empty( $form_id ) ) {
805
		return false;
806
	}
807
808
	$form = new Give_Donate_Form( $form_id );
809
810
	return $form->get_maximum_price();
811
}
812
813
/**
814
 * Displays a formatted price for a donation form
815
 *
816
 * @since 1.0
817
 *
818
 * @param int      $form_id  ID of the form price to show
819
 * @param bool     $echo     Whether to echo or return the results
820
 * @param bool|int $price_id Optional price id for variable pricing
821
 *
822
 * @return int $formatted_price
823
 */
824
function give_price( $form_id = 0, $echo = true, $price_id = false ) {
825
	$price = 0;
826
827
	if ( empty( $form_id ) ) {
828
		$form_id = get_the_ID();
829
	}
830
831
	if ( give_has_variable_prices( $form_id ) ) {
832
833
		$prices = give_get_variable_prices( $form_id );
834
835
		if ( false !== $price_id ) {
836
837
			// loop through multi-prices to see which is default
838
			foreach ( $prices as $price ) {
0 ignored issues
show
Bug introduced by
The expression $prices of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
839
				// this is the default price
840
				if ( isset( $price['_give_default'] ) && $price['_give_default'] === 'default' ) {
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
841
					$price = (float) $price['_give_amount'];
842
				};
843
			}
844
		} else {
845
846
			$price = give_get_lowest_price_option( $form_id );
847
		}
848
	} else {
849
850
		$price = give_get_form_price( $form_id );
851
	}
852
853
	$price           = apply_filters( 'give_form_price', give_maybe_sanitize_amount( $price ), $form_id );
854
	$formatted_price = '<span class="give_price" id="give_price_' . $form_id . '">' . $price . '</span>';
855
	$formatted_price = apply_filters( 'give_form_price_after_html', $formatted_price, $form_id, $price );
856
857
	if ( $echo ) {
858
		echo $formatted_price;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$formatted_price'
Loading history...
859
	} else {
860
		return $formatted_price;
861
	}
862
}
863
864
add_filter( 'give_form_price', 'give_format_amount', 10 );
865
add_filter( 'give_form_price', 'give_currency_filter', 20 );
866
867
868
/**
869
 * Retrieves the amount of a variable price option
870
 *
871
 * @since 1.0
872
 *
873
 * @param int $form_id  ID of the form
874
 * @param int $price_id ID of the price option
875
 *
876
 * @return float $amount Amount of the price option
877
 */
878
function give_get_price_option_amount( $form_id = 0, $price_id = 0 ) {
879
	$prices = give_get_variable_prices( $form_id );
880
881
	$amount = 0.00;
882
883 View Code Duplication
	foreach ( $prices as $price ) {
0 ignored issues
show
Bug introduced by
The expression $prices of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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...
884
		if ( isset( $price['_give_id']['level_id'] ) && $price['_give_id']['level_id'] == $price_id ) {
885
			$amount = isset( $price['_give_amount'] ) ? $price['_give_amount'] : 0.00;
886
			break;
887
		};
888
	}
889
890
	return apply_filters( 'give_get_price_option_amount', give_maybe_sanitize_amount( $amount ), $form_id, $price_id );
891
}
892
893
/**
894
 * Returns the goal of a form
895
 *
896
 * @since 1.0
897
 *
898
 * @param int $form_id ID number of the form to retrieve a goal for
899
 *
900
 * @return mixed string|int Goal of the form
901
 */
902
function give_get_form_goal( $form_id = 0 ) {
903
904
	if ( empty( $form_id ) ) {
905
		return false;
906
	}
907
908
	$form = new Give_Donate_Form( $form_id );
909
910
	return $form->goal;
911
912
}
913
914
/**
915
 * Returns the goal format of a form
916
 *
917
 * @since 2.0
918
 *
919
 * @param int $form_id ID number of the form to retrieve a goal for
920
 *
921
 * @return mixed string|int Goal of the form
922
 */
923
function give_get_form_goal_format( $form_id = 0 ) {
924
925
	if ( empty( $form_id ) ) {
926
		return false;
927
	}
928
929
	return give_get_meta( $form_id, '_give_goal_format', true );
930
931
}
932
933
/**
934
 * Display/Return a formatted goal for a donation form
935
 *
936
 * @since 1.0
937
 *
938
 * @param int  $form_id ID of the form price to show
939
 * @param bool $echo    Whether to echo or return the results
940
 *
941
 * @return string $formatted_goal
942
 */
943
function give_goal( $form_id = 0, $echo = true ) {
944
945
	if ( empty( $form_id ) ) {
946
		$form_id = get_the_ID();
947
	}
948
949
	$goal        = give_get_form_goal( $form_id );
950
	$goal_format = give_get_form_goal_format( $form_id );
951
952
	if ( 'donation' === $goal_format ) {
953
		$goal = "{$goal} donations";
954
	} else {
955
		$goal = apply_filters( 'give_form_goal', give_maybe_sanitize_amount( $goal ), $form_id );
956
	}
957
958
	$formatted_goal = sprintf(
959
		'<span class="give_price" id="give_price_%1$s">%2$s</span>',
960
		$form_id,
961
		$goal
962
	);
963
	$formatted_goal = apply_filters( 'give_form_price_after_html', $formatted_goal, $form_id, $goal );
964
965
	if ( $echo ) {
966
		echo $formatted_goal;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$formatted_goal'
Loading history...
967
	} else {
968
		return $formatted_goal;
969
	}
970
}
971
972
add_filter( 'give_form_goal', 'give_format_amount', 10 );
973
add_filter( 'give_form_goal', 'give_currency_filter', 20 );
974
975
976
/**
977
 * Checks if users can only donate when logged in
978
 *
979
 * @since  1.0
980
 *
981
 * @param  int $form_id Give form ID
982
 *
983
 * @return bool  $ret Whether or not the logged_in_only setting is set
984
 */
985 View Code Duplication
function give_logged_in_only( $form_id ) {
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...
986
	// If _give_logged_in_only is set to enable then guest can donate from that specific form.
987
	// Otherwise it is member only donation form.
988
	$val = give_get_meta( $form_id, '_give_logged_in_only', true );
989
	$val = ! empty( $val ) ? $val : 'enabled';
990
991
	$ret = ! give_is_setting_enabled( $val );
992
993
	return (bool) apply_filters( 'give_logged_in_only', $ret, $form_id );
994
}
995
996
997
/**
998
 * Checks the option for the "Register / Login Option"
999
 *
1000
 * @since 1.4.1
1001
 *
1002
 * @param int $form_id
1003
 *
1004
 * @return string
1005
 */
1006
function give_show_login_register_option( $form_id ) {
1007
1008
	$show_register_form = give_get_meta( $form_id, '_give_show_register_form', true );
1009
1010
	return apply_filters( 'give_show_register_form', $show_register_form, $form_id );
1011
1012
}
1013
1014
1015
/**
1016
 * Get pre fill form field values.
1017
 *
1018
 * Note: this function will extract form field values from give_purchase session data.
1019
 *
1020
 * @since  1.8
1021
 *
1022
 * @param  int $form_id Form ID.
1023
 *
1024
 * @return array
1025
 */
1026
function _give_get_prefill_form_field_values( $form_id ) {
1027
	$logged_in_donor_info = array();
1028
1029
	if ( is_user_logged_in() ) :
1030
		$donor_data    = get_userdata( get_current_user_id() );
1031
		$donor         = new Give_Donor( get_current_user_id(), true );
1032
		$donor_address = $donor->get_donor_address();
1033
		$company_name  = $donor->get_company_name();
1034
1035
		$logged_in_donor_info = array(
1036
			// First name.
1037
			'give_first'      => $donor_data->first_name,
1038
1039
			// Last name.
1040
			'give_last'       => $donor_data->last_name,
1041
1042
			// Title Prefix.
1043
			'give_title'      => $donor->get_meta( '_give_donor_title_prefix', true ),
1044
1045
			// Company name.
1046
			'company_name'    => $company_name,
1047
1048
			// Email.
1049
			'give_email'      => $donor_data->user_email,
1050
1051
			// Street address 1.
1052
			'card_address'    => $donor_address['line1'],
1053
1054
			// Street address 2.
1055
			'card_address_2'  => $donor_address['line2'],
1056
1057
			// Country.
1058
			'billing_country' => $donor_address['country'],
1059
1060
			// State.
1061
			'card_state'      => $donor_address['state'],
1062
1063
			// City.
1064
			'card_city'       => $donor_address['city'],
1065
1066
			// Zipcode
1067
			'card_zip'        => $donor_address['zip'],
1068
		);
1069
	endif;
1070
1071
	// Bailout: Auto fill form field values only form form which donor is donating.
1072
	if (
1073
		empty( $_GET['form-id'] )
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
1074
		|| ! $form_id
1075
		|| ( $form_id !== absint( $_GET['form-id'] ) )
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
1076
	) {
1077
		return $logged_in_donor_info;
1078
	}
1079
1080
	// Get purchase data.
1081
	$give_purchase_data = Give()->session->get( 'give_purchase' );
1082
1083
	// Get donor info from form data.
1084
	$give_donor_info_in_session = empty( $give_purchase_data['post_data'] )
1085
		? array()
1086
		: $give_purchase_data['post_data'];
1087
1088
	// Output.
1089
	return wp_parse_args( $give_donor_info_in_session, $logged_in_donor_info );
1090
}
1091
1092
/**
1093
 * Get donor count of form
1094
 *
1095
 * @since 2.1.0
1096
 *
1097
 * @param int   $form_id
1098
 * @param array $args
1099
 *
1100
 * @return int
1101
 */
1102
function give_get_form_donor_count( $form_id, $args = array() ) {
1103
	global $wpdb;
1104
1105
	$cache_key   = Give_Cache::get_key( "form_donor_count_{$form_id}", $args, false );
1106
	$donor_count = absint( Give_Cache::get_db_query( $cache_key ) );
1107
1108
	if ( $form_id && ! $donor_count ) {
1109
		// Set arguments.
1110
		$args = wp_parse_args(
1111
			$args,
1112
			array(
1113
				'unique' => true,
1114
			)
1115
		);
1116
1117
		$donation_meta_table  = Give()->payment_meta->table_name;
1118
		$donation_id_col_name = Give()->payment_meta->get_meta_type() . '_id';
1119
1120
		$distinct = $args['unique'] ? 'DISTINCT meta_value' : 'meta_value';
1121
1122
		$query = $wpdb->prepare(
1123
			"
1124
			SELECT COUNT({$distinct})
1125
			FROM {$donation_meta_table}
1126
			WHERE meta_key=%s
1127
			AND {$donation_id_col_name} IN(
1128
				SELECT {$donation_id_col_name}
1129
				FROM {$donation_meta_table} as pm
1130
				INNER JOIN {$wpdb->posts} as p
1131
				ON pm.{$donation_id_col_name}=p.ID
1132
				WHERE pm.meta_key=%s
1133
				AND pm.meta_value=%s
1134
				AND p.post_status=%s
1135
			)
1136
			",
1137
			'_give_payment_donor_id',
1138
			'_give_payment_form_id',
1139
			$form_id,
1140
			'publish'
1141
		);
1142
1143
		$donor_count = absint( $wpdb->get_var( $query ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
1144
	}
1145
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1146
1147
	/**
1148
	 * Filter the donor count
1149
	 *
1150
	 * @since 2.1.0
1151
	 */
1152
	$donor_count = apply_filters( 'give_get_form_donor_count', $donor_count, $form_id, $args );
1153
1154
	return $donor_count;
1155
}
1156
1157
/**
1158
 * Verify the form status.
1159
 *
1160
 * @param int $form_id Donation Form ID.
1161
 *
1162
 * @since 2.1
1163
 *
1164
 * @return void
1165
 */
1166
function give_set_form_closed_status( $form_id ) {
1167
1168
	// Bailout.
1169
	if ( empty( $form_id ) ) {
1170
		return;
1171
	}
1172
1173
	$open_form       = false;
1174
	$is_goal_enabled = give_is_setting_enabled( give_get_meta( $form_id, '_give_goal_option', true, 'disabled' ) );
0 ignored issues
show
Documentation introduced by
'disabled' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1175
1176
	// Proceed, if the form goal is enabled.
1177
	if ( $is_goal_enabled ) {
1178
1179
		$close_form_when_goal_achieved = give_is_setting_enabled( give_get_meta( $form_id, '_give_close_form_when_goal_achieved', true, 'disabled' ) );
0 ignored issues
show
Documentation introduced by
'disabled' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1180
1181
		// Proceed, if close form when goal achieved option is enabled.
1182
		if ( $close_form_when_goal_achieved ) {
1183
1184
			$form                = new Give_Donate_Form( $form_id );
1185
			$goal_progress_stats = give_goal_progress_stats( $form );
1186
1187
			// Verify whether the form is closed or not after processing data.
1188
			$closed = $goal_progress_stats['raw_goal'] <= $goal_progress_stats['raw_actual'];
1189
1190
			// Update form meta if verified that the form is closed.
1191
			if ( $closed ) {
1192
				give_update_meta( $form_id, '_give_form_status', 'closed' );
1193
			} else {
1194
				$open_form = true;
1195
			}
1196
		} else {
1197
			$open_form = true;
1198
		}
1199
	} else {
1200
		$open_form = true;
1201
	}
1202
1203
	// If $open_form is true, then update form status to open.
1204
	if ( $open_form ) {
1205
		give_update_meta( $form_id, '_give_form_status', 'open' );
1206
	}
1207
}
1208
1209
/**
1210
 * Show Form Goal Stats in Admin ( Listing and Detail page )
1211
 *
1212
 * @param int $form_id Form ID.
1213
 *
1214
 * @since 2.1.0
1215
 *
1216
 * @return string
1217
 */
1218
function give_admin_form_goal_stats( $form_id ) {
1219
1220
	$html             = '';
1221
	$goal_stats       = give_goal_progress_stats( $form_id );
1222
	$percent_complete = round( ( $goal_stats['raw_actual'] / $goal_stats['raw_goal'] ), 3 ) * 100;
1223
1224
	$html .= sprintf(
1225
		'<div class="give-admin-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="%1$s">
1226
<span style="width:%1$s%%;"></span>
1227
</div>',
1228
		esc_attr( $goal_stats['progress'] )
1229
	);
1230
1231
	$html .= sprintf(
1232
		( 'percentage' !== $goal_stats['format'] ) ?
1233
			'<div class="give-goal-text"><span>%1$s</span> %2$s <a href="%3$s">%4$s</a> %5$s ' :
1234
			'<div class="give-goal-text"><a href="%3$s">%1$s </a>',
1235
		( 'percentage' !== $goal_stats['format'] ) ? $goal_stats['actual'] : $percent_complete . '%',
1236
		( 'percentage' !== $goal_stats['format'] ) ? __( 'of', 'give' ) : '',
1237
		esc_url( admin_url( "post.php?post={$form_id}&action=edit&give_tab=donation_goal_options" ) ),
1238
		$goal_stats['goal'],
1239
		( 'donors' === $goal_stats['format'] ? __( 'Donors', 'give' ) : ( 'donation' === $goal_stats['format'] ? __( 'Donations', 'give' ) : '' ) )
1240
	);
1241
1242
	if ( $goal_stats['raw_actual'] >= $goal_stats['raw_goal'] ) {
1243
		$html .= sprintf( '<span class="give-admin-goal-achieved"><span class="dashicons dashicons-star-filled"></span> %s</span>', __( 'Goal achieved', 'give' ) );
1244
	}
1245
1246
	$html .= '</div>';
1247
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1248
1249
	return $html;
1250
}
1251
1252
/**
1253
 * Get the default donation form's level id.
1254
 *
1255
 * @since 2.2.0
1256
 *
1257
 * @param integer $form_id Donation Form ID.
1258
 *
1259
 * @return null | array
1260
 */
1261
function give_form_get_default_level( $form_id ) {
1262
	$default_level = null;
1263
1264
	// If donation form has variable prices.
1265
	if ( give_has_variable_prices( $form_id ) ) {
1266
		/**
1267
		 * Filter the variable pricing
1268
		 *
1269
		 *
1270
		 * @since      1.0
1271
		 * @deprecated 2.2 Use give_get_donation_levels filter instead of give_form_variable_prices.
1272
		 *                 Check Give_Donate_Form::get_prices().
1273
		 *
1274
		 * @param array $prices Array of variable prices.
1275
		 * @param int   $form   Form ID.
1276
		 */
1277
		$prices = apply_filters( 'give_form_variable_prices', give_get_variable_prices( $form_id ), $form_id );
1278
1279
		// Go through each of the level and get the default level id.
1280
		foreach ( $prices as $level ) {
1281
			if (
0 ignored issues
show
introduced by
Found "=== '". Use Yoda Condition checks, you must
Loading history...
1282
				isset( $level['_give_default'] )
1283
				&& $level['_give_default'] === 'default'
1284
			) {
1285
				$default_level = $level;
1286
			}
1287
		}
1288
	}
1289
1290
	/**
1291
	 * Filter the default donation level id.
1292
	 *
1293
	 * @since 2.2.0
1294
	 *
1295
	 * @param array   $default_level Default level price data.
1296
	 * @param integer $form_id       Donation form ID.
1297
	 */
1298
	return apply_filters( 'give_form_get_default_level', $default_level, $form_id );
1299
}
1300
1301
/**
1302
 * Get the default level id.
1303
 *
1304
 * @since 2.2.0
1305
 *
1306
 * @param array|integer   $price_or_level_id Price level data.
1307
 * @param boolean|integer $form_id           Donation Form ID.
1308
 *
1309
 * @return boolean
1310
 */
1311
function give_is_default_level_id( $price_or_level_id, $form_id = 0 ) {
1312
	$is_default = false;
1313
1314
	if (
1315
		! empty( $form_id )
1316
		&& is_numeric( $price_or_level_id )
1317
	) {
1318
		// Get default level id.
1319
		$form_price_data = give_form_get_default_level( $form_id );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $form_price_data is correct as give_form_get_default_level($form_id) (which targets give_form_get_default_level()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1320
1321
		$is_default = ! is_null( $form_price_data ) && ( $price_or_level_id === absint( $form_price_data['_give_id']['level_id'] ) );
1322
	}
1323
1324
	$is_default = false === $is_default && is_array( $price_or_level_id ) ?
1325
		( isset( $price_or_level_id['_give_default'] ) && $price_or_level_id['_give_default'] === 'default' )
1326
		: $is_default;
1327
1328
	/**
1329
	 * Allow developers to modify the default level id checks.
1330
	 *
1331
	 * @since 2.2.0
1332
	 *
1333
	 * @param bool          $is_default        True if it is default price level id otherwise false.
1334
	 * @param array|integer $price_or_level_id Price Data.
1335
	 */
1336
	return apply_filters( 'give_is_default_level_id', $is_default, $price_or_level_id );
1337
}
1338
1339
1340
/**
1341
 * Get Name Title Prefixes (a.k.a. Salutation) value.
1342
 *
1343
 * @param int $form_id Donation Form ID.
1344
 *
1345
 * @since 2.2.0
1346
 *
1347
 * @return mixed
1348
 */
1349
function give_get_name_title_prefixes( $form_id = 0 ) {
1350
1351
	$name_title_prefix = give_is_name_title_prefix_enabled( $form_id );
1352
	$title_prefixes    = give_get_option( 'title_prefixes', give_get_default_title_prefixes() );
0 ignored issues
show
Documentation introduced by
give_get_default_title_prefixes() is of type array, but the function expects a string|boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1353
1354
	// If form id exists, then fetch form specific title prefixes.
1355
	if ( intval( $form_id ) > 0 && $name_title_prefix ) {
1356
1357
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1358
		if ( 'global' !== $form_title_prefix ) {
1359
			$form_title_prefixes = give_get_meta( $form_id, '_give_title_prefixes', true, give_get_default_title_prefixes() );
0 ignored issues
show
Documentation introduced by
give_get_default_title_prefixes() is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1360
1361
			// Check whether the form based title prefixes exists or not.
1362
			if ( is_array( $form_title_prefixes ) && count( $form_title_prefixes ) > 0 ) {
1363
				$title_prefixes = $form_title_prefixes;
1364
			}
1365
		}
1366
	}
1367
1368
	return $title_prefixes;
1369
}
1370
1371
/**
1372
 * Check whether the name title prefix is enabled or not.
1373
 *
1374
 * @param int    $form_id Donation Form ID.
1375
 * @param string $status  Status to set status based on option value.
1376
 *
1377
 * @since 2.2.0
1378
 *
1379
 * @return bool
1380
 */
1381
function give_is_name_title_prefix_enabled( $form_id = 0, $status = '' ) {
1382
	if ( empty( $status ) ) {
1383
		$status = array( 'required', 'optional' );
1384
	} else {
1385
		$status = array( $status );
1386
	}
1387
1388
	$title_prefix_status = give_is_setting_enabled( give_get_option( 'name_title_prefix' ), $status );
0 ignored issues
show
Documentation introduced by
$status is of type array<integer,string,{"0":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1389
1390
	if ( intval( $form_id ) > 0 ) {
1391
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1392
1393
		if ( 'disabled' === $form_title_prefix ) {
1394
			$title_prefix_status = false;
1395
		} elseif ( in_array( $form_title_prefix, $status, true ) ) {
1396
			$title_prefix_status = give_is_setting_enabled( $form_title_prefix, $status );
0 ignored issues
show
Documentation introduced by
$status is of type array<integer,string,{"0":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1397
		}
1398
	}
1399
1400
	return $title_prefix_status;
1401
1402
}
1403
1404
/**
1405
 * Get Donor Name with Title Prefix
1406
 *
1407
 * @param int|Give_Donor $donor Donor Information.
1408
 *
1409
 * @since 2.2.0
1410
 *
1411
 * @return object
1412
 */
1413
function give_get_name_with_title_prefixes( $donor ) {
1414
1415
	// Prepare Give_Donor object, if $donor is numeric.
1416
	if ( is_numeric( $donor ) ) {
1417
		$donor = new Give_Donor( $donor );
1418
	}
1419
1420
	$title_prefix = Give()->donor_meta->get_meta( $donor->id, '_give_donor_title_prefix', true );
1421
1422
	// Update Donor name, if non empty title prefix.
1423
	if ( ! empty( $title_prefix ) ) {
1424
		$donor->name = give_get_donor_name_with_title_prefixes( $title_prefix, $donor->name );
1425
	}
1426
1427
	return $donor;
1428
}
1429
1430
/**
1431
 * This function will generate donor name with title prefix if it is required.
1432
 *
1433
 * @param string $title_prefix Title Prefix of Donor
1434
 * @param string $name         Donor Name.
1435
 *
1436
 * @since 2.2.0
1437
 *
1438
 * @return string
1439
 */
1440
function give_get_donor_name_with_title_prefixes( $title_prefix, $name ) {
1441
1442
	$donor_name = $name;
1443
1444
	if ( ! empty( $title_prefix ) && ! empty( $name ) ) {
1445
		$donor_name = "{$title_prefix} {$name}";
1446
	}
1447
1448
	return trim( $donor_name );
1449
}
1450
1451
/**
1452
 * This function will fetch the default list of title prefixes.
1453
 *
1454
 * @since 2.2.0
1455
 *
1456
 * @return array
1457
 */
1458
function give_get_default_title_prefixes() {
1459
	/**
1460
	 * Filter the data
1461
	 * Set default title prefixes.
1462
	 *
1463
	 * @since 2.2.0
1464
	 */
1465
	return apply_filters(
1466
		'give_get_default_title_prefixes',
1467
		array(
1468
			'Mr.'  => __( 'Mr.', 'give' ),
1469
			'Mrs.' => __( 'Mrs.', 'give' ),
1470
			'Ms.'  => __( 'Ms.', 'give' ),
1471
		)
1472
	);
1473
}
1474
1475
/**
1476
 * This function will check whether the name title prefix field is required or not.
1477
 *
1478
 * @param int $form_id Donation Form ID.
1479
 *
1480
 * @since 2.2.0
1481
 *
1482
 * @return bool
1483
 */
1484
function give_is_name_title_prefix_required( $form_id = 0 ) {
1485
1486
	// Bail out, if name title prefix is not enabled.
1487
	if ( ! give_is_name_title_prefix_enabled( $form_id ) ) {
1488
		return false;
1489
	}
1490
1491
	$status      = array( 'optional' );
1492
	$is_optional = give_is_setting_enabled( give_get_option( 'name_title_prefix' ), $status );
0 ignored issues
show
Documentation introduced by
$status is of type array<integer,string,{"0":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1493
1494
	if ( intval( $form_id ) > 0 ) {
1495
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1496
1497
		if ( 'required' === $form_title_prefix ) {
1498
			$is_optional = false;
1499
		} elseif ( 'optional' === $form_title_prefix ) {
1500
			$is_optional = true;
1501
		}
1502
	}
1503
1504
	return ( ! $is_optional );
1505
}
1506
1507
/**
1508
 * Deletes form meta when the form is permanently deleted from the trash.
1509
 *
1510
 * @since 2.3.0
1511
 *
1512
 * @param integer $id Donation Form ID which needs to be deleted.
1513
 *
1514
 * @return void
1515
 */
1516
function give_handle_form_meta_on_delete( $id ) {
1517
1518
	global $wpdb;
1519
1520
	$form     = get_post( $id );
1521
	$get_data = give_clean( $_GET );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
1522
1523
	if (
1524
		'give_forms' === $form->post_type &&
1525
		'trash' === $form->post_status &&
1526
		(
1527
			( isset( $get_data['action'] ) && 'delete' === $get_data['action'] ) ||
1528
			! empty( $get_data['delete_all'] )
1529
		)
1530
	) {
1531
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->formmeta} WHERE form_id = '%d'", $form->ID ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
1532
	}
1533
}
1534
1535
add_action( 'before_delete_post', 'give_handle_form_meta_on_delete', 10, 1 );
1536