Test Failed
Push — master ( 315839...9b266f )
by Devin
05:39
created

functions.php ➔ give_send_back_to_checkout()   C

Complexity

Conditions 11
Paths 192

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 192
nop 1
dl 0
loc 69
rs 5.9163
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
 * Give Form Functions
4
 *
5
 * @package     GiveWP
6
 * @subpackage  Includes/Forms
7
 * @copyright   Copyright (c) 2016, GiveWP
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' ) {
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 ) {
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
function give_get_success_page_uri() {
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 View Code Duplication
function give_is_success_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...
121
	$give_options = give_get_settings();
122
123
	$success_page = isset( $give_options['success_page'] ) ? is_page( $give_options['success_page'] ) : false;
124
125
	return apply_filters( 'give_is_success_page', $success_page );
126
}
127
128
/**
129
 * Send To Success Page
130
 *
131
 * Sends the user to the success page.
132
 *
133
 * @param string $query_string
134
 *
135
 * @access      public
136
 * @since       1.0
137
 * @return      void
138
 */
139
function give_send_to_success_page( $query_string = null ) {
140
141
	$redirect = give_get_success_page_uri();
142
143
	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...
144
		$redirect .= $query_string;
145
	}
146
147
	$gateway = isset( $_REQUEST['give-gateway'] ) ? $_REQUEST['give-gateway'] : '';
148
149
	wp_redirect( apply_filters( 'give_success_page_redirect', $redirect, $gateway, $query_string ) );
150
	give_die();
151
}
152
153
154
/**
155
 * Send back to donation form.
156
 *
157
 * Used to redirect a user back to the donation form if there are errors present.
158
 *
159
 * @param array|string $args
160
 *
161
 * @access public
162
 * @since  1.0
163
 * @return Void
164
 */
165
function give_send_back_to_checkout( $args = array() ) {
166
167
	$url     = isset( $_POST['give-current-url'] ) ? sanitize_text_field( $_POST['give-current-url'] ) : '';
168
	$form_id = 0;
169
170
	// Set the form_id.
171
	if ( isset( $_POST['give-form-id'] ) ) {
172
		$form_id = sanitize_text_field( $_POST['give-form-id'] );
173
	}
174
175
	// Need a URL to continue. If none, redirect back to single form.
176
	if ( empty( $url ) ) {
177
		wp_safe_redirect( get_permalink( $form_id ) );
178
		give_die();
179
	}
180
181
	$defaults = array(
182
		'form-id' => (int) $form_id,
183
	);
184
185
	// Set the $level_id.
186
	if ( isset( $_POST['give-price-id'] ) ) {
187
		$defaults['level-id'] = sanitize_text_field( $_POST['give-price-id'] );
188
	}
189
190
	// Check for backward compatibility.
191
	if ( is_string( $args ) ) {
192
		$args = str_replace( '?', '', $args );
193
	}
194
195
	$args = wp_parse_args( $args, $defaults );
196
197
	// Merge URL query with $args to maintain third-party URL parameters after redirect.
198
	$url_data = wp_parse_url( $url );
199
200
	// Check if an array to prevent notices before parsing.
201
	if ( isset( $url_data['query'] ) && ! empty( $url_data['query'] ) ) {
202
		parse_str( $url_data['query'], $query );
203
204
		// Precaution: don't allow any CC info.
205
		unset( $query['card_number'] );
206
		unset( $query['card_cvc'] );
207
208
	} else {
209
		// No $url_data so pass empty array.
210
		$query = array();
211
	}
212
213
	$new_query        = array_merge( $args, $query );
214
	$new_query_string = http_build_query( $new_query );
215
216
	$path = $url_data['path'];
217
218
	if( is_multisite() && ! is_subdomain_install() ) {
219
		/* @var  WP_Site $site_info */
220
		$site_info = get_site();
221
		$path = 0 === strpos( $path, $site_info->path )
222
			? str_replace( untrailingslashit( $site_info->path ), '', $path )
223
			: $path ;
224
	}
225
226
	// Assemble URL parts.
227
	$redirect = home_url( '/' . $path . '?' . $new_query_string . '#give-form-' . $form_id . '-wrap' );
228
229
	// Redirect them.
230
	wp_safe_redirect( apply_filters( 'give_send_back_to_checkout', $redirect, $args ) );
231
	give_die();
232
233
}
234
235
/**
236
 * Get Success Page URL
237
 *
238
 * Gets the success page URL.
239
 *
240
 * @param string $query_string
241
 *
242
 * @access      public
243
 * @since       1.0
244
 * @return      string
245
 */
246
function give_get_success_page_url( $query_string = null ) {
247
248
	$success_page = give_get_option( 'success_page', 0 );
249
	$success_page = get_permalink( $success_page );
250
251
	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...
252
		$success_page .= $query_string;
253
	}
254
255
	return apply_filters( 'give_success_page_url', $success_page );
256
257
}
258
259
/**
260
 * Get the URL of the Failed Donation Page.
261
 *
262
 * @since 1.0
263
 *
264
 * @param bool $extras Extras to append to the URL.
265
 *
266
 * @return mixed Full URL to the Failed Donation Page, if present, home page if it doesn't exist.
267
 */
268
function give_get_failed_transaction_uri( $extras = false ) {
269
	$give_options = give_get_settings();
270
271
	// Remove question mark.
272
	if ( 0 === strpos( $extras, '?' ) ) {
273
		$extras = substr( $extras, 1 );
274
	}
275
276
	$extras_args = wp_parse_args( $extras );
277
278
	// Set nonce if payment id exist in extra params.
279
	if ( array_key_exists( 'payment-id', $extras_args ) ) {
280
		$extras_args['_wpnonce'] = wp_create_nonce( "give-failed-donation-{$extras_args['payment-id']}" );
281
		$extras                  = http_build_query( $extras_args );
282
	}
283
284
	$uri = ! empty( $give_options['failure_page'] ) ?
285
		trailingslashit( get_permalink( $give_options['failure_page'] ) ) :
286
		home_url();
287
288
289
	if ( $extras ) {
290
		$uri .= "?{$extras}";
291
	}
292
293
	return apply_filters( 'give_get_failed_transaction_uri', $uri );
294
}
295
296
/**
297
 * Determines if we're currently on the Failed Donation Page.
298
 *
299
 * @since 1.0
300
 * @return bool True if on the Failed Donation Page, false otherwise.
301
 */
