Completed
Pull Request — master (#1907)
by
unknown
19:56
created

process-donation.php ➔ give_get_required_fields()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 67
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 33
nc 4
nop 1
dl 0
loc 67
rs 8.8076
c 0
b 0
f 0

How to fix   Long Method   

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 26 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Process Donation
4
 *
5
 * @package     Give
6
 * @subpackage  Functions
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Process Donation Form
19
 *
20
 * Handles the donation form process.
21
 *
22
 * @access      private
23
 * @since       1.0
24
 * @return      false|null
25
 */
26
function give_process_donation_form() {
27
28
	/**
29
	 * Fires before processing the donation form.
30
	 *
31
	 * @since 1.0
32
	 */
33
	do_action( 'give_pre_process_donation' );
34
35
	// Validate the form $_POST data
36
	$valid_data = give_donation_form_validate_fields();
37
38
	/**
39
	 * Fires after validating donation form fields.
40
	 *
41
	 * Allow you to hook to donation form errors.
42
	 *
43
	 * @since 1.0
44
	 *
45
	 * @param bool|array $valid_data Validate fields.
46
	 * @param array $_POST Array of variables passed via the HTTP POST.
47
	 */
48
	do_action( 'give_checkout_error_checks', $valid_data, $_POST );
49
50
	$is_ajax = isset( $_POST['give_ajax'] );
51
52
	// Process the login form
53
	if ( isset( $_POST['give_login_submit'] ) ) {
54
		give_process_form_login();
55
	}
56
57
	// Validate the user
58
	$user = give_get_donation_form_user( $valid_data );
59
60
	if ( false === $valid_data || give_get_errors() || ! $user ) {
61
		if ( $is_ajax ) {
62
			/**
63
			 * Fires when AJAX sends back errors from the donation form.
64
			 *
65
			 * @since 1.0
66
			 */
67
			do_action( 'give_ajax_donation_errors' );
68
			give_die();
69
		} else {
70
			return false;
71
		}
72
	}
73
74
	// If AJAX send back success to proceed with form submission
75
	if ( $is_ajax ) {
76
		echo 'success';
77
		give_die();
78
	}
79
80
	// After AJAX: Setup session if not using php_sessions
81
	if ( ! Give()->session->use_php_sessions() ) {
82
		// Double-check that set_cookie is publicly accessible;
83
		// we're using a slightly modified class-wp-sessions.php
84
		$session_reflection = new ReflectionMethod( 'WP_Session', 'set_cookie' );
85
		if ( $session_reflection->isPublic() ) {
86
			// Manually set the cookie.
87
			Give()->session->init()->set_cookie();
0 ignored issues
show
Bug introduced by
The method set_cookie cannot be called on Give()->session->init() (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
88
		}
89
	}
90
91
	// Setup user information
92
	$user_info = array(
93
		'id'         => $user['user_id'],
94
		'email'      => $user['user_email'],
95
		'first_name' => $user['user_first'],
96
		'last_name'  => $user['user_last'],
97
		'address'    => $user['address'],
98
	);
99
100
	$auth_key = defined( 'AUTH_KEY' ) ? AUTH_KEY : '';
101
102
	$price        = isset( $_POST['give-amount'] ) ? (float) apply_filters( 'give_donation_total', give_sanitize_amount( give_format_amount( $_POST['give-amount'] ) ) ) : '0.00';
103
	$purchase_key = strtolower( md5( $user['user_email'] . date( 'Y-m-d H:i:s' ) . $auth_key . uniqid( 'give', true ) ) );
104
105
	// Setup donation information
106
	$donation_data = array(
107
		'price'        => $price,
108
		'purchase_key' => $purchase_key,
109
		'user_email'   => $user['user_email'],
110
		'date'         => date( 'Y-m-d H:i:s', current_time( 'timestamp' ) ),
111
		'user_info'    => stripslashes_deep( $user_info ),
112
		'post_data'    => $_POST,
113
		'gateway'      => $valid_data['gateway'],
114
		'card_info'    => $valid_data['cc_info'],
115
	);
116
117
	// Add the user data for hooks
118
	$valid_data['user'] = $user;
119
120
	/**
121
	 * Fires before donation form gateway.
122
	 *
123
	 * Allow you to hook to donation form before the gateway.
124
	 *
125
	 * @since 1.0
126
	 *
127
	 * @param array $_POST Array of variables passed via the HTTP POST.
128
	 * @param array $user_info Array containing basic user information.
129
	 * @param bool|array $valid_data Validate fields.
130
	 */
131
	do_action( 'give_checkout_before_gateway', $_POST, $user_info, $valid_data );
132
133
	// Sanity check for price
134
	if ( ! $donation_data['price'] ) {
135
		// Revert to manual
136
		$donation_data['gateway'] = 'manual';
137
		$_POST['give-gateway']    = 'manual';
138
	}
139
140
	/**
141
	 * Allow the donation data to be modified before it is sent to the gateway.
142
	 *
143
	 * @since 1.7
144
	 */
145
	$donation_data = apply_filters( 'give_donation_data_before_gateway', $donation_data, $valid_data );
146
147
	// Setup the data we're storing in the donation session
148
	$session_data = $donation_data;
149
150
	// Make sure credit card numbers are never stored in sessions
151
	unset( $session_data['card_info']['card_number'] );
152
	unset( $session_data['post_data']['card_number'] );
153
154
	// Used for showing data to non logged-in users after donation, and for other plugins needing donation data.
155
	give_set_purchase_session( $session_data );
156
157
	// Send info to the gateway for payment processing
158
	give_send_to_gateway( $donation_data['gateway'], $donation_data );
159
	give_die();
160
161
}
162
163
add_action( 'give_purchase', 'give_process_donation_form' );
164
add_action( 'wp_ajax_give_process_donation', 'give_process_donation_form' );
165
add_action( 'wp_ajax_nopriv_give_process_donation', 'give_process_donation_form' );
166
167
168
/**
169
 * Verify that when a logged in user makes a donation that the email address used doesn't belong to a different customer.
170
 *
171
 * @since  1.7
172
 *
173
 * @param  array $valid_data Validated data submitted for the donation.
174
 * @param  array $post Additional $_POST data submitted
175
 *
176
 * @return void
177
 */
178
function give_check_logged_in_user_for_existing_email( $valid_data, $post ) {
0 ignored issues
show
Unused Code introduced by
The parameter $post is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
179
180
	// Verify that the email address belongs to this customer.
181
	if ( is_user_logged_in() ) {
182
183
		$submitted_email    = $valid_data['logged_in_user']['user_email'];
184
		$customer = new Give_Donor( get_current_user_id(), true );
185
186
		// If this email address is not registered with this customer, see if it belongs to any other customer
187
		if (
188
			$submitted_email !== $customer->email
189
			&& ( is_array( $customer->emails ) && ! in_array( $submitted_email, $customer->emails ) )
190
		) {
191
			$found_customer = new Give_Donor( $submitted_email );
192
193
			if ( $found_customer->id > 0 ) {
194
				give_set_error( 'give-customer-email-exists', sprintf( __( 'You are logged in as %1$s, and are submitting a donation as %2$s, which is an existing donor. To ensure that the email address is tied to the correct donor, please submit this donation from a logged-out browser, or choose another email address.' ,'give' ), $customer->email, $submitted_email ) );
195
			}
196
		}
197
	}
198
}
199
200
add_action( 'give_checkout_error_checks', 'give_check_logged_in_user_for_existing_email', 10, 2 );
201
202
/**
203
 * Process the checkout login form
204
 *
205
 * @access      private
206
 * @since       1.0
207
 * @return      void
208
 */
209
function give_process_form_login() {
210
	$is_ajax = isset( $_POST['give_ajax'] );
211
212
	$user_data = give_donation_form_validate_user_login();
213
214
	if ( give_get_errors() || $user_data['user_id'] < 1 ) {
215
		if ( $is_ajax ) {
216
			/**
217
			 * Fires when AJAX sends back errors from the donation form.
218
			 *
219
			 * @since 1.0
220
			 */
221
			ob_start();
222
				do_action( 'give_ajax_donation_errors' );
223
				$message = ob_get_contents();
224
			ob_end_clean();
225
			wp_send_json_error( $message );
226
		} else {
227
			wp_redirect( $_SERVER['HTTP_REFERER'] );
228
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_process_form_login() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
229
		}
230
	}
231
232
	give_log_user_in( $user_data['user_id'], $user_data['user_login'], $user_data['user_pass'] );
233
234
	if ( $is_ajax ) {
235
		$message = Give()->notices->print_frontend_notice(
236
			sprintf(
237
				/* translators: %s: user first name */
238
				esc_html__( 'Welcome %s! You have successfully logged into your account.', 'give' ),
239
				( ! empty( $user_data['user_first'] ) ) ? $user_data['user_first'] : $user_data['user_login']
240
			),
241
			false,
242
			'success'
243
		);
244
245
		wp_send_json_success( $message );
246
	} else {
247
		wp_redirect( $_SERVER['HTTP_REFERER'] );
248
	}
249
}
250
251
add_action( 'wp_ajax_give_process_donation_login', 'give_process_form_login' );
252
add_action( 'wp_ajax_nopriv_give_process_donation_login', 'give_process_form_login' );
253
254
/**
255
 * Donation Form Validate Fields.
256
 *
257
 * @access      private
258
 * @since       1.0
259
 * @return      bool|array
260
 */
261
function give_donation_form_validate_fields() {
262
263
	// Check if there is $_POST
264
	if ( empty( $_POST ) ) {
265
		return false;
266
	}
267
268
	$form_id = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
269
270
	// Start an array to collect valid data
271
	$valid_data = array(
272
		'gateway'          => give_donation_form_validate_gateway(), // Gateway fallback (amount is validated here)
273
		'need_new_user'    => false,     // New user flag
274
		'need_user_login'  => false,     // Login user flag
275
		'logged_user_data' => array(),   // Logged user collected data
276
		'new_user_data'    => array(),   // New user collected data
277
		'login_user_data'  => array(),   // Login user collected data
278
		'guest_user_data'  => array(),   // Guest user collected data
279
		'cc_info'          => give_donation_form_validate_cc(),// Credit card info
280
	);
281
282
	// Validate Honeypot First
283
	if ( ! empty( $_POST['give-honeypot'] ) ) {
284
		give_set_error( 'invalid_honeypot', esc_html__( 'Honeypot field detected. Go away bad bot!', 'give' ) );
285
	}
286
287
	// Validate agree to terms
288
	if ( give_is_terms_enabled( $form_id ) ) {
289
		give_donation_form_validate_agree_to_terms();
290
	}
291
292
	// Stop processing donor registration, if donor registration is optional and donor can do guest checkout.
293
	// If registration form username field is empty that means donor do not want to registration instead want guest checkout.
294
	if (
295
		! give_logged_in_only( $form_id )
296
		&& isset( $_POST['give-purchase-var'] )
297
		&& $_POST['give-purchase-var'] == 'needs-to-register'
298
		&& empty( $_POST['give_user_login'] )
299
	) {
300
		unset( $_POST['give-purchase-var'] );
301
	}
302
303
	if ( is_user_logged_in() ) {
304
		// Collect logged in user data.
305
		$valid_data['logged_in_user'] = give_donation_form_validate_logged_in_user();
306
	} elseif ( isset( $_POST['give-purchase-var'] ) && $_POST['give-purchase-var'] == 'needs-to-register' ) {
307
		// Set new user registration as required.
308
		$valid_data['need_new_user'] = true;
309
		// Validate new user data.
310
		$valid_data['new_user_data'] = give_donation_form_validate_new_user();
311
		// Check if login validation is needed.
312
	} elseif ( isset( $_POST['give-purchase-var'] ) && $_POST['give-purchase-var'] == 'needs-to-login' ) {
313
		// Set user login as required.
314
		$valid_data['need_user_login'] = true;
315
		// Validate users login info.
316
		$valid_data['login_user_data'] = give_donation_form_validate_user_login();
317
	} else {
318
		// Not registering or logging in, so setup guest user data.
319
		$valid_data['guest_user_data'] = give_donation_form_validate_guest_user();
320
	}
321
322
	// Return collected data.
323
	return $valid_data;
324
}
325
326
/**
327
 * Donation Form Validate Gateway
328
 *
329
 * Validate the gateway and donation amount.
330
 *
331
 * @access      private
332
 * @since       1.0
333
 * @return      string
334
 */
335
function give_donation_form_validate_gateway() {
336
337
	$form_id = isset( $_REQUEST['give-form-id'] ) ? $_REQUEST['give-form-id'] : 0;
338
	$amount  = isset( $_REQUEST['give-amount'] ) ? give_sanitize_amount( $_REQUEST['give-amount'] ) : 0;
339
	$gateway = give_get_default_gateway( $form_id );
340
341
	// Check if a gateway value is present.
342
	if ( ! empty( $_REQUEST['give-gateway'] ) ) {
343
344
		$gateway = sanitize_text_field( $_REQUEST['give-gateway'] );
345
346
		// Is amount being donated in LIVE mode 0.00? If so, error:
347
		if ( $amount == 0 && ! give_is_test_mode() ) {
348
349
			give_set_error( 'invalid_donation_amount', __( 'Please insert a valid donation amount.', 'give' ) );
350
351
		} // End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
352
		elseif ( ! give_verify_minimum_price() ) {
353
			// translators: %s: minimum donation amount.
354
			give_set_error(
355
				'invalid_donation_minimum',
356
				sprintf(
357
					/* translators: %s: minimum donation amount */
358
					__( 'This form has a minimum donation amount of %s.', 'give' ),
359
					give_currency_filter( give_format_amount( give_get_form_minimum_price( $form_id ) ) )
360
				)
361
			);
362
363
		} //Is this test mode zero donation? Let it through but set to manual gateway.
364
		elseif ( $amount == 0 && give_is_test_mode() ) {
365
366
			$gateway = 'manual';
367
368
		} //Check if this gateway is active.
369
		elseif ( ! give_is_gateway_active( $gateway ) ) {
370
371
			give_set_error( 'invalid_gateway', __( 'The selected payment gateway is not enabled.', 'give' ) );
372
373
		}
374
	}
375
376
	return $gateway;
377
378
}
379
380
/**
381
 * Donation Form Validate Minimum Donation Amount
382
 *
383
 * @access      private
384
 * @since       1.3.6
385
 * @return      bool
386
 */
387
function give_verify_minimum_price() {
388
389
	$amount          = give_sanitize_amount( $_REQUEST['give-amount'] );
390
	$form_id         = isset( $_REQUEST['give-form-id'] ) ? $_REQUEST['give-form-id'] : 0;
391
	$price_id        = isset( $_REQUEST['give-price-id'] ) ? $_REQUEST['give-price-id'] : null;
392
	$variable_prices = give_has_variable_prices( $form_id );
393
394
	if ( $variable_prices && in_array( $price_id, give_get_variable_price_ids( $form_id ) ) ) {
395
396
		$price_level_amount = give_get_price_option_amount( $form_id, $price_id );
397
398
		if ( $price_level_amount == $amount ) {
399
			return true;
400
		}
401
	}
402
403
	if ( give_get_form_minimum_price( $form_id ) > $amount ) {
404
		return false;
405
	}
406
407
	return true;
408
}
409
410
/**
411
 * Donation form validate agree to "Terms and Conditions".
412
 *
413
 * @access      private
414
 * @since       1.0
415
 * @return      void
416
 */
417
function give_donation_form_validate_agree_to_terms() {
418
	// Validate agree to terms.
419
	if ( ! isset( $_POST['give_agree_to_terms'] ) || $_POST['give_agree_to_terms'] != 1 ) {
420
		// User did not agree.
421
		give_set_error( 'agree_to_terms', apply_filters( 'give_agree_to_terms_text', __( 'You must agree to the terms and conditions.', 'give' ) ) );
422
	}
423
}
424
425
/**
426
 * Donation Form Required Fields.
427
 *
428
 * @access      private
429
 * @since       1.0
430
 *
431
 * @param       $form_id
432
 *
433
 * @return      array
434
 */
435
function give_get_required_fields( $form_id ) {
436
437
	$payment_mode = give_get_chosen_gateway( $form_id );
438
439
	$required_fields = array(
440
		'give_email' => array(
441
			'error_id'      => 'invalid_email',
442
			'error_message' => __( 'Please enter a valid email address.', 'give' ),
443
		),
444
		'give_first' => array(
445
			'error_id'      => 'invalid_first_name',
446
			'error_message' => __( 'Please enter your first name.', 'give' ),
447
		),
448
	);
449
450
	$require_address = give_require_billing_address( $payment_mode );
451
452
	if ( $require_address ) {
453
		$required_fields['card_address']    = array(
454
			'error_id'      => 'invalid_card_address',
455
			'error_message' => __( 'Please enter your primary billing address.', 'give' ),
456
		);
457
		$required_fields['card_zip']        = array(
458
			'error_id'      => 'invalid_zip_code',
459
			'error_message' => __( 'Please enter your zip / postal code.', 'give' ),
460
		);
461
		$required_fields['card_city']       = array(
462
			'error_id'      => 'invalid_city',
463
			'error_message' => __( 'Please enter your billing city.', 'give' ),
464
		);
465
		$required_fields['billing_country'] = array(
466
			'error_id'      => 'invalid_country',
467
			'error_message' => __( 'Please select your billing country.', 'give' ),
468
		);
469
470
471
		$required_fields['card_state']      = array(
472
			'error_id'      => 'invalid_state',
473
			'error_message' => __( 'Please enter billing state / province / County.', 'give' ),
474
		);
475
476
		// Check if billing country alredy exists.
477
		if ( ! empty( $_POST['billing_country'] ) ) {
478
			// Get the value from $_POST.
479
			$country = sanitize_text_field( $_POST['billing_country'] );
480
481
			// Get the country list that does not have any states init.
482
			$no_states_country = give_no_states_country_list();
483
484
			// Check if states is empty or not.
485
			if ( array_key_exists( $country, $no_states_country ) ) {
486
				// If states is empty remove the required feilds of state in billing cart.
487
				unset( $required_fields['card_state'] );
488
			}
489
		}
490
	}
491
492
	/**
493
	 * Filters the donation form required field.
494
	 *
495
	 * @since 1.7
496
	 */
497
	$required_fields = apply_filters( 'give_donation_form_required_fields', $required_fields, $form_id );
498
499
	return $required_fields;
500
501
}
502
503
/**
504
 * Check if the Billing Address is required
505
 *
506
 * @since  1.0.1
507
 *
508
 * @param string $payment_mode
509
 *
510
 * @return bool
511
 */
512
function give_require_billing_address( $payment_mode ) {
513
514
	$return = false;
515
516
	if ( isset( $_POST['billing_country'] ) || did_action( "give_{$payment_mode}_cc_form" ) || did_action( 'give_cc_form' ) ) {
517
		$return = true;
518
	}
519
520
	// Let payment gateways and other extensions determine if address fields should be required.
521
	return apply_filters( 'give_require_billing_address', $return );
522
523
}
524
525
/**
526
 * Donation Form Validate Logged In User.
527
 *
528
 * @access      private
529
 * @since       1.0
530
 * @return      array
531
 */
532
function give_donation_form_validate_logged_in_user() {
533
	global $user_ID;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
534
535
	$form_id = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
536
537
	// Start empty array to collect valid user data.
538
	$valid_user_data = array(
539
		// Assume there will be errors.
540
		'user_id' => - 1,
541
	);
542
543
	// Verify there is a user_ID.
544
	if ( $user_ID > 0 ) {
545
		// Get the logged in user data.
546
		$user_data = get_userdata( $user_ID );
547
548
		// Loop through required fields and show error messages.
549
		foreach ( give_get_required_fields( $form_id ) as $field_name => $value ) {
550
			if ( in_array( $value, give_get_required_fields( $form_id ) ) && empty( $_POST[ $field_name ] ) ) {
551
				give_set_error( $value['error_id'], $value['error_message'] );
552
			}
553
		}
554
555
		// Verify data.
556
		if ( $user_data ) {
557
			// Collected logged in user data.
558
			$valid_user_data = array(
559
				'user_id'    => $user_ID,
560
				'user_email' => isset( $_POST['give_email'] ) ? sanitize_email( $_POST['give_email'] ) : $user_data->user_email,
561
				'user_first' => isset( $_POST['give_first'] ) && ! empty( $_POST['give_first'] ) ? sanitize_text_field( $_POST['give_first'] ) : $user_data->first_name,
562
				'user_last'  => isset( $_POST['give_last'] ) && ! empty( $_POST['give_last'] ) ? sanitize_text_field( $_POST['give_last'] ) : $user_data->last_name,
563
			);
564
565
			if ( ! is_email( $valid_user_data['user_email'] ) ) {
566
				give_set_error( 'email_invalid', esc_html__( 'Invalid email.', 'give' ) );
567
			}
568
		} else {
569
			// Set invalid user error.
570
			give_set_error( 'invalid_user', esc_html__( 'The user information is invalid.', 'give' ) );
571
		}
572
	}
573
574
	// Return user data.
575
	return $valid_user_data;
576
}
577
578
/**
579
 * Donate Form Validate New User
580
 *
581
 * @access      private
582
 * @since       1.0
583
 * @return      array
584
 */
585
function give_donation_form_validate_new_user() {
586
	// Default user data.
587
	$default_user_data = array(
588
		'give-form-id'           => '',
589
		'user_id'                => - 1, // Assume there will be errors.
590
		'user_first'             => '',
591
		'user_last'              => '',
592
		'give_user_login'        => false,
593
		'give_email'             => false,
594
		'give_user_pass'         => false,
595
		'give_user_pass_confirm' => false,
596
	);
597
598
	// Get user data.
599
	$user_data            = wp_parse_args( array_map( 'trim', give_clean( $_POST ) ), $default_user_data );
600
	$registering_new_user = false;
601
	$form_id              = absint( $user_data['give-form-id'] );
602
603
	// Start an empty array to collect valid user data.
604
	$valid_user_data = array(
605
		// Assume there will be errors.
606
		'user_id'    => - 1,
607
608
		// Get first name.
609
		'user_first' => $user_data['give_first'],
610
611
		// Get last name.
612
		'user_last'  => $user_data['give_last'],
613
	);
614
615
	// Loop through required fields and show error messages.
616
	foreach ( give_get_required_fields( $form_id ) as $field_name => $value ) {
617
		if ( in_array( $value, give_get_required_fields( $form_id ) ) && empty( $_POST[ $field_name ] ) ) {
618
			give_set_error( $value['error_id'], $value['error_message'] );
619
		}
620
	}
621
622
	// Check if we have an username to register.
623
	if ( give_validate_username( $user_data['give_user_login'] ) ) {
624
		$registering_new_user          = true;
625
		$valid_user_data['user_login'] = $user_data['give_user_login'];
626
	}
627
628
	// Check if we have an email to verify.
629
	if ( give_validate_user_email( $user_data['give_email'], $registering_new_user ) ) {
630
		$valid_user_data['user_email'] = $user_data['give_email'];
631
	}
632
633
	// Check password.
634
	if ( give_validate_user_password( $user_data['give_user_pass'], $user_data['give_user_pass_confirm'], $registering_new_user ) ) {
635
		// All is good to go.
636
		$valid_user_data['user_pass'] = $user_data['give_user_pass'];
637
	}
638
639
	return $valid_user_data;
640
}
641
642
/**
643
 * Donation Form Validate User Login
644
 *
645
 * @access      private
646
 * @since       1.0
647
 * @return      array
648
 */
649
function give_donation_form_validate_user_login() {
650
651
	// Start an array to collect valid user data.
652
	$valid_user_data = array(
653
		// Assume there will be errors.
654
		'user_id' => - 1,
655
	);
656
657
	// Username.
658
	if ( ! isset( $_POST['give_user_login'] ) || $_POST['give_user_login'] == '' ) {
659
		give_set_error( 'must_log_in', __( 'You must register or login to complete your donation.', 'give' ) );
660
661
		return $valid_user_data;
662
	}
663
664
	// Get the user by login.
665
	$user_data = get_user_by( 'login', strip_tags( $_POST['give_user_login'] ) );
666
667
	// Check if user exists.
668
	if ( $user_data ) {
669
		// Get password.
670
		$user_pass = isset( $_POST['give_user_pass'] ) ? $_POST['give_user_pass'] : false;
671
672
		// Check user_pass.
673
		if ( $user_pass ) {
674
			// Check if password is valid.
675
			if ( ! wp_check_password( $user_pass, $user_data->user_pass, $user_data->ID ) ) {
676
				// Incorrect password.
677
				give_set_error(
678
					'password_incorrect',
679
					sprintf(
680
						'%1$s <a href="%2$s">%3$s</a>',
681
						__( 'The password you entered is incorrect.', 'give' ),
682
						wp_lostpassword_url( "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ),
683
						__( 'Reset Password', 'give' )
684
					)
685
				);
686
				// All is correct.
687
			} else {
688
				// Repopulate the valid user data array.
689
				$valid_user_data = array(
690
					'user_id'    => $user_data->ID,
691
					'user_login' => $user_data->user_login,
692
					'user_email' => $user_data->user_email,
693
					'user_first' => $user_data->first_name,
694
					'user_last'  => $user_data->last_name,
695
					'user_pass'  => $user_pass,
696
				);
697
			}
698
		} else {
699
			// Empty password.
700
			give_set_error( 'password_empty', __( 'Enter a password.', 'give' ) );
701
		}
702
	} else {
703
		// No username.
704
		give_set_error( 'username_incorrect', __( 'The username you entered does not exist.', 'give' ) );
705
	}// End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
706
707
	return $valid_user_data;
708
}
709
710
/**
711
 * Donation Form Validate Guest User
712
 *
713
 * @access  private
714
 * @since   1.0
715
 * @return  array
716
 */
717
function give_donation_form_validate_guest_user() {
718
719
	$form_id = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
720
721
	// Start an array to collect valid user data.
722
	$valid_user_data = array(
723
		// Set a default id for guests.
724
		'user_id' => 0,
725
	);
726
727
	// Show error message if user must be logged in.
728
	if ( give_logged_in_only( $form_id ) ) {
729
		give_set_error( 'logged_in_only', __( 'You must be logged in to donate.', 'give' ) );
730
	}
731
732
	// Get the guest email.
733
	$guest_email = isset( $_POST['give_email'] ) ? $_POST['give_email'] : false;
734
735
	// Check email.
736
	if ( $guest_email && strlen( $guest_email ) > 0 ) {
737
		// Validate email.
738
		if ( ! is_email( $guest_email ) ) {
739
			// Invalid email.
740
			give_set_error( 'email_invalid', __( 'Invalid email.', 'give' ) );
741
		} else {
742
			// All is good to go.
743
			$valid_user_data['user_email'] = $guest_email;
744
745
			// Get user_id from donor if exist.
746
			$donor = new Give_Donor( $guest_email );
747
			if ( $donor->id && $donor->user_id ) {
748
				$valid_user_data['user_id'] = $donor->user_id;
749
			}
750
		}
751
	} else {
752
		// No email.
753
		give_set_error( 'email_empty', __( 'Enter an email.', 'give' ) );
754
	}
755
756
	// Loop through required fields and show error messages.
757
	foreach ( give_get_required_fields( $form_id ) as $field_name => $value ) {
758
		if ( in_array( $value, give_get_required_fields( $form_id ) ) && empty( $_POST[ $field_name ] ) ) {
759
			give_set_error( $value['error_id'], $value['error_message'] );
760
		}
761
	}
762
763
	return $valid_user_data;
764
}
765
766
/**
767
 * Register And Login New User
768
 *
769
 * @param array $user_data
770
 *
771
 * @access  private
772
 * @since   1.0
773
 * @return  integer
774
 */
775
function give_register_and_login_new_user( $user_data = array() ) {
776
	// Verify the array.
777
	if ( empty( $user_data ) ) {
778
		return - 1;
779
	}
780
781
	if ( give_get_errors() ) {
782
		return - 1;
783
	}
784
785
	$user_args = apply_filters( 'give_insert_user_args', array(
786
		'user_login'      => isset( $user_data['user_login'] ) ? $user_data['user_login'] : '',
787
		'user_pass'       => isset( $user_data['user_pass'] ) ? $user_data['user_pass'] : '',
788
		'user_email'      => isset( $user_data['user_email'] ) ? $user_data['user_email'] : '',
789
		'first_name'      => isset( $user_data['user_first'] ) ? $user_data['user_first'] : '',
790
		'last_name'       => isset( $user_data['user_last'] ) ? $user_data['user_last'] : '',
791
		'user_registered' => date( 'Y-m-d H:i:s' ),
792
		'role'            => get_option( 'default_role' ),
793
	), $user_data );
794
795
	// Insert new user.
796
	$user_id = wp_insert_user( $user_args );
797
798
	// Validate inserted user.
799
	if ( is_wp_error( $user_id ) ) {
800
		return - 1;
801
	}
802
803
	// Allow themes and plugins to filter the user data.
804
	$user_data = apply_filters( 'give_insert_user_data', $user_data, $user_args );
805
806
	/**
807
	 * Fires after inserting user.
808
	 *
809
	 * @since 1.0
810
	 *
811
	 * @param int $user_id User id.
812
	 * @param array $user_data Array containing user data.
813
	 */
814
	do_action( 'give_insert_user', $user_id, $user_data );
815
816
	// Login new user.
817
	give_log_user_in( $user_id, $user_data['user_login'], $user_data['user_pass'] );
818
819
	// Return user id.
820
	return $user_id;
821
}
822
823
/**
824
 * Get Donation Form User
825
 *
826
 * @param array $valid_data
827
 *
828
 * @access  private
829
 * @since   1.0
830
 * @return  array|bool
831
 */
832
function give_get_donation_form_user( $valid_data = array() ) {
833
834
	// Initialize user.
835
	$user    = false;
836
	$is_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
837
838
	if ( $is_ajax ) {
839
		// Do not create or login the user during the ajax submission (check for errors only).
840
		return true;
841
	} elseif ( is_user_logged_in() ) {
842
		// Set the valid user as the logged in collected data.
843
		$user = $valid_data['logged_in_user'];
844
	} elseif ( $valid_data['need_new_user'] === true || $valid_data['need_user_login'] === true ) {
845
		// New user registration.
846
		if ( $valid_data['need_new_user'] === true ) {
847
			// Set user.
848
			$user = $valid_data['new_user_data'];
849
			// Register and login new user.
850
			$user['user_id'] = give_register_and_login_new_user( $user );
851
			// User login
852
		} elseif ( $valid_data['need_user_login'] === true && ! $is_ajax ) {
853
854
			/**
855
			 * The login form is now processed in the give_process_donation_login() function.
856
			 * This is still here for backwards compatibility.
857
			 * This also allows the old login process to still work if a user removes the checkout login submit button.
858
			 *
859
			 * This also ensures that the donor is logged in correctly if they click "Donation" instead of submitting the login form, meaning the donor is logged in during the donation process.
860
			 */
861
			// Set user.
862
			$user = $valid_data['login_user_data'];
863
			// Login user.
864
			give_log_user_in( $user['user_id'], $user['user_login'], $user['user_pass'] );
865
		}
866
	}
867
868
	// Check guest checkout.
869
	if ( false === $user && false === give_logged_in_only( $_POST['give-form-id'] ) ) {
870
		// Set user
871
		$user = $valid_data['guest_user_data'];
872
	}
873
874
	// Verify we have an user.
875
	if ( false === $user || empty( $user ) ) {
876
		// Return false.
877
		return false;
878
	}
879
880
	// Get user first name.
881
	if ( ! isset( $user['user_first'] ) || strlen( trim( $user['user_first'] ) ) < 1 ) {
882
		$user['user_first'] = isset( $_POST['give_first'] ) ? strip_tags( trim( $_POST['give_first'] ) ) : '';
883
	}
884
885
	// Get user last name.
886
	if ( ! isset( $user['user_last'] ) || strlen( trim( $user['user_last'] ) ) < 1 ) {
887
		$user['user_last'] = isset( $_POST['give_last'] ) ? strip_tags( trim( $_POST['give_last'] ) ) : '';
888
	}
889
890
	// Get the user's billing address details.
891
	$user['address']            = array();
892
	$user['address']['line1']   = ! empty( $_POST['card_address'] ) ? sanitize_text_field( $_POST['card_address'] ) : false;
893
	$user['address']['line2']   = ! empty( $_POST['card_address_2'] ) ? sanitize_text_field( $_POST['card_address_2'] ) : false;
894
	$user['address']['city']    = ! empty( $_POST['card_city'] ) ? sanitize_text_field( $_POST['card_city'] ) : false;
895
	$user['address']['state']   = ! empty( $_POST['card_state'] ) ? sanitize_text_field( $_POST['card_state'] ) : false;
896
	$user['address']['country'] = ! empty( $_POST['billing_country'] ) ? sanitize_text_field( $_POST['billing_country'] ) : false;
897
	$user['address']['zip']     = ! empty( $_POST['card_zip'] ) ? sanitize_text_field( $_POST['card_zip'] ) : false;
898
899
	if ( empty( $user['address']['country'] ) ) {
900
		$user['address'] = false;
901
	} // End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
902
903
	if ( ! empty( $user['user_id'] ) && $user['user_id'] > 0 && ! empty( $user['address'] ) ) {
904
		// Store the address in the user's meta so the donation form can be pre-populated with it on return donation.
905
		update_user_meta( $user['user_id'], '_give_user_address', $user['address'] );
906
	}
907
908
	// Return valid user.
909
	return $user;
910
}
911
912
/**
913
 * Validates the credit card info.
914
 *
915
 * @access  private
916
 * @since   1.0
917
 * @return  array
918
 */
919
function give_donation_form_validate_cc() {
920
921
	$card_data = give_get_donation_cc_info();
922
923
	// Validate the card zip.
924
	if ( ! empty( $card_data['card_zip'] ) ) {
925
		if ( ! give_donation_form_validate_cc_zip( $card_data['card_zip'], $card_data['card_country'] ) ) {
926
			give_set_error( 'invalid_cc_zip', __( 'The zip / postal code you entered for your billing address is invalid.', 'give' ) );
927
		}
928
	}
929
930
	// Ensure no spaces.
931
	if ( ! empty( $card_data['card_number'] ) ) {
932
		$card_data['card_number'] = str_replace( '+', '', $card_data['card_number'] ); // no "+" signs
933
		$card_data['card_number'] = str_replace( ' ', '', $card_data['card_number'] ); // No spaces
934
	}
935
936
	// This should validate card numbers at some point too.
937
	return $card_data;
938
}
939
940
/**
941
 * Get credit card info.
942
 *
943
 * @access  private
944
 * @since   1.0
945
 * @return  array
946
 */
947
function give_get_donation_cc_info() {
948
949
	$cc_info                   = array();
950
	$cc_info['card_name']      = isset( $_POST['card_name'] ) ? sanitize_text_field( $_POST['card_name'] ) : '';
951
	$cc_info['card_number']    = isset( $_POST['card_number'] ) ? sanitize_text_field( $_POST['card_number'] ) : '';
952
	$cc_info['card_cvc']       = isset( $_POST['card_cvc'] ) ? sanitize_text_field( $_POST['card_cvc'] ) : '';
953
	$cc_info['card_exp_month'] = isset( $_POST['card_exp_month'] ) ? sanitize_text_field( $_POST['card_exp_month'] ) : '';
954
	$cc_info['card_exp_year']  = isset( $_POST['card_exp_year'] ) ? sanitize_text_field( $_POST['card_exp_year'] ) : '';
955
	$cc_info['card_address']   = isset( $_POST['card_address'] ) ? sanitize_text_field( $_POST['card_address'] ) : '';
956
	$cc_info['card_address_2'] = isset( $_POST['card_address_2'] ) ? sanitize_text_field( $_POST['card_address_2'] ) : '';
957
	$cc_info['card_city']      = isset( $_POST['card_city'] ) ? sanitize_text_field( $_POST['card_city'] ) : '';
958
	$cc_info['card_state']     = isset( $_POST['card_state'] ) ? sanitize_text_field( $_POST['card_state'] ) : '';
959
	$cc_info['card_country']   = isset( $_POST['billing_country'] ) ? sanitize_text_field( $_POST['billing_country'] ) : '';
960
	$cc_info['card_zip']       = isset( $_POST['card_zip'] ) ? sanitize_text_field( $_POST['card_zip'] ) : '';
961
962
	// Return cc info.
963
	return $cc_info;
964
}
965
966
/**
967
 * Validate zip code based on country code
968
 *
969
 * @since  1.0
970
 *
971
 * @param int    $zip
972
 * @param string $country_code
973
 *
974
 * @return bool|mixed
975
 */
976
function give_donation_form_validate_cc_zip( $zip = 0, $country_code = '' ) {
977
	$ret = false;
978
979
	if ( empty( $zip ) || empty( $country_code ) ) {
980
		return $ret;
981
	}
982
983
	$country_code = strtoupper( $country_code );
984
985
	$zip_regex = array(
986
		'AD' => 'AD\d{3}',
987
		'AM' => '(37)?\d{4}',
988
		'AR' => '^([A-Z]{1}\d{4}[A-Z]{3}|[A-Z]{1}\d{4}|\d{4})$',
989
		'AS' => '96799',
990
		'AT' => '\d{4}',
991
		'AU' => '^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$',
992
		'AX' => '22\d{3}',
993
		'AZ' => '\d{4}',
994
		'BA' => '\d{5}',
995
		'BB' => '(BB\d{5})?',
996
		'BD' => '\d{4}',
997
		'BE' => '^[1-9]{1}[0-9]{3}$',
998
		'BG' => '\d{4}',
999
		'BH' => '((1[0-2]|[2-9])\d{2})?',
1000
		'BM' => '[A-Z]{2}[ ]?[A-Z0-9]{2}',
1001
		'BN' => '[A-Z]{2}[ ]?\d{4}',
1002
		'BR' => '\d{5}[\-]?\d{3}',
1003
		'BY' => '\d{6}',
1004
		'CA' => '^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$',
1005
		'CC' => '6799',
1006
		'CH' => '^[1-9][0-9][0-9][0-9]$',
1007
		'CK' => '\d{4}',
1008
		'CL' => '\d{7}',
1009
		'CN' => '\d{6}',
1010
		'CR' => '\d{4,5}|\d{3}-\d{4}',
1011
		'CS' => '\d{5}',
1012
		'CV' => '\d{4}',
1013
		'CX' => '6798',
1014
		'CY' => '\d{4}',
1015
		'CZ' => '\d{3}[ ]?\d{2}',
1016
		'DE' => '\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b',
1017
		'DK' => '^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$',
1018
		'DO' => '\d{5}',
1019
		'DZ' => '\d{5}',
1020
		'EC' => '([A-Z]\d{4}[A-Z]|(?:[A-Z]{2})?\d{6})?',
1021
		'EE' => '\d{5}',
1022
		'EG' => '\d{5}',
1023
		'ES' => '^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$',
1024
		'ET' => '\d{4}',
1025
		'FI' => '\d{5}',
1026
		'FK' => 'FIQQ 1ZZ',
1027
		'FM' => '(9694[1-4])([ \-]\d{4})?',
1028
		'FO' => '\d{3}',
1029
		'FR' => '^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$',
1030
		'GE' => '\d{4}',
1031
		'GF' => '9[78]3\d{2}',
1032
		'GL' => '39\d{2}',
1033
		'GN' => '\d{3}',
1034
		'GP' => '9[78][01]\d{2}',
1035
		'GR' => '\d{3}[ ]?\d{2}',
1036
		'GS' => 'SIQQ 1ZZ',
1037
		'GT' => '\d{5}',
1038
		'GU' => '969[123]\d([ \-]\d{4})?',
1039
		'GW' => '\d{4}',
1040
		'HM' => '\d{4}',
1041
		'HN' => '(?:\d{5})?',
1042
		'HR' => '\d{5}',
1043
		'HT' => '\d{4}',
1044
		'HU' => '\d{4}',
1045
		'ID' => '\d{5}',
1046
		'IE' => '((D|DUBLIN)?([1-9]|6[wW]|1[0-8]|2[024]))?',
1047
		'IL' => '\d{5}',
1048
		'IN' => '^[1-9][0-9][0-9][0-9][0-9][0-9]$', // india
1049
		'IO' => 'BBND 1ZZ',
1050
		'IQ' => '\d{5}',
1051
		'IS' => '\d{3}',
1052
		'IT' => '^(V-|I-)?[0-9]{5}$',
1053
		'JO' => '\d{5}',
1054
		'JP' => '\d{3}-\d{4}',
1055
		'KE' => '\d{5}',
1056
		'KG' => '\d{6}',
1057
		'KH' => '\d{5}',
1058
		'KR' => '\d{3}[\-]\d{3}',
1059
		'KW' => '\d{5}',
1060
		'KZ' => '\d{6}',
1061
		'LA' => '\d{5}',
1062
		'LB' => '(\d{4}([ ]?\d{4})?)?',
1063
		'LI' => '(948[5-9])|(949[0-7])',
1064
		'LK' => '\d{5}',
1065
		'LR' => '\d{4}',
1066
		'LS' => '\d{3}',
1067
		'LT' => '\d{5}',
1068
		'LU' => '\d{4}',
1069
		'LV' => '\d{4}',
1070
		'MA' => '\d{5}',
1071
		'MC' => '980\d{2}',
1072
		'MD' => '\d{4}',
1073
		'ME' => '8\d{4}',
1074
		'MG' => '\d{3}',
1075
		'MH' => '969[67]\d([ \-]\d{4})?',
1076
		'MK' => '\d{4}',
1077
		'MN' => '\d{6}',
1078
		'MP' => '9695[012]([ \-]\d{4})?',
1079
		'MQ' => '9[78]2\d{2}',
1080
		'MT' => '[A-Z]{3}[ ]?\d{2,4}',
1081
		'MU' => '(\d{3}[A-Z]{2}\d{3})?',
1082
		'MV' => '\d{5}',
1083
		'MX' => '\d{5}',
1084
		'MY' => '\d{5}',
1085
		'NC' => '988\d{2}',
1086
		'NE' => '\d{4}',
1087
		'NF' => '2899',
1088
		'NG' => '(\d{6})?',
1089
		'NI' => '((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?',
1090
		'NL' => '^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$',
1091
		'NO' => '\d{4}',
1092
		'NP' => '\d{5}',
1093
		'NZ' => '\d{4}',
1094
		'OM' => '(PC )?\d{3}',
1095
		'PF' => '987\d{2}',
1096
		'PG' => '\d{3}',
1097
		'PH' => '\d{4}',
1098
		'PK' => '\d{5}',
1099
		'PL' => '\d{2}-\d{3}',
1100
		'PM' => '9[78]5\d{2}',
1101
		'PN' => 'PCRN 1ZZ',
1102
		'PR' => '00[679]\d{2}([ \-]\d{4})?',
1103
		'PT' => '\d{4}([\-]\d{3})?',
1104
		'PW' => '96940',
1105
		'PY' => '\d{4}',
1106
		'RE' => '9[78]4\d{2}',
1107
		'RO' => '\d{6}',
1108
		'RS' => '\d{5}',
1109
		'RU' => '\d{6}',
1110
		'SA' => '\d{5}',
1111
		'SE' => '^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$',
1112
		'SG' => '\d{6}',
1113
		'SH' => '(ASCN|STHL) 1ZZ',
1114
		'SI' => '\d{4}',
1115
		'SJ' => '\d{4}',
1116
		'SK' => '\d{3}[ ]?\d{2}',
1117
		'SM' => '4789\d',
1118
		'SN' => '\d{5}',
1119
		'SO' => '\d{5}',
1120
		'SZ' => '[HLMS]\d{3}',
1121
		'TC' => 'TKCA 1ZZ',
1122
		'TH' => '\d{5}',
1123
		'TJ' => '\d{6}',
1124
		'TM' => '\d{6}',
1125
		'TN' => '\d{4}',
1126
		'TR' => '\d{5}',
1127
		'TW' => '\d{3}(\d{2})?',
1128
		'UA' => '\d{5}',
1129
		'UK' => '^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$',
1130
		'US' => '^\d{5}([\-]?\d{4})?$',
1131
		'UY' => '\d{5}',
1132
		'UZ' => '\d{6}',
1133
		'VA' => '00120',
1134
		'VE' => '\d{4}',
1135
		'VI' => '008(([0-4]\d)|(5[01]))([ \-]\d{4})?',
1136
		'WF' => '986\d{2}',
1137
		'YT' => '976\d{2}',
1138
		'YU' => '\d{5}',
1139
		'ZA' => '\d{4}',
1140
		'ZM' => '\d{5}',
1141
	);
1142
1143
	if ( ! isset( $zip_regex[ $country_code ] ) || preg_match( '/' . $zip_regex[ $country_code ] . '/i', $zip ) ) {
1144
		$ret = true;
1145
	}
1146
1147
	return apply_filters( 'give_is_zip_valid', $ret, $zip, $country_code );
1148
}
1149
1150
1151
/**
1152
 * Auto set correct donation level id on basis of amount.
1153
 *
1154
 * Note: If amount does not match to donation level amount then level id will be auto select to first match level id on basis of amount.
1155
 *
1156
 * @param array $valid_data
1157
 * @param array $data
1158
 *
1159
 * @return bool
1160
 */
1161
function give_validate_multi_donation_form_level( $valid_data, $data ) {
0 ignored issues
show
Unused Code introduced by
The parameter $valid_data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1162
	/* @var Give_Donate_Form $form */
1163
	$form = new Give_Donate_Form( $data['give-form-id'] );
1164
1165
	$donation_level_matched = false;
1166
1167
	if ( $form->is_multi_type_donation_form() ) {
1168
1169
		// Bailout.
1170
		if ( ! ( $variable_prices = $form->get_prices() ) ) {
1171
			return false;
1172
		}
1173
1174
		// Sanitize donation amount.
1175
		$data['give-amount'] = give_sanitize_amount( $data['give-amount'] );
1176
1177
		// Get number of decimals.
1178
		$default_decimals = give_get_price_decimals();
1179
1180
		if ( $data['give-amount'] === give_sanitize_amount( give_get_price_option_amount( $data['give-form-id'], $data['give-price-id'] ), $default_decimals ) ) {
1181
			return true;
1182
		}
1183
1184
		// Find correct donation level from all donation levels.
1185
		foreach ( $variable_prices as $variable_price ) {
1186
			// Sanitize level amount.
1187
			$variable_price['_give_amount'] = give_sanitize_amount( $variable_price['_give_amount'], $default_decimals );
1188
1189
			// Set first match donation level ID.
1190
			if ( $data['give-amount'] === $variable_price['_give_amount'] ) {
1191
				$_POST['give-price-id'] = $variable_price['_give_id']['level_id'];
1192
				$donation_level_matched = true;
1193
				break;
1194
			}
1195
		}
1196
1197
		// If donation amount is not find in donation levels then check if form has custom donation feature enable or not.
1198
		// If yes then set price id to custom if amount is greater then custom minimum amount (if any).
1199
		if (
1200
			! $donation_level_matched
1201
			&& ( give_is_setting_enabled( give_get_meta( $data['give-form-id'], '_give_custom_amount', true ) ) )
1202
		) {
1203
			// Sanitize custom minimum amount.
1204
			$custom_minimum_amount = give_sanitize_amount( give_get_meta( $data['give-form-id'], '_give_custom_amount_minimum', true ), $default_decimals );
1205
1206
			if ( $data['give-amount'] >= $custom_minimum_amount ) {
1207
				$_POST['give-price-id'] = 'custom';
1208
				$donation_level_matched = true;
1209
			}
1210
		}
1211
	}// End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1212
1213
	return ( $donation_level_matched ? true : false );
1214
}
1215
1216
add_action( 'give_checkout_error_checks', 'give_validate_multi_donation_form_level', 10, 2 );
1217