302
function give_is_failed_transaction_page() {
303
	$give_options = give_get_settings();
304
	$ret          = isset( $give_options['failure_page'] ) ? is_page( $give_options['failure_page'] ) : false;
305
306
	return apply_filters( 'give_is_failure_page', $ret );
307
}
308
309
/**
310
 * Mark payments as Failed when returning to the Failed Donation Page
311
 *
312
 * @since  1.0
313
 * @since  1.8.16 Add security check
314
 *
315
 * @return bool
316
 */
317
function give_listen_for_failed_payments() {
318
319
	$failed_page = give_get_option( 'failure_page', 0 );
320
	$payment_id  = ! empty( $_GET['payment-id'] ) ? absint( $_GET['payment-id'] ) : 0;
321
	$nonce       = ! empty( $_GET['_wpnonce'] ) ? give_clean( $_GET['_wpnonce'] ) : false;
322
323
	// Bailout.
324
	if ( ! $failed_page || ! is_page( $failed_page ) || ! $payment_id || ! $nonce ) {
325
		return false;
326
	}
327
328
	// Security check.
329
	if ( ! wp_verify_nonce( $nonce, "give-failed-donation-{$payment_id}" ) ) {
330
		wp_die( __( 'We\'re unable to recognize your session. Please refresh the screen to try again; otherwise contact your website administrator for assistance.', 'give' ), __( 'Error', 'give' ) );
331
	}
332
333
	// Set payment status to failure
334
	give_update_payment_status( $payment_id, 'failed' );
335
}
336
337
add_action( 'template_redirect', 'give_listen_for_failed_payments' );
338
339
/**
340
 * Retrieve the Donation History page URI
341
 *
342
 * @access      public
343
 * @since       1.7
344
 *
345
 * @return      string
346
 */
347
function give_get_history_page_uri() {
348
	$give_options = give_get_settings();
349
350
	$history_page = isset( $give_options['history_page'] ) ? get_permalink( absint( $give_options['history_page'] ) ) : get_bloginfo( 'url' );
351
352
	return apply_filters( 'give_get_history_page_uri', $history_page );
353
}
354
355
/**
356
 * Determines if we're currently on the History page.
357
 *
358
 * @since 1.0
359
 *
360
 * @return bool True if on the History page, false otherwise.
361
 */
362 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...
363
	$give_options = give_get_settings();
364
365
	$history_page = isset( $give_options['history_page'] ) ? absint( $give_options['history_page'] ) : 0;
366
367
	return apply_filters( 'give_is_history_page', is_page( $history_page ) );
368
}
369
370
/**
371
 * Check if a field is required
372
 *
373
 * @param string $field
374
 * @param int    $form_id
375
 *
376
 * @access      public
377
 * @since       1.0
378
 * @return      bool
379
 */
380
function give_field_is_required( $field, $form_id ) {
381
382
	$required_fields = give_get_required_fields( $form_id );
383
384
	return array_key_exists( $field, $required_fields );
385
}
386
387
/**
388
 * Record Donation In Log
389
 *
390
 * Stores log information for a donation.
391
 *
392
 * @since 1.0
393
 *
394
 * @param int         $give_form_id  Give Form ID.
395
 * @param int         $payment_id    Payment ID.
396
 * @param bool|int    $price_id      Price ID, if any.
397
 * @param string|null $donation_date The date of the donation.
398
 *
399
 * @return void
400
 */
401
function give_record_donation_in_log( $give_form_id = 0, $payment_id, $price_id = false, $donation_date = null ) {
402
	$log_data = array(
403
		'log_parent'   => $payment_id,
404
		'log_type'     => 'sale',
405
		'log_date'     => isset( $donation_date ) ? $donation_date : null,
406
		'log_date_gmt' => isset( $donation_date ) ? $donation_date : null,
407
	);
408
409
	$log_meta = array(
410
		'form_id'  => $give_form_id,
411
		'price_id' => (int) $price_id,
412
	);
413
414
	Give()->logs->insert_log( $log_data, $log_meta );
415
}
416
417
418
/**
419
 * Increases the donation total count of a donation form.
420
 *
421
 * @since 1.0
422
 *
423
 * @param int $form_id  Give Form ID
424
 * @param int $quantity Quantity to increase donation count by
425
 *
426
 * @return bool|int
427
 */
428
function give_increase_donation_count( $form_id = 0, $quantity = 1 ) {
429
	$quantity = (int) $quantity;
430
431
	/** @var \Give_Donate_Form $form */
432
	$form = new Give_Donate_Form( $form_id );
433
434
	return $form->increase_sales( $quantity );
435
}
436
437
/**
438
 * Update the goal progress count of a donation form.
439
 *
440
 * @since 2.4.0
441
 *
442
 * @param int $form_id Give Form ID
443
 *
444
 * @return void
445
 */
446
function give_update_goal_progress( $form_id = 0 ) {
447
448
	//Get goal option meta key
449
	$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...
450
451
	// Check, if the form goal is enabled.
452
	if ( $is_goal_enabled ) {
453
		$goal_stats               = give_goal_progress_stats( $form_id );
454
		$form_goal_progress_value = ! empty( $goal_stats['progress'] ) ? $goal_stats['progress'] : 0;
455
	} else {
456
		$form_goal_progress_value = -1;
457
	}
458
459
	give_update_meta( $form_id, '_give_form_goal_progress', $form_goal_progress_value );
460
}
461
462
/**
463
 * Decreases the sale count of a form. Primarily for when a donation is refunded.
464
 *
465
 * @since 1.0
466
 *
467
 * @param int $form_id  Give Form ID
468
 * @param int $quantity Quantity to increase donation count by
469
 *
470
 * @return bool|int
471
 */
472
function give_decrease_donation_count( $form_id = 0, $quantity = 1 ) {
473
	$quantity = (int) $quantity;
474
475
	/** @var \Give_Donate_Form $form */
476
	$form = new Give_Donate_Form( $form_id );
477
478
	return $form->decrease_sales( $quantity );
479
}
480
481
/**
482
 * Increases the total earnings of a form.
483
 *
484
 * @since 1.0
485
 *
486
 * @since 2.1 Pass donation id.
487
 *
488
 * @param int $give_form_id Give Form ID
489
 * @param int $amount       Earnings
490
 * @param int $payment_id   Donation ID.
491
 *
492
 * @return bool|int
493
 */
494
function give_increase_earnings( $give_form_id = 0, $amount, $payment_id = 0 ) {
495
	/** @var \Give_Donate_Form $form */
496
	$form = new Give_Donate_Form( $give_form_id );
497
498
	return $form->increase_earnings( $amount, $payment_id );
499
}
500
501
/**
502
 * Decreases the total earnings of a form.
503
 *
504
 * Primarily for when a donation is refunded.
505
 *
506
 * @since 1.0
507
 *
508
 * @since 2.1 Pass donation id.
509
 *
510
 * @param int $form_id    Give Form ID
511
 * @param int $amount     Earnings
512
 * @param int $payment_id Donation ID.
513
 *
514
 * @return bool|int
515
 */
516
function give_decrease_form_earnings( $form_id = 0, $amount, $payment_id = 0 ) {
517
	/** @var \Give_Donate_Form $form */
518
	$form = new Give_Donate_Form( $form_id );
519
520
	return $form->decrease_earnings( $amount, $payment_id );
521
}
522
523
524
/**
525
 * Returns the total earnings for a form.
526
 *
527
 * @since 1.0
528
 *
529
 * @param int $form_id Give Form ID
530
 *
531
 * @return int $earnings Earnings for a certain form
532
 */
533
function give_get_form_earnings_stats( $form_id = 0 ) {
534
	$give_form = new Give_Donate_Form( $form_id );
535
536
	/**
537
	 * Filter the form earnings
538
	 *
539
	 * @since 1.8.17
540
	 */
541
	return apply_filters( 'give_get_form_earnings_stats', $give_form->earnings, $form_id, $give_form );
542
}
543
544
545
/**
546
 * Return the sales number for a form.
547
 *
548
 * @since 1.0
549
 *
550
 * @param int $give_form_id Give Form ID
551
 *
552
 * @return int $sales Amount of sales for a certain form
553
 */
554
function give_get_form_sales_stats( $give_form_id = 0 ) {
555
	$give_form = new Give_Donate_Form( $give_form_id );
556
557
	return $give_form->sales;
558
}
559
560
561
/**
562
 * Retrieves the average monthly sales for a specific donation form
563
 *
564
 * @since 1.0
565
 *
566
 * @param int $form_id Form ID
567
 *
568
 * @return float $sales Average monthly sales
569
 */
570 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...
571
	$sales        = give_get_form_sales_stats( $form_id );
572
	$release_date = get_post_field( 'post_date', $form_id );
573
574
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
575
576
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
577
578
	if ( $months > 0 ) {
579
		$sales = ( $sales / $months );
580
	}
581
582
	return $sales;
583
}
584
585
586
/**
587
 * Retrieves the average monthly earnings for a specific form
588
 *
589
 * @since 1.0
590
 *
591
 * @param int $form_id Form ID
592
 *
593
 * @return float $earnings Average monthly earnings
594
 */
595 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...
596
	$earnings     = give_get_form_earnings_stats( $form_id );
597
	$release_date = get_post_field( 'post_date', $form_id );
598
599
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
600
601
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
602
603
	if ( $months > 0 ) {
604
		$earnings = ( $earnings / $months );
605
	}
606
607
	return $earnings < 0 ? 0 : $earnings;
608
}
609
610
611
/**
612
 * Get Price Option Name (Text)
613
 *
614
 * Retrieves the name of a variable price option.
615
 *
616
 * @since       1.0
617
 *
618
 * @param int  $form_id      ID of the donation form.
619
 * @param int  $price_id     ID of the price option.
620
 * @param int  $payment_id   payment ID for use in filters ( optional ).
621
 * @param bool $use_fallback Outputs the level amount if no level text is provided.
622
 *
623
 * @return string $price_name Name of the price option
624
 */
625
function give_get_price_option_name( $form_id = 0, $price_id = 0, $payment_id = 0, $use_fallback = true ) {
626
627
	$prices     = give_get_variable_prices( $form_id );
628
	$price_name = '';
629
630
	if ( false === $prices ) {
631
		return $price_name;
632
	}
633
634
	foreach ( $prices as $price ) {
635
636
		if ( intval( $price['_give_id']['level_id'] ) === intval( $price_id ) ) {
637
638
			$price_text     = isset( $price['_give_text'] ) ? $price['_give_text'] : '';
639
			$price_fallback = $use_fallback ?
640
				give_currency_filter(
641
					give_format_amount(
642
						$price['_give_amount'],
643
						array( 'sanitize' => false )
644
					),
645
					array( 'decode_currency' => true )
646
				) : '';
647
			$price_name     = ! empty( $price_text ) ? $price_text : $price_fallback;
648
649
		}
650
	}
651
652
	return apply_filters( 'give_get_price_option_name', $price_name, $form_id, $payment_id, $price_id );
653
}
654
655
656
/**
657
 * Retrieves a price from from low to high of a variable priced form
658
 *
659
 * @since 1.0
660
 *
661
 * @param int  $form_id   ID of the form
662
 * @param bool $formatted Flag to decide which type of price range string return
663
 *
664
 * @return string $range A fully formatted price range
665
 */
666
function give_price_range( $form_id = 0, $formatted = true ) {
667
	$low        = give_get_lowest_price_option( $form_id );
668
	$high       = give_get_highest_price_option( $form_id );
669
	$order_type = ! empty( $_REQUEST['order'] ) ? $_REQUEST['order'] : 'asc';
670
671
	$range = sprintf(
672
		'<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>',
673
		'asc' === $order_type ? 'low' : 'high',
674
		'asc' === $order_type ? give_currency_filter( give_format_amount( $low, array( 'sanitize' => false ) ) ) : give_currency_filter( give_format_amount( $high, array( 'sanitize' => false ) ) ),
675
		'asc' === $order_type ? 'high' : 'low',
676
		'asc' === $order_type ? give_currency_filter( give_format_amount( $high, array( 'sanitize' => false ) ) ) : give_currency_filter( give_format_amount( $low, array( 'sanitize' => false ) ) )
677
678
	);
679
680
	if ( ! $formatted ) {
681
		$range = wp_strip_all_tags( $range );
682
	}
683
684
	return apply_filters( 'give_price_range', $range, $form_id, $low, $high );
685
}
686
687
688
/**
689
 * Get Lowest Price ID
690
 *
691
 * Retrieves the ID for the cheapest price option of a variable donation form
692
 *
693
 * @since 1.5
694
 *
695
 * @param int $form_id ID of the donation
696
 *
697
 * @return int ID of the lowest price
698
 */
699
function give_get_lowest_price_id( $form_id = 0 ) {
700
701
	if ( empty( $form_id ) ) {
702
		$form_id = get_the_ID();
703
	}
704
705
	if ( ! give_has_variable_prices( $form_id ) ) {
706
		return give_get_form_price( $form_id );
707
	}
708
709
	$prices = give_get_variable_prices( $form_id );
710
711
	$min = $min_id = 0;
712
713
	if ( ! empty( $prices ) ) {
714
715
		foreach ( $prices as $key => $price ) {
716
717
			if ( empty( $price['_give_amount'] ) ) {
718
				continue;
719
			}
720
721
			if ( ! isset( $min ) ) {
722
				$min = $price['_give_amount'];
723
			} else {
724
				$min = min( $min, $price['_give_amount'] );
725
			}
726
727
			if ( $price['_give_amount'] == $min ) {
728
				$min_id = $price['_give_id']['level_id'];
729
			}
730
		}
731
	}
732
733
	return (int) $min_id;
734
}
735
736
/**
737
 * Retrieves cheapest price option of a variable priced form
738
 *
739
 * @since 1.0
740
 *
741
 * @param int $form_id ID of the form
742
 *
743
 * @return float Amount of the lowest price
744
 */
745 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...
746
	if ( empty( $form_id ) ) {
747
		$form_id = get_the_ID();
748
	}
749
750
	if ( ! give_has_variable_prices( $form_id ) ) {
751
		return give_get_form_price( $form_id );
752
	}
753
754
	if ( ! ( $low = get_post_meta( $form_id, '_give_levels_minimum_amount', true ) ) ) {
755
		// Backward compatibility.
756
		$prices = wp_list_pluck( give_get_variable_prices( $form_id ), '_give_amount' );
757
		$low    = ! empty( $prices ) ? min( $prices ) : 0;
758
	}
759
760
	return give_maybe_sanitize_amount( $low );
761
}
762
763
/**
764
 * Retrieves most expensive price option of a variable priced form
765
 *
766
 * @since 1.0
767
 *
768
 * @param int $form_id ID of the form
769
 *
770
 * @return float Amount of the highest price
771
 */
772 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...
773
774
	if ( empty( $form_id ) ) {
775
		$form_id = get_the_ID();
776
	}
777
778
	if ( ! give_has_variable_prices( $form_id ) ) {
779
		return give_get_form_price( $form_id );
780
	}
781
782
	if ( ! ( $high = get_post_meta( $form_id, '_give_levels_maximum_amount', true ) ) ) {
783
		// Backward compatibility.
784
		$prices = wp_list_pluck( give_get_variable_prices( $form_id ), '_give_amount' );
785
		$high   = ! empty( $prices ) ? max( $prices ) : 0;
786
	}
787
788
	return give_maybe_sanitize_amount( $high );
789
}
790
791
/**
792
 * Returns the price of a form, but only for non-variable priced forms.
793
 *
794
 * @since 1.0
795
 *
796
 * @param int $form_id ID number of the form to retrieve a price for
797
 *
798
 * @return mixed string|int Price of the form
799
 */
800
function give_get_form_price( $form_id = 0 ) {
801
802
	if ( empty( $form_id ) ) {
803
		return false;
804
	}
805
806
	$form = new Give_Donate_Form( $form_id );
807
808
	return $form->__get( 'price' );
809
}
810
811
/**
812
 * Returns the minimum price amount of a form, only enforced for the custom amount input.
813
 *
814
 * @since 1.3.6
815
 *
816
 * @param int $form_id ID number of the form to retrieve the minimum price for
817
 *
818
 * @return mixed string|int Minimum price of the form
819
 */
820
function give_get_form_minimum_price( $form_id = 0 ) {
821
822
	if ( empty( $form_id ) ) {
823
		return false;
824
	}
825
826
	$form = new Give_Donate_Form( $form_id );
827
828
	return $form->get_minimum_price();
829
830
}
831
832
/**
833
 * Return the maximum price amount of form.
834
 *
835
 * @since 2.1
836
 *
837
 * @param int $form_id Donate Form ID
838
 *
839
 * @return bool|float
840
 */
841
function give_get_form_maximum_price( $form_id = 0 ) {
842
843
	if ( empty( $form_id ) ) {
844
		return false;
845
	}
846
847
	$form = new Give_Donate_Form( $form_id );
848
849
	return $form->get_maximum_price();
850
}
851
852
/**
853
 * Displays a formatted price for a donation form
854
 *
855
 * @since 1.0
856
 *
857
 * @param int      $form_id  ID of the form price to show
858
 * @param bool     $echo     Whether to echo or return the results
859
 * @param bool|int $price_id Optional price id for variable pricing
860
 *
861
 * @return int $formatted_price
862
 */
863
function give_price( $form_id = 0, $echo = true, $price_id = false ) {
864
	$price = 0;
865
866
	if ( empty( $form_id ) ) {
867
		$form_id = get_the_ID();
868
	}
869
870
	if ( give_has_variable_prices( $form_id ) ) {
871
872
		$prices = give_get_variable_prices( $form_id );
873
874
		if ( false !== $price_id ) {
875
876
			// loop through multi-prices to see which is default
877
			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...
878
				// this is the default price
879
				if ( isset( $price['_give_default'] ) && $price['_give_default'] === 'default' ) {
880
					$price = (float) $price['_give_amount'];
881
				};
882
			}
883
		} else {
884
885
			$price = give_get_lowest_price_option( $form_id );
886
		}
887
	} else {
888
889
		$price = give_get_form_price( $form_id );
890
	}
891
892
	$price           = apply_filters( 'give_form_price', give_maybe_sanitize_amount( $price ), $form_id );
893
	$formatted_price = '<span class="give_price" id="give_price_' . $form_id . '">' . $price . '</span>';
894
	$formatted_price = apply_filters( 'give_form_price_after_html', $formatted_price, $form_id, $price );
895
896
	if ( $echo ) {
897
		echo $formatted_price;
898
	} else {
899
		return $formatted_price;
900
	}
901
}
902
903
add_filter( 'give_form_price', 'give_format_amount', 10 );
904
add_filter( 'give_form_price', 'give_currency_filter', 20 );
905
906
907
/**
908
 * Retrieves the amount of a variable price option
909
 *
910
 * @since 1.0
911
 *
912
 * @param int $form_id  ID of the form
913
 * @param int $price_id ID of the price option
914
 *
915
 * @return float $amount Amount of the price option
916
 */
917
function give_get_price_option_amount( $form_id = 0, $price_id = 0 ) {
918
	$prices = give_get_variable_prices( $form_id );
919
920
	$amount = 0.00;
921
922 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...
923
		if ( isset( $price['_give_id']['level_id'] ) && $price['_give_id']['level_id'] == $price_id ) {
924
			$amount = isset( $price['_give_amount'] ) ? $price['_give_amount'] : 0.00;
925
			break;
926
		};
927
	}
928
929
	return apply_filters( 'give_get_price_option_amount', give_maybe_sanitize_amount( $amount ), $form_id, $price_id );
930
}
931
932
/**
933
 * Returns the goal of a form
934
 *
935
 * @since 1.0
936
 *
937
 * @param int $form_id ID number of the form to retrieve a goal for
938
 *
939
 * @return mixed string|int Goal of the form
940
 */
941
function give_get_form_goal( $form_id = 0 ) {
942
943
	if ( empty( $form_id ) ) {
944
		return false;
945
	}
946
947
	$form = new Give_Donate_Form( $form_id );
948
949
	return $form->goal;
950
951
}
952
953
/**
954
 * Returns the goal format of a form
955
 *
956
 * @since 2.0
957
 *
958
 * @param int $form_id ID number of the form to retrieve a goal for
959
 *
960
 * @return mixed string|int Goal of the form
961
 */
962
function give_get_form_goal_format( $form_id = 0 ) {
963
964
	if ( empty( $form_id ) ) {
965
		return false;
966
	}
967
968
	return give_get_meta( $form_id, '_give_goal_format', true );
969
970
}
971
972
/**
973
 * Display/Return a formatted goal for a donation form
974
 *
975
 * @since 1.0
976
 *
977
 * @param int  $form_id ID of the form price to show
978
 * @param bool $echo    Whether to echo or return the results
979
 *
980
 * @return string $formatted_goal
981
 */
982
function give_goal( $form_id = 0, $echo = true ) {
983
984
	if ( empty( $form_id ) ) {
985
		$form_id = get_the_ID();
986
	}
987
988
	$goal        = give_get_form_goal( $form_id );
989
	$goal_format = give_get_form_goal_format( $form_id );
990
991
	if ( 'donation' === $goal_format ) {
992
		$goal = "{$goal} donations";
993
	} else {
994
		$goal = apply_filters( 'give_form_goal', give_maybe_sanitize_amount( $goal ), $form_id );
995
	}
996
997
	$formatted_goal = sprintf(
998
		'<span class="give_price" id="give_price_%1$s">%2$s</span>',
999
		$form_id,
1000
		$goal
1001
	);
1002
	$formatted_goal = apply_filters( 'give_form_price_after_html', $formatted_goal, $form_id, $goal );
1003
1004
	if ( $echo ) {
1005
		echo $formatted_goal;
1006
	} else {
1007
		return $formatted_goal;
1008
	}
1009
}
1010
1011
add_filter( 'give_form_goal', 'give_format_amount', 10 );
1012
add_filter( 'give_form_goal', 'give_currency_filter', 20 );
1013
1014
1015
/**
1016
 * Checks if users can only donate when logged in
1017
 *
1018
 * @since  1.0
1019
 *
1020
 * @param  int $form_id Give form ID
1021
 *
1022
 * @return bool  $ret Whether or not the logged_in_only setting is set
1023
 */
1024 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...
1025
	// If _give_logged_in_only is set to enable then guest can donate from that specific form.
1026
	// Otherwise it is member only donation form.
1027
	$val = give_get_meta( $form_id, '_give_logged_in_only', true );
1028
	$val = ! empty( $val ) ? $val : 'enabled';
1029
1030
	$ret = ! give_is_setting_enabled( $val );
1031
1032
	return (bool) apply_filters( 'give_logged_in_only', $ret, $form_id );
1033
}
1034
1035
1036
/**
1037
 * Checks the option for the "Register / Login Option"
1038
 *
1039
 * @since 1.4.1
1040
 *
1041
 * @param int $form_id
1042
 *
1043
 * @return string
1044
 */
1045
function give_show_login_register_option( $form_id ) {
1046
1047
	$show_register_form = give_get_meta( $form_id, '_give_show_register_form', true );
1048
1049
	return apply_filters( 'give_show_register_form', $show_register_form, $form_id );
1050
1051
}
1052
1053
1054
/**
1055
 * Get pre fill form field values.
1056
 *
1057
 * Note: this function will extract form field values from give_purchase session data.
1058
 *
1059
 * @since  1.8
1060
 *
1061
 * @param  int $form_id Form ID.
1062
 *
1063
 * @return array
1064
 */
1065
function _give_get_prefill_form_field_values( $form_id ) {
1066
	$logged_in_donor_info = array();
1067
1068
	if ( is_user_logged_in() ) :
1069
		$donor_data    = get_userdata( get_current_user_id() );
1070
		$donor         = new Give_Donor( get_current_user_id(), true );
1071
		$donor_address = $donor->get_donor_address();
1072
		$company_name  = $donor->get_company_name();
1073
1074
		$logged_in_donor_info = array(
1075
			// First name.
1076
			'give_first'      => $donor_data->first_name,
1077
1078
			// Last name.
1079
			'give_last'       => $donor_data->last_name,
1080
1081
			// Title Prefix.
1082
			'give_title'      => $donor->get_meta( '_give_donor_title_prefix', true ),
1083
1084
			// Company name.
1085
			'company_name'    => $company_name,
1086
1087
			// Email.
1088
			'give_email'      => $donor_data->user_email,
1089
1090
			// Street address 1.
1091
			'card_address'    => $donor_address['line1'],
1092
1093
			// Street address 2.
1094
			'card_address_2'  => $donor_address['line2'],
1095
1096
			// Country.
1097
			'billing_country' => $donor_address['country'],
1098
1099
			// State.
1100
			'card_state'      => $donor_address['state'],
1101
1102
			// City.
1103
			'card_city'       => $donor_address['city'],
1104
1105
			// Zipcode
1106
			'card_zip'        => $donor_address['zip'],
1107
		);
1108
	endif;
1109
1110
	// Bailout: Auto fill form field values only form form which donor is donating.
1111
	if (
1112
		empty( $_GET['form-id'] )
1113
		|| ! $form_id
1114
		|| ( $form_id !== absint( $_GET['form-id'] ) )
1115
	) {
1116
		return $logged_in_donor_info;
1117
	}
1118
1119
	// Get purchase data.
1120
	$give_purchase_data = Give()->session->get( 'give_purchase' );
1121
1122
	// Get donor info from form data.
1123
	$give_donor_info_in_session = empty( $give_purchase_data['post_data'] )
1124
		? array()
1125
		: $give_purchase_data['post_data'];
1126
1127
	// Output.
1128
	return wp_parse_args( $give_donor_info_in_session, $logged_in_donor_info );
1129
}
1130
1131
/**
1132
 * Get donor count of form
1133
 *
1134
 * @since 2.1.0
1135
 *
1136
 * @param int   $form_id
1137
 * @param array $args
1138
 *
1139
 * @return int
1140
 */
1141
function give_get_form_donor_count( $form_id, $args = array() ) {
1142
	global $wpdb;
1143
1144
	$cache_key   = Give_Cache::get_key( "form_donor_count_{$form_id}", $args, false );
1145
	$donor_count = absint( Give_Cache::get_db_query( $cache_key ) );
1146
1147
	if ( $form_id && ! $donor_count ) {
1148
		// Set arguments.
1149
		$args = wp_parse_args(
1150
			$args,
1151
			array(
1152
				'unique' => true,
1153
			)
1154
		);
1155
1156
		$donation_meta_table  = Give()->payment_meta->table_name;
1157
		$donation_id_col_name = Give()->payment_meta->get_meta_type() . '_id';
1158
1159
		$distinct = $args['unique'] ? 'DISTINCT meta_value' : 'meta_value';
1160
1161
		$query = $wpdb->prepare(
1162
			"
1163
			SELECT COUNT({$distinct})
1164
			FROM {$donation_meta_table}
1165
			WHERE meta_key=%s
1166
			AND {$donation_id_col_name} IN(
1167
				SELECT {$donation_id_col_name}
1168
				FROM {$donation_meta_table} as pm
1169
				INNER JOIN {$wpdb->posts} as p
1170
				ON pm.{$donation_id_col_name}=p.ID
1171
				WHERE pm.meta_key=%s
1172
				AND pm.meta_value=%s
1173
				AND p.post_status=%s
1174
			)
1175
			",
1176
			'_give_payment_donor_id',
1177
			'_give_payment_form_id',
1178
			$form_id,
1179
			'publish'
1180
		);
1181
1182
		$donor_count = absint( $wpdb->get_var( $query ) );
1183
	}
1184
1185
1186
	/**
1187
	 * Filter the donor count
1188
	 *
1189
	 * @since 2.1.0
1190
	 */
1191
	$donor_count = apply_filters( 'give_get_form_donor_count', $donor_count, $form_id, $args );
1192
1193
	return $donor_count;
1194
}
1195
1196
/**
1197
 * Verify the form status.
1198
 *
1199
 * @param int $form_id Donation Form ID.
1200
 *
1201
 * @since 2.1
1202
 *
1203
 * @return void
1204
 */
1205
function give_set_form_closed_status( $form_id ) {
1206
1207
	// Bailout.
1208
	if ( empty( $form_id ) ) {
1209
		return;
1210
	}
1211
1212
	$open_form       = false;
1213
	$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...
1214
1215
	// Proceed, if the form goal is enabled.
1216
	if ( $is_goal_enabled ) {
1217
1218
		$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...
1219
1220
		// Proceed, if close form when goal achieved option is enabled.
1221
		if ( $close_form_when_goal_achieved ) {
1222
1223
			$form                = new Give_Donate_Form( $form_id );
1224
			$goal_progress_stats = give_goal_progress_stats( $form );
1225
1226
			// Verify whether the form is closed or not after processing data.
1227
			$closed = $goal_progress_stats['raw_goal'] <= $goal_progress_stats['raw_actual'];
1228
1229
			// Update form meta if verified that the form is closed.
1230
			if ( $closed ) {
1231
				give_update_meta( $form_id, '_give_form_status', 'closed' );
1232
			} else {
1233
				$open_form = true;
1234
			}
1235
		} else {
1236
			$open_form = true;
1237
		}
1238
	} else {
1239
		$open_form = true;
1240
	}
1241
1242
	// If $open_form is true, then update form status to open.
1243
	if ( $open_form ) {
1244
		give_update_meta( $form_id, '_give_form_status', 'open' );
1245
	}
1246
}
1247
1248
/**
1249
 * Show Form Goal Stats in Admin ( Listing and Detail page )
1250
 *
1251
 * @param int $form_id Form ID.
1252
 *
1253
 * @since 2.1.0
1254
 *
1255
 * @return string
1256
 */
1257
function give_admin_form_goal_stats( $form_id ) {
1258
1259
	$html             = '';
1260
	$goal_stats       = give_goal_progress_stats( $form_id );
1261
	$percent_complete = round( ( $goal_stats['raw_actual'] / $goal_stats['raw_goal'] ), 3 ) * 100;
1262
1263
	$html .= sprintf(
1264
		'<div class="give-admin-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="%1$s">
1265
<span style="width:%1$s%%;"></span>
1266
</div>',
1267
		esc_attr( $goal_stats['progress'] )
1268
	);
1269
1270
	$html .= sprintf(
1271
		( 'percentage' !== $goal_stats['format'] ) ?
1272
			'<div class="give-goal-text"><span>%1$s</span> %2$s <a href="%3$s">%4$s</a> %5$s ' :
1273
			'<div class="give-goal-text"><a href="%3$s">%1$s </a>',
1274
		( 'percentage' !== $goal_stats['format'] ) ? $goal_stats['actual'] : $percent_complete . '%',
1275
		( 'percentage' !== $goal_stats['format'] ) ? __( 'of', 'give' ) : '',
1276
		esc_url( admin_url( "post.php?post={$form_id}&action=edit&give_tab=donation_goal_options" ) ),
1277
		$goal_stats['goal'],
1278
		( 'donors' === $goal_stats['format'] ? __( 'donors', 'give' ) : ( 'donation' === $goal_stats['format'] ? __( 'donations', 'give' ) : '' ) )
1279
	);
1280
1281
	if ( $goal_stats['raw_actual'] >= $goal_stats['raw_goal'] ) {
1282
		$html .= sprintf( '<span class="give-admin-goal-achieved"><span class="dashicons dashicons-star-filled"></span> %s</span>', __( 'Goal achieved', 'give' ) );
1283
	}
1284
1285
	$html .= '</div>';
1286
1287
1288
	return $html;
1289
}
1290
1291
/**
1292
 * Get the default donation form's level id.
1293
 *
1294
 * @since 2.2.0
1295
 *
1296
 * @param integer $form_id Donation Form ID.
1297
 *
1298
 * @return null | array
1299
 */
1300
function give_form_get_default_level( $form_id ) {
1301
	$default_level = null;
1302
1303
	// If donation form has variable prices.
1304
	if ( give_has_variable_prices( $form_id ) ) {
1305
		/**
1306
		 * Filter the variable pricing
1307
		 *
1308
		 *
1309
		 * @since      1.0
1310
		 * @deprecated 2.2 Use give_get_donation_levels filter instead of give_form_variable_prices.
1311
		 *                 Check Give_Donate_Form::get_prices().
1312
		 *
1313
		 * @param array $prices Array of variable prices.
1314
		 * @param int   $form   Form ID.
1315
		 */
1316
		$prices = apply_filters( 'give_form_variable_prices', give_get_variable_prices( $form_id ), $form_id );
1317
1318
		// Go through each of the level and get the default level id.
1319
		foreach ( $prices as $level ) {
1320
			if (
1321
				isset( $level['_give_default'] )
1322
				&& $level['_give_default'] === 'default'
1323
			) {
1324
				$default_level = $level;
1325
			}
1326
		}
1327
	}
1328
1329
	/**
1330
	 * Filter the default donation level id.
1331
	 *
1332
	 * @since 2.2.0
1333
	 *
1334
	 * @param array   $default_level Default level price data.
1335
	 * @param integer $form_id       Donation form ID.
1336
	 */
1337
	return apply_filters( 'give_form_get_default_level', $default_level, $form_id );
1338
}
1339
1340
/**
1341
 * Get the default level id.
1342
 *
1343
 * @since 2.2.0
1344
 *
1345
 * @param array|integer   $price_or_level_id Price level data.
1346
 * @param boolean|integer $form_id           Donation Form ID.
1347
 *
1348
 * @return boolean
1349
 */
1350
function give_is_default_level_id( $price_or_level_id, $form_id = 0 ) {
1351
	$is_default = false;
1352
1353
	if (
1354
		! empty( $form_id )
1355
		&& is_numeric( $price_or_level_id )
1356
	) {
1357
		// Get default level id.
1358
		$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...
1359
1360
		$is_default = ! is_null( $form_price_data ) && ( $price_or_level_id === absint( $form_price_data['_give_id']['level_id'] ) );
1361
	}
1362
1363
	$is_default = false === $is_default && is_array( $price_or_level_id ) ?
1364
		( isset( $price_or_level_id['_give_default'] ) && $price_or_level_id['_give_default'] === 'default' )
1365
		: $is_default;
1366
1367
	/**
1368
	 * Allow developers to modify the default level id checks.
1369
	 *
1370
	 * @since 2.2.0
1371
	 *
1372
	 * @param bool          $is_default        True if it is default price level id otherwise false.
1373
	 * @param array|integer $price_or_level_id Price Data.
1374
	 */
1375
	return apply_filters( 'give_is_default_level_id', $is_default, $price_or_level_id );
1376
}
1377
1378
1379
/**
1380
 * Get Name Title Prefixes (a.k.a. Salutation) value.
1381
 *
1382
 * @param int $form_id Donation Form ID.
1383
 *
1384
 * @since 2.2.0
1385
 *
1386
 * @return array
1387
 */
1388
function give_get_name_title_prefixes( $form_id = 0 ) {
1389
1390
	$name_title_prefix = give_is_name_title_prefix_enabled( $form_id );
1391
	$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...
1392
1393
	// If form id exists, then fetch form specific title prefixes.
1394
	if ( intval( $form_id ) > 0 && $name_title_prefix ) {
1395
1396
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1397
		if ( 'global' !== $form_title_prefix ) {
1398
			$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...
1399
1400
			// Check whether the form based title prefixes exists or not.
1401
			if ( is_array( $form_title_prefixes ) && count( $form_title_prefixes ) > 0 ) {
1402
				$title_prefixes = $form_title_prefixes;
1403
			}
1404
		}
1405
	}
1406
1407
	return array_filter( (array) $title_prefixes );
1408
}
1409
1410
/**
1411
 * Check whether the name title prefix is enabled or not.
1412
 *
1413
 * @param int    $form_id Donation Form ID.
1414
 * @param string $status  Status to set status based on option value.
1415
 *
1416
 * @since 2.2.0
1417
 *
1418
 * @return bool
1419
 */
1420
function give_is_name_title_prefix_enabled( $form_id = 0, $status = '' ) {
1421
	if ( empty( $status ) ) {
1422
		$status = array( 'required', 'optional' );
1423
	} else {
1424
		$status = array( $status );
1425
	}
1426
1427
	$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...
1428
1429
	if ( intval( $form_id ) > 0 ) {
1430
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1431
1432
		if ( 'disabled' === $form_title_prefix ) {
1433
			$title_prefix_status = false;
1434
		} elseif ( in_array( $form_title_prefix, $status, true ) ) {
1435
			$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...
1436
		}
1437
	}
1438
1439
	return $title_prefix_status;
1440
1441
}
1442
1443
/**
1444
 * Get Donor Name with Title Prefix
1445
 *
1446
 * @param int|Give_Donor $donor Donor Information.
1447
 *
1448
 * @since 2.2.0
1449
 *
1450
 * @return object
1451
 */
1452
function give_get_name_with_title_prefixes( $donor ) {
1453
1454
	// Prepare Give_Donor object, if $donor is numeric.
1455
	if ( is_numeric( $donor ) ) {
1456
		$donor = new Give_Donor( $donor );
1457
	}
1458
1459
	$title_prefix = Give()->donor_meta->get_meta( $donor->id, '_give_donor_title_prefix', true );
1460
1461
	// Update Donor name, if non empty title prefix.
1462
	if ( ! empty( $title_prefix ) ) {
1463
		$donor->name = give_get_donor_name_with_title_prefixes( $title_prefix, $donor->name );
1464
	}
1465
1466
	return $donor;
1467
}
1468
1469
/**
1470
 * This function will generate donor name with title prefix if it is required.
1471
 *
1472
 * @param string $title_prefix Title Prefix of Donor
1473
 * @param string $name         Donor Name.
1474
 *
1475
 * @since 2.2.0
1476
 *
1477
 * @return string
1478
 */
1479
function give_get_donor_name_with_title_prefixes( $title_prefix, $name ) {
1480
1481
	$donor_name = $name;
1482
1483
	if ( ! empty( $title_prefix ) && ! empty( $name ) ) {
1484
		$donor_name = "{$title_prefix} {$name}";
1485
	}
1486
1487
	return trim( $donor_name );
1488
}
1489
1490
/**
1491
 * This function will fetch the default list of title prefixes.
1492
 *
1493
 * @since 2.2.0
1494
 *
1495
 * @return array
1496
 */
1497
function give_get_default_title_prefixes() {
1498
	/**
1499
	 * Filter the data
1500
	 * Set default title prefixes.
1501
	 *
1502
	 * @since 2.2.0
1503
	 */
1504
	return apply_filters(
1505
		'give_get_default_title_prefixes',
1506
		array(
1507
			'Mr.'  => __( 'Mr.', 'give' ),
1508
			'Mrs.' => __( 'Mrs.', 'give' ),
1509
			'Ms.'  => __( 'Ms.', 'give' ),
1510
		)
1511
	);
1512
}
1513
1514
/**
1515
 * This function will check whether the name title prefix field is required or not.
1516
 *
1517
 * @param int $form_id Donation Form ID.
1518
 *
1519
 * @since 2.2.0
1520
 *
1521
 * @return bool
1522
 */
1523
function give_is_name_title_prefix_required( $form_id = 0 ) {
1524
1525
	// Bail out, if name title prefix is not enabled.
1526
	if ( ! give_is_name_title_prefix_enabled( $form_id ) ) {
1527
		return false;
1528
	}
1529
1530
	$status      = array( 'optional' );
1531
	$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...
1532
1533
	if ( intval( $form_id ) > 0 ) {
1534
		$form_title_prefix = give_get_meta( $form_id, '_give_name_title_prefix', true );
1535
1536
		if ( 'required' === $form_title_prefix ) {
1537
			$is_optional = false;
1538
		} elseif ( 'optional' === $form_title_prefix ) {
1539
			$is_optional = true;
1540
		}
1541
	}
1542
1543
	return ( ! $is_optional );
1544
}
1545
1546
/**
1547
 * Deletes form meta when the form is permanently deleted from the trash.
1548
 *
1549
 * @since 2.3.0
1550
 *
1551
 * @param integer $id Donation Form ID which needs to be deleted.
1552
 *
1553
 * @return void
1554
 */
1555
function give_handle_form_meta_on_delete( $id ) {
1556
1557
	global $wpdb;
1558
1559
	$form     = get_post( $id );
1560
	$get_data = give_clean( $_GET );
1561
1562
	if (
1563
		'give_forms' === $form->post_type &&
1564
		'trash' === $form->post_status &&
1565
		(
1566
			( isset( $get_data['action'] ) && 'delete' === $get_data['action'] ) ||
1567
			! empty( $get_data['delete_all'] )
1568
		)
1569
	) {
1570
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->formmeta} WHERE form_id = '%d'", $form->ID ) );
1571
	}
1572
}
1573
1574
add_action( 'before_delete_post', 'give_handle_form_meta_on_delete', 10, 1 );
1575
1576
1577
/**
1578
 * Get list of default param of form shrtcode.
1579
 *
1580
 * @since 2.4.1
1581
 * @return array
1582
 */
1583
function give_get_default_form_shortcode_args() {
1584
	$default = array(
1585
		'id'                    => '',
1586
		'show_title'            => true,
1587
		'show_goal'             => true,
1588
		'show_content'          => '',
1589
		'float_labels'          => '',
1590
		'display_style'         => '',
1591
		'continue_button_title' => '',
1592
	);
1593
1594
	/**
1595
	 * Fire the filter
1596
	 */
1597
	$default = apply_filters( 'give_get_default_form_shortcode_args', $default );
1598
1599
	return $default;
1600
}
1601