Completed
Push — es6/issue-1475 ( 93c1ad )
by Ravinder
1139:39 queued 1133:44
created

process-donation.php ➔ give_donation_form_validate_gateway()   C

Complexity

Conditions 11
Paths 28

Size

Total Lines 56

Duplication

Lines 24
Ratio 42.86 %

Importance

Changes 0
Metric Value
cc 11
nc 28
nop 0
dl 24
loc 56
rs 6.8133
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
 * 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
 *
25
 * @return mixed
26
 */
27
function give_process_donation_form() {
28
	$is_ajax = isset( $_POST['give_ajax'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
29
30
	// Verify donation form nonce.
31
	if(  ! give_verify_donation_form_nonce() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 2 found
Loading history...
32
		if( $is_ajax ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
33
			/**
34
			 * Fires when AJAX sends back errors from the donation form.
35
			 *
36
			 * @since 1.0
37
			 */
38
			do_action( 'give_ajax_donation_errors' );
39
			
40
			give_die();
41
		} else{
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
42
			give_send_back_to_checkout();
43
		}
44
	}
45
46
	/**
47
	 * Fires before processing the donation form.
48
	 *
49
	 * @since 1.0
50
	 */
51
	do_action( 'give_pre_process_donation' );
52
53
	// Validate the form $_POST data.
54
	$valid_data = give_donation_form_validate_fields();
55
56
	/**
57
	 * Fires after validating donation form fields.
58
	 *
59
	 * Allow you to hook to donation form errors.
60
	 *
61
	 * @since 1.0
62
	 *
63
	 * @param bool|array $valid_data Validate fields.
64
	 * @param array $deprecated Deprecated Since 2.0.2. Use $_POST instead.
65
	 */
66
	do_action( 'give_checkout_error_checks', $valid_data, $deprecated = $_POST );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
67
68
	// Process the login form.
69
	if ( isset( $_POST['give_login_submit'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
70
		give_process_form_login();
71
	}
72
73
	// Validate the user.
74
	$user = give_get_donation_form_user( $valid_data );
0 ignored issues
show
Security Bug introduced by
It seems like $valid_data defined by give_donation_form_validate_fields() on line 54 can also be of type false; however, give_get_donation_form_user() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
75
76
	if ( false === $valid_data || give_get_errors() || ! $user ) {
77
		if ( $is_ajax ) {
78
			/**
79
			 * Fires when AJAX sends back errors from the donation form.
80
			 *
81
			 * @since 1.0
82
			 */
83
			do_action( 'give_ajax_donation_errors' );
84
			give_die();
85
		} else {
86
			return false;
87
		}
88
	}
89
90
	// If AJAX send back success to proceed with form submission.
91
	if ( $is_ajax ) {
92
		echo 'success';
93
		give_die();
94
	}
95
96
	// After AJAX: Setup session if not using php_sessions.
97
	if ( ! Give()->session->use_php_sessions() ) {
98
		// Double-check that set_cookie is publicly accessible.
99
		// we're using a slightly modified class-wp-sessions.php.
100
		$session_reflection = new ReflectionMethod( 'WP_Session', 'set_cookie' );
101
		if ( $session_reflection->isPublic() ) {
102
			// Manually set the cookie.
103
			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...
104
		}
105
	}
106
107
	// Setup user information.
108
	$user_info = array(
109
		'id'         => $user['user_id'],
110
		'email'      => $user['user_email'],
111
		'first_name' => $user['user_first'],
112
		'last_name'  => $user['user_last'],
113
		'address'    => $user['address'],
114
	);
115
116
	$auth_key = defined( 'AUTH_KEY' ) ? AUTH_KEY : '';
117
118
	$price        = isset( $_POST['give-amount'] ) ?
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
119
		(float) apply_filters( 'give_donation_total', give_maybe_sanitize_amount( $_POST['give-amount'] ) ) :
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
120
		'0.00';
121
	$purchase_key = strtolower( md5( $user['user_email'] . date( 'Y-m-d H:i:s' ) . $auth_key . uniqid( 'give', true ) ) );
122
123
	// Setup donation information.
124
	$donation_data = array(
125
		'price'         => $price,
126
		'purchase_key'  => $purchase_key,
127
		'user_email'    => $user['user_email'],
128
		'date'          => date( 'Y-m-d H:i:s', current_time( 'timestamp' ) ),
129
		'user_info'     => stripslashes_deep( $user_info ),
130
		'post_data'     => give_clean( $_POST ),
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
131
		'gateway'       => $valid_data['gateway'],
132
		'card_info'     => $valid_data['cc_info'],
133
	);
134
135
	// Add the user data for hooks.
136
	$valid_data['user'] = $user;
137
138
	/**
139
	 * Fires before donation form gateway.
140
	 *
141
	 * Allow you to hook to donation form before the gateway.
142
	 *
143
	 * @since 1.0
144
	 *
145
	 * @param array $_POST Array of variables passed via the HTTP POST.
146
	 * @param array $user_info Array containing basic user information.
147
	 * @param bool|array $valid_data Validate fields.
148
	 */
149
	do_action( 'give_checkout_before_gateway', give_clean( $_POST ), $user_info, $valid_data );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
150
151
	// Sanity check for price.
152
	if ( ! $donation_data['price'] ) {
153
		// Revert to manual.
154
		$donation_data['gateway'] = 'manual';
155
		$_POST['give-gateway']    = 'manual';
156
	}
157
158
	/**
159
	 * Allow the donation data to be modified before it is sent to the gateway.
160
	 *
161
	 * @since 1.7
162
	 */
163
	$donation_data = apply_filters( 'give_donation_data_before_gateway', $donation_data, $valid_data );
164
165
	// Setup the data we're storing in the donation session.
166
	$session_data = $donation_data;
167
168
	// Make sure credit card numbers are never stored in sessions.
169
	unset( $session_data['card_info']['card_number'] );
170
	unset( $session_data['post_data']['card_number'] );
171
172
	// Used for showing data to non logged-in users after donation, and for other plugins needing donation data.
173
	give_set_purchase_session( $session_data );
174
175
	// Send info to the gateway for payment processing.
176
	give_send_to_gateway( $donation_data['gateway'], $donation_data );
177
	give_die();
178
}
179
180
add_action( 'give_purchase', 'give_process_donation_form' );
181
add_action( 'wp_ajax_give_process_donation', 'give_process_donation_form' );
182
add_action( 'wp_ajax_nopriv_give_process_donation', 'give_process_donation_form' );
183
184
/**
185
 * Verify that when a logged in user makes a donation that the email address used doesn't belong to a different customer.
186
 *
187
 * @since  1.7
188
 *
189
 * @param  array $valid_data Validated data submitted for the donation.
190
 *
191
 * @return void
192
 */
193
function give_check_logged_in_user_for_existing_email( $valid_data ) {
194
195
	// Verify that the email address belongs to this customer.
196
	if ( is_user_logged_in() ) {
197
198
		$submitted_email = $valid_data['logged_in_user']['user_email'];
199
		$donor           = new Give_Donor( get_current_user_id(), true );
200
201
		// If this email address is not registered with this customer, see if it belongs to any other customer.
202
		if (
203
			$submitted_email !== $donor->email
204
			&& ( is_array( $donor->emails ) && ! in_array( $submitted_email, $donor->emails ) )
205
		) {
206
			$found_donor = new Give_Donor( $submitted_email );
207
208
			if ( $found_donor->id > 0 ) {
209
				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' ), $donor->email, $submitted_email ) );
210
			}
211
		}
212
	}
213
}
214
215
add_action( 'give_checkout_error_checks', 'give_check_logged_in_user_for_existing_email', 10, 1 );
216
217
/**
218
 * Process the checkout login form
219
 *
220
 * @access      private
221
 * @since       1.0
222
 * @return      void
223
 */
224
function give_process_form_login() {
225
	$is_ajax = isset( $_POST['give_ajax'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
226
227
	$user_data = give_donation_form_validate_user_login();
228
229
	if ( give_get_errors() || $user_data['user_id'] < 1 ) {
230
		if ( $is_ajax ) {
231
			/**
232
			 * Fires when AJAX sends back errors from the donation form.
233
			 *
234
			 * @since 1.0
235
			 */
236
			ob_start();
237
			do_action( 'give_ajax_donation_errors' );
238
			$message = ob_get_contents();
239
			ob_end_clean();
240
			wp_send_json_error( $message );
241
		} else {
242
			wp_redirect( $_SERVER['HTTP_REFERER'] );
0 ignored issues
show
introduced by
Detected usage of a non-validated input variable: $_SERVER
Loading history...
243
			exit;
244
		}
245
	}
246
247
	give_log_user_in( $user_data['user_id'], $user_data['user_login'], $user_data['user_pass'] );
248
249
	if ( $is_ajax ) {
250
		$message = Give()->notices->print_frontend_notice(
251
			sprintf(
252
			/* translators: %s: user first name */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 12.
Loading history...
253
				esc_html__( 'Welcome %s! You have successfully logged into your account.', 'give' ),
254
				( ! empty( $user_data['user_first'] ) ) ? $user_data['user_first'] : $user_data['user_login']
255
			),
256
			false,
257
			'success'
258
		);
259
260
		wp_send_json_success( $message );
261
	} else {
262
		wp_redirect( $_SERVER['HTTP_REFERER'] );
0 ignored issues
show
introduced by
Detected usage of a non-validated input variable: $_SERVER
Loading history...
263
	}
264
}
265
266
add_action( 'wp_ajax_give_process_donation_login', 'give_process_form_login' );
267
add_action( 'wp_ajax_nopriv_give_process_donation_login', 'give_process_form_login' );
268
269
/**
270
 * Donation Form Validate Fields.
271
 *
272
 * @access      private
273
 * @since       1.0
274
 * @return      bool|array
275
 */
276
function give_donation_form_validate_fields() {
277
278
	// Check if there is $_POST.
279
	if ( empty( $_POST ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
280
		return false;
281
	}
282
283
	$form_id = ! empty( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
284
285
	// Start an array to collect valid data.
286
	$valid_data = array(
287
		'gateway'          => give_donation_form_validate_gateway(), // Gateway fallback (amount is validated here).
288
		'need_new_user'    => false,     // New user flag.
289
		'need_user_login'  => false,     // Login user flag.
290
		'logged_user_data' => array(),   // Logged user collected data.
291
		'new_user_data'    => array(),   // New user collected data.
292
		'login_user_data'  => array(),   // Login user collected data.
293
		'guest_user_data'  => array(),   // Guest user collected data.
294
		'cc_info'          => give_donation_form_validate_cc(),// Credit card info.
295
	);
296
297
	// Validate Honeypot First.
298
	if ( ! empty( $_POST['give-honeypot'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
299
		give_set_error( 'invalid_honeypot', esc_html__( 'Honeypot field detected. Go away bad bot!', 'give' ) );
300
	}
301
302
	// Check spam detect.
303
	if ( isset( $_POST['action'] )
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
304
	     && give_is_setting_enabled( give_get_option( 'akismet_spam_protection' ) )
305
	     && give_is_spam_donation()
306
	) {
307
		give_set_error( 'invalid_donation', __( 'This donation has been flagged as spam. Please try again.', 'give' ) );
308
	}
309
310
	// Validate agree to terms.
311
	if ( give_is_terms_enabled( $form_id ) ) {
312
		give_donation_form_validate_agree_to_terms();
313
	}
314
315
	if ( is_user_logged_in() ) {
316
		// Collect logged in user data.
317
		$valid_data['logged_in_user'] = give_donation_form_validate_logged_in_user();
318
	} elseif ( isset( $_POST['give-purchase-var'] ) && $_POST['give-purchase-var'] == 'needs-to-register' && ! empty( $_POST['give_create_account'] ) ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
319
		// Set new user registration as required.
320
		$valid_data['need_new_user'] = true;
321
		// Validate new user data.
322
		$valid_data['new_user_data'] = give_donation_form_validate_new_user();
323
		// Check if login validation is needed.
324
	} elseif ( isset( $_POST['give-purchase-var'] ) && $_POST['give-purchase-var'] == 'needs-to-login' ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
325
		// Set user login as required.
326
		$valid_data['need_user_login'] = true;
327
		// Validate users login info.
328
		$valid_data['login_user_data'] = give_donation_form_validate_user_login();
329
	} else {
330
		// Not registering or logging in, so setup guest user data.
331
		$valid_data['guest_user_data'] = give_donation_form_validate_guest_user();
332
	}
333
334
	// Return collected data.
335
	return $valid_data;
336
}
337
338
/**
339
 * Detect spam donation.
340
 *
341
 * @since 1.8.14
342
 *
343
 * @return bool|mixed
344
 */
345
function give_is_spam_donation() {
346
	$spam = false;
347
348
	$user_agent = (string) isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_SERVER
Loading history...
349
350
	if ( strlen( $user_agent ) < 2 ) {
351
		$spam = true;
352
	}
353
354
	// Allow developer to customized Akismet spam detect API call and it's response.
355
	return apply_filters( 'give_spam', $spam );
356
}
357
358
/**
359
 * Donation Form Validate Gateway
360
 *
361
 * Validate the gateway and donation amount.
362
 *
363
 * @access      private
364
 * @since       1.0
365
 * @return      string
366
 */
367
function give_donation_form_validate_gateway() {
368
369
	$form_id = isset( $_REQUEST['give-form-id'] ) ? $_REQUEST['give-form-id'] : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
370
	$amount  = isset( $_REQUEST['give-amount'] ) ? give_maybe_sanitize_amount( $_REQUEST['give-amount'] ) : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
371
	$gateway = give_get_default_gateway( $form_id );
372
373
	// Check if a gateway value is present.
374
	if ( ! empty( $_REQUEST['give-gateway'] ) ) {
375
376
		$gateway = sanitize_text_field( $_REQUEST['give-gateway'] );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
377
378
		// Is amount being donated in LIVE mode 0.00? If so, error:
379
		if ( $amount == 0 && ! give_is_test_mode() ) {
0 ignored issues
show
introduced by
Found "== 0". Use Yoda Condition checks, you must
Loading history...
380
381
			give_set_error( 'invalid_donation_amount', __( 'Please insert a valid donation amount.', 'give' ) );
382
383
		} // End if().
384 View Code Duplication
		elseif ( ! give_verify_minimum_price( 'minimum' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
385
			// translators: %s: minimum donation amount.
386
			give_set_error(
387
				'invalid_donation_minimum',
388
				sprintf(
389
				/* translators: %s: minimum donation amount */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 16.
Loading history...
390
					__( 'This form has a minimum donation amount of %s.', 'give' ),
391
					give_currency_filter( give_format_amount( give_get_form_minimum_price( $form_id ), array( 'sanitize' => false ) ) )
0 ignored issues
show
Documentation introduced by
give_get_form_minimum_price($form_id) is of type false|double, but the function expects a string.

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...
392
				)
393
			);
394
395
		} // End if().
396 View Code Duplication
		elseif ( ! give_verify_minimum_price( 'maximum' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
397
			// translators: %s: Maximum donation amount.
398
			give_set_error(
399
				'invalid_donation_maximum',
400
				sprintf(
401
				/* translators: %s: Maximum donation amount */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 16.
Loading history...
402
					__( 'This form has a maximum donation amount of %s.', 'give' ),
403
					give_currency_filter( give_format_amount( give_get_form_maximum_price( $form_id ), array( 'sanitize' => false ) ) )
0 ignored issues
show
Documentation introduced by
give_get_form_maximum_price($form_id) is of type false|double, but the function expects a string.

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...
404
				)
405
			);
406
407
		} //Is this test mode zero donation? Let it through but set to manual gateway.
408
		elseif ( $amount == 0 && give_is_test_mode() ) {
0 ignored issues
show
introduced by
Found "== 0". Use Yoda Condition checks, you must
Loading history...
409
410
			$gateway = 'manual';
411
412
		} //Check if this gateway is active.
413
		elseif ( ! give_is_gateway_active( $gateway ) ) {
414
415
			give_set_error( 'invalid_gateway', __( 'The selected payment gateway is not enabled.', 'give' ) );
416
417
		}
418
	}
419
420
	return $gateway;
421
422
}
423
424
/**
425
 * Donation Form Validate Minimum or Maximum Donation Amount
426
 *
427
 * @access      private
428
 * @since       1.3.6
429
 * @since       2.1 Added support for give maximum amount.
430
 *
431
 * @param string $amount_range Which amount needs to verify? minimum or maximum.
432
 *
433
 * @return      bool
434
 */
435
function give_verify_minimum_price( $amount_range = 'minimum' ) {
436
437
	$amount          = give_maybe_sanitize_amount( $_REQUEST['give-amount'] );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_REQUEST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
438
	$form_id         = isset( $_REQUEST['give-form-id'] ) ? $_REQUEST['give-form-id'] : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
439
	$price_id        = isset( $_REQUEST['give-price-id'] ) ? $_REQUEST['give-price-id'] : null;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
440
	$variable_prices = give_has_variable_prices( $form_id );
441
442
	if ( $variable_prices && in_array( $price_id, give_get_variable_price_ids( $form_id ) ) ) {
443
444
		$price_level_amount = give_get_price_option_amount( $form_id, $price_id );
445
446
		if ( $price_level_amount == $amount ) {
447
			return true;
448
		}
449
	}
450
451
	switch ( $amount_range ) {
452
		case 'minimum' :
453
			if ( give_get_form_minimum_price( $form_id ) > $amount ) {
454
				return false;
455
			}
456
			break;
457
		case 'maximum' :
458
			if ( give_get_form_maximum_price( $form_id ) < $amount ) {
459
				return false;
460
			}
461
			break;
462
	}
463
464
	return true;
465
}
466
467
/**
468
 * Donation form validate agree to "Terms and Conditions".
469
 *
470
 * @access      private
471
 * @since       1.0
472
 * @return      void
473
 */
474
function give_donation_form_validate_agree_to_terms() {
475
	// Validate agree to terms.
476
	if ( ! isset( $_POST['give_agree_to_terms'] ) || $_POST['give_agree_to_terms'] != 1 ) {
0 ignored issues
show
introduced by
Found "!= 1". Use Yoda Condition checks, you must
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
477
		// User did not agree.
478
		give_set_error( 'agree_to_terms', apply_filters( 'give_agree_to_terms_text', __( 'You must agree to the terms and conditions.', 'give' ) ) );
479
	}
480
}
481
482
/**
483
 * Donation Form Required Fields.
484
 *
485
 * @access      private
486
 * @since       1.0
487
 *
488
 * @param       $form_id
489
 *
490
 * @return      array
491
 */
492
function give_get_required_fields( $form_id ) {
493
494
	$payment_mode = give_get_chosen_gateway( $form_id );
495
496
	$required_fields = array(
497
		'give_email' => array(
498
			'error_id'      => 'invalid_email',
499
			'error_message' => __( 'Please enter a valid email address.', 'give' ),
500
		),
501
		'give_first' => array(
502
			'error_id'      => 'invalid_first_name',
503
			'error_message' => __( 'Please enter your first name.', 'give' ),
504
		),
505
	);
506
507
	$require_address = give_require_billing_address( $payment_mode );
508
509
	if ( $require_address ) {
510
		$required_fields['card_address']    = array(
511
			'error_id'      => 'invalid_card_address',
512
			'error_message' => __( 'Please enter your primary billing address.', 'give' ),
513
		);
514
		$required_fields['card_zip']        = array(
515
			'error_id'      => 'invalid_zip_code',
516
			'error_message' => __( 'Please enter your zip / postal code.', 'give' ),
517
		);
518
		$required_fields['card_city']       = array(
519
			'error_id'      => 'invalid_city',
520
			'error_message' => __( 'Please enter your billing city.', 'give' ),
521
		);
522
		$required_fields['billing_country'] = array(
523
			'error_id'      => 'invalid_country',
524
			'error_message' => __( 'Please select your billing country.', 'give' ),
525
		);
526
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
527
528
		$required_fields['card_state'] = array(
529
			'error_id'      => 'invalid_state',
530
			'error_message' => __( 'Please enter billing state / province / County.', 'give' ),
531
		);
532
533
		// Check if billing country already exists.
534
		if ( ! empty( $_POST['billing_country'] ) ) {
535
			// Get the value from $_POST.
536
			$country = sanitize_text_field( $_POST['billing_country'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
537
538
			// Get the country list that does not required any states init.
539
			$states_country = give_states_not_required_country_list();
540
541
			// Check if states is empty or not.
542
			if ( array_key_exists( $country, $states_country ) ) {
543
				// If states is empty remove the required feilds of state in billing cart.
544
				unset( $required_fields['card_state'] );
545
			}
546
		}
547
	}
548
549
	if ( give_is_company_field_enabled( $form_id ) ) {
550
		$form_option    = give_get_meta( $form_id, '_give_company_field', true );
551
		$global_setting = give_get_option( 'company_field' );
552
553
		$is_company_field_required = false;
554
555
		if ( ! empty( $form_option ) && give_is_setting_enabled( $form_option, array( 'required' ) ) ) {
0 ignored issues
show
Documentation introduced by
array('required') 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...
556
			$is_company_field_required = true;
557
558
		} elseif ( 'global' === $form_option && give_is_setting_enabled( $global_setting, array( 'required' ) ) ) {
0 ignored issues
show
Documentation introduced by
array('required') 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...
559
			$is_company_field_required = true;
560
561
		} elseif ( empty( $form_option ) && give_is_setting_enabled( $global_setting, array( 'required' ) ) ) {
0 ignored issues
show
Documentation introduced by
array('required') 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...
562
			$is_company_field_required = true;
563
564
		}
565
566
		if( $is_company_field_required ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
567
			$required_fields['give_company_name'] = array(
568
				'error_id'      => 'invalid_company',
569
				'error_message' => __( 'Please enter Company Name.', 'give' ),
570
			);
571
		}
572
	}
573
574
	/**
575
	 * Filters the donation form required field.
576
	 *
577
	 * @since 1.7
578
	 */
579
	$required_fields = apply_filters( 'give_donation_form_required_fields', $required_fields, $form_id );
580
581
	return $required_fields;
582
583
}
584
585
/**
586
 * Check if the Billing Address is required
587
 *
588
 * @since  1.0.1
589
 *
590
 * @param string $payment_mode
591
 *
592
 * @return bool
593
 */
594
function give_require_billing_address( $payment_mode ) {
595
596
	$return = false;
597
598
	if ( isset( $_POST['billing_country'] ) || did_action( "give_{$payment_mode}_cc_form" ) || did_action( 'give_cc_form' ) ) {
599
		$return = true;
600
	}
601
602
	// Let payment gateways and other extensions determine if address fields should be required.
603
	return apply_filters( 'give_require_billing_address', $return );
604
605
}
606
607
/**
608
 * Donation Form Validate Logged In User.
609
 *
610
 * @access      private
611
 * @since       1.0
612
 * @return      array
613
 */
614
function give_donation_form_validate_logged_in_user() {
615
	global $user_ID;
616
617
	$form_id = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
618
619
	// Start empty array to collect valid user data.
620
	$valid_user_data = array(
621
		// Assume there will be errors.
622
		'user_id' => - 1,
623
	);
624
625
	// Verify there is a user_ID.
626
	if ( $user_ID > 0 ) {
627
		// Get the logged in user data.
628
		$user_data = get_userdata( $user_ID );
629
630
		// Validate Required Form Fields.
631
		give_validate_required_form_fields( $form_id );
632
633
		// Verify data.
634
		if ( $user_data ) {
635
			// Collected logged in user data.
636
			$valid_user_data = array(
637
				'user_id'    => $user_ID,
638
				'user_email' => isset( $_POST['give_email'] ) ? sanitize_email( $_POST['give_email'] ) : $user_data->user_email,
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
639
				'user_first' => isset( $_POST['give_first'] ) && ! empty( $_POST['give_first'] ) ? sanitize_text_field( $_POST['give_first'] ) : $user_data->first_name,
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
640
				'user_last'  => isset( $_POST['give_last'] ) && ! empty( $_POST['give_last'] ) ? sanitize_text_field( $_POST['give_last'] ) : $user_data->last_name,
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
641
			);
642
643
			give_donation_form_validate_name_fields();
644
645
			if ( ! is_email( $valid_user_data['user_email'] ) ) {
646
				give_set_error( 'email_invalid', esc_html__( 'Invalid email.', 'give' ) );
647
			}
648
		} else {
649
			// Set invalid user error.
650
			give_set_error( 'invalid_user', esc_html__( 'The user information is invalid.', 'give' ) );
651
		}
652
	}
653
654
	// Return user data.
655
	return $valid_user_data;
656
}
657
658
/**
659
 * Donate Form Validate New User
660
 *
661
 * @access      private
662
 * @since       1.0
663
 * @return      array
664
 */
665
function give_donation_form_validate_new_user() {
666
667
	$auto_generated_password = wp_generate_password();
668
669
	// Default user data.
670
	$default_user_data = array(
671
		'give-form-id'           => '',
672
		'user_id'                => - 1, // Assume there will be errors.
673
		'user_first'             => '',
674
		'user_last'              => '',
675
		'give_user_login'        => false,
676
		'give_email'             => false,
677
		'give_user_pass'         => $auto_generated_password,
678
		'give_user_pass_confirm' => $auto_generated_password,
679
	);
680
681
	// Get user data.
682
	$user_data            = wp_parse_args( give_clean( $_POST ), $default_user_data );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
683
	$registering_new_user = false;
684
	$form_id              = absint( $user_data['give-form-id'] );
685
686
	give_donation_form_validate_name_fields();
687
688
	// Start an empty array to collect valid user data.
689
	$valid_user_data = array(
690
		// Assume there will be errors.
691
		'user_id'    => - 1,
692
693
		// Get first name.
694
		'user_first' => $user_data['give_first'],
695
696
		// Get last name.
697
		'user_last'  => $user_data['give_last'],
698
699
		// Get Password.
700
		'user_pass'  => $user_data['give_user_pass'],
701
	);
702
703
	// Validate Required Form Fields.
704
	give_validate_required_form_fields( $form_id );
705
706
	// Set Email as Username.
707
	$valid_user_data['user_login'] = $user_data['give_email'];
708
709
	// Check if we have an email to verify.
710
	if ( give_validate_user_email( $user_data['give_email'], $registering_new_user ) ) {
711
		$valid_user_data['user_email'] = $user_data['give_email'];
712
	}
713
714
	return $valid_user_data;
715
}
716
717
/**
718
 * Donation Form Validate User Login
719
 *
720
 * @access      private
721
 * @since       1.0
722
 * @return      array
723
 */
724
function give_donation_form_validate_user_login() {
725
726
	// Start an array to collect valid user data.
727
	$valid_user_data = array(
728
		// Assume there will be errors.
729
		'user_id' => - 1,
730
	);
731
732
	// Username.
733
	if ( ! isset( $_POST['give_user_login'] ) || $_POST['give_user_login'] == '' ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
734
		give_set_error( 'must_log_in', __( 'You must register or login to complete your donation.', 'give' ) );
735
736
		return $valid_user_data;
737
	}
738
739
	// Get the user by login.
740
	$user_data = get_user_by( 'login', strip_tags( $_POST['give_user_login'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
741
742
	// Check if user exists.
743
	if ( $user_data ) {
744
		// Get password.
745
		$user_pass = isset( $_POST['give_user_pass'] ) ? $_POST['give_user_pass'] : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
746
747
		// Check user_pass.
748
		if ( $user_pass ) {
749
			// Check if password is valid.
750
			if ( ! wp_check_password( $user_pass, $user_data->user_pass, $user_data->ID ) ) {
751
				// Incorrect password.
752
				give_set_error(
753
					'password_incorrect',
754
					sprintf(
755
						'%1$s <a href="%2$s">%3$s</a>',
756
						__( 'The password you entered is incorrect.', 'give' ),
757
						wp_lostpassword_url( "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ),
758
						__( 'Reset Password', 'give' )
759
					)
760
				);
761
				// All is correct.
762
			} else {
763
764
				// Repopulate the valid user data array.
765
				$valid_user_data = array(
766
					'user_id'    => $user_data->ID,
767
					'user_login' => $user_data->user_login,
768
					'user_email' => $user_data->user_email,
769
					'user_first' => $user_data->first_name,
770
					'user_last'  => $user_data->last_name,
771
					'user_pass'  => $user_pass,
772
				);
773
			}
774
		} else {
775
			// Empty password.
776
			give_set_error( 'password_empty', __( 'Enter a password.', 'give' ) );
777
		}
778
	} else {
779
		// No username.
780
		give_set_error( 'username_incorrect', __( 'The username you entered does not exist.', 'give' ) );
781
	}// End if().
782
783
	return $valid_user_data;
784
}
785
786
/**
787
 * Donation Form Validate Guest User
788
 *
789
 * @access  private
790
 * @since   1.0
791
 * @return  array
792
 */
793
function give_donation_form_validate_guest_user() {
794
795
	$form_id = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
796
797
	// Start an array to collect valid user data.
798
	$valid_user_data = array(
799
		// Set a default id for guests.
800
		'user_id' => 0,
801
	);
802
803
	give_donation_form_validate_name_fields();
804
805
	// Get the guest email.
806
	$guest_email = isset( $_POST['give_email'] ) ? $_POST['give_email'] : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
807
808
	// Check email.
809
	if ( $guest_email && strlen( $guest_email ) > 0 ) {
810
		// Validate email.
811
		if ( ! is_email( $guest_email ) ) {
812
			// Invalid email.
813
			give_set_error( 'email_invalid', __( 'Invalid email.', 'give' ) );
814
		} else {
815
			// All is good to go.
816
			$valid_user_data['user_email'] = $guest_email;
817
818
			// Get user_id from donor if exist.
819
			$donor = new Give_Donor( $guest_email );
820
			if ( $donor->id && $donor->user_id ) {
821
				$valid_user_data['user_id'] = $donor->user_id;
822
			}
823
		}
824
	} else {
825
		// No email.
826
		give_set_error( 'email_empty', __( 'Enter an email.', 'give' ) );
827
	}
828
829
	// Validate Required Form Fields.
830
	give_validate_required_form_fields( $form_id );
831
832
	return $valid_user_data;
833
}
834
835
/**
836
 * Register And Login New User
837
 *
838
 * @param array $user_data
839
 *
840
 * @access  private
841
 * @since   1.0
842
 * @return  integer
843
 */
844
function give_register_and_login_new_user( $user_data = array() ) {
845
	// Verify the array.
846
	if ( empty( $user_data ) ) {
847
		return - 1;
848
	}
849
850
	if ( give_get_errors() ) {
851
		return - 1;
852
	}
853
854
	$user_args = apply_filters( 'give_insert_user_args', array(
855
		'user_login'      => isset( $user_data['user_login'] ) ? $user_data['user_login'] : '',
856
		'user_pass'       => isset( $user_data['user_pass'] ) ? $user_data['user_pass'] : '',
857
		'user_email'      => isset( $user_data['user_email'] ) ? $user_data['user_email'] : '',
858
		'first_name'      => isset( $user_data['user_first'] ) ? $user_data['user_first'] : '',
859
		'last_name'       => isset( $user_data['user_last'] ) ? $user_data['user_last'] : '',
860
		'user_registered' => date( 'Y-m-d H:i:s' ),
861
		'role'            => give_get_option( 'donor_default_user_role', 'give_donor' ),
862
	), $user_data );
863
864
	// Insert new user.
865
	$user_id = wp_insert_user( $user_args );
866
867
	// Validate inserted user.
868
	if ( is_wp_error( $user_id ) ) {
869
		return - 1;
870
	}
871
872
	// Allow themes and plugins to filter the user data.
873
	$user_data = apply_filters( 'give_insert_user_data', $user_data, $user_args );
874
875
	/**
876
	 * Fires after inserting user.
877
	 *
878
	 * @since 1.0
879
	 *
880
	 * @param int $user_id User id.
881
	 * @param array $user_data Array containing user data.
882
	 */
883
	do_action( 'give_insert_user', $user_id, $user_data );
884
885
	/**
886
	 * Filter allow user to alter if user when to login or not when user is register for the first time.
887
	 *
888
	 * @since 1.8.13
889
	 *
890
	 * return bool True if login with registration and False if only want to register.
891
	 */
892
	if ( true === (bool) apply_filters( 'give_log_user_in_on_register', true ) ) {
893
		// Login new user.
894
		give_log_user_in( $user_id, $user_data['user_login'], $user_data['user_pass'] );
895
	}
896
897
	// Return user id.
898
	return $user_id;
899
}
900
901
/**
902
 * Get Donation Form User
903
 *
904
 * @param array $valid_data
905
 *
906
 * @access  private
907
 * @since   1.0
908
 * @return  array|bool
909
 */
910
function give_get_donation_form_user( $valid_data = array() ) {
911
912
	// Initialize user.
913
	$user    = false;
914
	$is_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
915
916
	if ( $is_ajax ) {
917
		// Do not create or login the user during the ajax submission (check for errors only).
918
		return true;
919
	} elseif ( is_user_logged_in() ) {
920
		// Set the valid user as the logged in collected data.
921
		$user = $valid_data['logged_in_user'];
922
	} elseif ( $valid_data['need_new_user'] === true || $valid_data['need_user_login'] === true ) {
0 ignored issues
show
introduced by
Found "=== true". Use Yoda Condition checks, you must
Loading history...
923
		// New user registration.
924
		if ( $valid_data['need_new_user'] === true ) {
0 ignored issues
show
introduced by
Found "=== true". Use Yoda Condition checks, you must
Loading history...
925
			// Set user.
926
			$user = $valid_data['new_user_data'];
927
			// Register and login new user.
928
			$user['user_id'] = give_register_and_login_new_user( $user );
929
			// User login
930
		} elseif ( $valid_data['need_user_login'] === true && ! $is_ajax ) {
0 ignored issues
show
introduced by
Found "=== true". Use Yoda Condition checks, you must
Loading history...
931
932
			/**
933
			 * The login form is now processed in the give_process_donation_login() function.
934
			 * This is still here for backwards compatibility.
935
			 * This also allows the old login process to still work if a user removes the checkout login submit button.
936
			 *
937
			 * 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.
938
			 */
939
			// Set user.
940
			$user = $valid_data['login_user_data'];
941
			// Login user.
942
			give_log_user_in( $user['user_id'], $user['user_login'], $user['user_pass'] );
943
		}
944
	}
945
946
	// Check guest checkout.
947
	if ( false === $user && false === give_logged_in_only( $_POST['give-form-id'] ) ) {
948
		// Set user
949
		$user = $valid_data['guest_user_data'];
950
	}
951
952
	// Verify we have an user.
953
	if ( false === $user || empty( $user ) ) {
954
		// Return false.
955
		return false;
956
	}
957
958
	// Get user first name.
959 View Code Duplication
	if ( ! isset( $user['user_first'] ) || strlen( trim( $user['user_first'] ) ) < 1 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
960
		$user['user_first'] = isset( $_POST['give_first'] ) ? strip_tags( trim( $_POST['give_first'] ) ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
961
	}
962
963
	// Get user last name.
964 View Code Duplication
	if ( ! isset( $user['user_last'] ) || strlen( trim( $user['user_last'] ) ) < 1 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
965
		$user['user_last'] = isset( $_POST['give_last'] ) ? strip_tags( trim( $_POST['give_last'] ) ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
966
	}
967
968
	// Get the user's billing address details.
969
	$user['address']            = array();
970
	$user['address']['line1']   = ! empty( $_POST['card_address'] ) ? give_clean( $_POST['card_address'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
971
	$user['address']['line2']   = ! empty( $_POST['card_address_2'] ) ? give_clean( $_POST['card_address_2'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
972
	$user['address']['city']    = ! empty( $_POST['card_city'] ) ? give_clean( $_POST['card_city'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
973
	$user['address']['state']   = ! empty( $_POST['card_state'] ) ? give_clean( $_POST['card_state'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
974
	$user['address']['zip']     = ! empty( $_POST['card_zip'] ) ? give_clean( $_POST['card_zip'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
975
	$user['address']['country'] = ! empty( $_POST['billing_country'] ) ? give_clean( $_POST['billing_country'] ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
976
977
	if ( empty( $user['address']['country'] ) ) {
978
		$user['address'] = false;
979
	} // End if().
980
981
	// Return valid user.
982
	return $user;
983
}
984
985
/**
986
 * Validates the credit card info.
987
 *
988
 * @access  private
989
 * @since   1.0
990
 * @return  array
991
 */
992
function give_donation_form_validate_cc() {
993
994
	$card_data = give_get_donation_cc_info();
995
996
	// Validate the card zip.
997
	if ( ! empty( $card_data['card_zip'] ) ) {
998
		if ( ! give_donation_form_validate_cc_zip( $card_data['card_zip'], $card_data['card_country'] ) ) {
999
			give_set_error( 'invalid_cc_zip', __( 'The zip / postal code you entered for your billing address is invalid.', 'give' ) );
1000
		}
1001
	}
1002
1003
	// Ensure no spaces.
1004
	if ( ! empty( $card_data['card_number'] ) ) {
1005
		$card_data['card_number'] = str_replace( '+', '', $card_data['card_number'] ); // no "+" signs
1006
		$card_data['card_number'] = str_replace( ' ', '', $card_data['card_number'] ); // No spaces
1007
	}
1008
1009
	// This should validate card numbers at some point too.
1010
	return $card_data;
1011
}
1012
1013
/**
1014
 * Get credit card info.
1015
 *
1016
 * @access  private
1017
 * @since   1.0
1018
 * @return  array
1019
 */
1020
function give_get_donation_cc_info() {
1021
1022
	$cc_info                   = array();
1023
	$cc_info['card_name']      = isset( $_POST['card_name'] ) ? sanitize_text_field( $_POST['card_name'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1024
	$cc_info['card_number']    = isset( $_POST['card_number'] ) ? sanitize_text_field( $_POST['card_number'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1025
	$cc_info['card_cvc']       = isset( $_POST['card_cvc'] ) ? sanitize_text_field( $_POST['card_cvc'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1026
	$cc_info['card_exp_month'] = isset( $_POST['card_exp_month'] ) ? sanitize_text_field( $_POST['card_exp_month'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1027
	$cc_info['card_exp_year']  = isset( $_POST['card_exp_year'] ) ? sanitize_text_field( $_POST['card_exp_year'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1028
	$cc_info['card_address']   = isset( $_POST['card_address'] ) ? sanitize_text_field( $_POST['card_address'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1029
	$cc_info['card_address_2'] = isset( $_POST['card_address_2'] ) ? sanitize_text_field( $_POST['card_address_2'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1030
	$cc_info['card_city']      = isset( $_POST['card_city'] ) ? sanitize_text_field( $_POST['card_city'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1031
	$cc_info['card_state']     = isset( $_POST['card_state'] ) ? sanitize_text_field( $_POST['card_state'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1032
	$cc_info['card_country']   = isset( $_POST['billing_country'] ) ? sanitize_text_field( $_POST['billing_country'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1033
	$cc_info['card_zip']       = isset( $_POST['card_zip'] ) ? sanitize_text_field( $_POST['card_zip'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
1034
1035
	// Return cc info.
1036
	return $cc_info;
1037
}
1038
1039
/**
1040
 * Validate zip code based on country code
1041
 *
1042
 * @since  1.0
1043
 *
1044
 * @param int $zip
1045
 * @param string $country_code
1046
 *
1047
 * @return bool|mixed
1048
 */
1049
function give_donation_form_validate_cc_zip( $zip = 0, $country_code = '' ) {
1050
	$ret = false;
1051
1052
	if ( empty( $zip ) || empty( $country_code ) ) {
1053
		return $ret;
1054
	}
1055
1056
	$country_code = strtoupper( $country_code );
1057
1058
	$zip_regex = array(
1059
		'AD' => 'AD\d{3}',
1060
		'AM' => '(37)?\d{4}',
1061
		'AR' => '^([A-Z]{1}\d{4}[A-Z]{3}|[A-Z]{1}\d{4}|\d{4})$',
1062
		'AS' => '96799',
1063
		'AT' => '\d{4}',
1064
		'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})$',
1065
		'AX' => '22\d{3}',
1066
		'AZ' => '\d{4}',
1067
		'BA' => '\d{5}',
1068
		'BB' => '(BB\d{5})?',
1069
		'BD' => '\d{4}',
1070
		'BE' => '^[1-9]{1}[0-9]{3}$',
1071
		'BG' => '\d{4}',
1072
		'BH' => '((1[0-2]|[2-9])\d{2})?',
1073
		'BM' => '[A-Z]{2}[ ]?[A-Z0-9]{2}',
1074
		'BN' => '[A-Z]{2}[ ]?\d{4}',
1075
		'BR' => '\d{5}[\-]?\d{3}',
1076
		'BY' => '\d{6}',
1077
		'CA' => '^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$',
1078
		'CC' => '6799',
1079
		'CH' => '^[1-9][0-9][0-9][0-9]$',
1080
		'CK' => '\d{4}',
1081
		'CL' => '\d{7}',
1082
		'CN' => '\d{6}',
1083
		'CR' => '\d{4,5}|\d{3}-\d{4}',
1084
		'CS' => '\d{5}',
1085
		'CV' => '\d{4}',
1086
		'CX' => '6798',
1087
		'CY' => '\d{4}',
1088
		'CZ' => '\d{3}[ ]?\d{2}',
1089
		'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',
1090
		'DK' => '^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$',
1091
		'DO' => '\d{5}',
1092
		'DZ' => '\d{5}',
1093
		'EC' => '([A-Z]\d{4}[A-Z]|(?:[A-Z]{2})?\d{6})?',
1094
		'EE' => '\d{5}',
1095
		'EG' => '\d{5}',
1096
		'ES' => '^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$',
1097
		'ET' => '\d{4}',
1098
		'FI' => '\d{5}',
1099
		'FK' => 'FIQQ 1ZZ',
1100
		'FM' => '(9694[1-4])([ \-]\d{4})?',
1101
		'FO' => '\d{3}',
1102
		'FR' => '^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$',
1103
		'GE' => '\d{4}',
1104
		'GF' => '9[78]3\d{2}',
1105
		'GL' => '39\d{2}',
1106
		'GN' => '\d{3}',
1107
		'GP' => '9[78][01]\d{2}',
1108
		'GR' => '\d{3}[ ]?\d{2}',
1109
		'GS' => 'SIQQ 1ZZ',
1110
		'GT' => '\d{5}',
1111
		'GU' => '969[123]\d([ \-]\d{4})?',
1112
		'GW' => '\d{4}',
1113
		'HM' => '\d{4}',
1114
		'HN' => '(?:\d{5})?',
1115
		'HR' => '\d{5}',
1116
		'HT' => '\d{4}',
1117
		'HU' => '\d{4}',
1118
		'ID' => '\d{5}',
1119
		'IE' => '((D|DUBLIN)?([1-9]|6[wW]|1[0-8]|2[024]))?',
1120
		'IL' => '\d{5}',
1121
		'IN' => '^[1-9][0-9][0-9][0-9][0-9][0-9]$', // india
1122
		'IO' => 'BBND 1ZZ',
1123
		'IQ' => '\d{5}',
1124
		'IS' => '\d{3}',
1125
		'IT' => '^(V-|I-)?[0-9]{5}$',
1126
		'JO' => '\d{5}',
1127
		'JP' => '\d{3}-\d{4}',
1128
		'KE' => '\d{5}',
1129
		'KG' => '\d{6}',
1130
		'KH' => '\d{5}',
1131
		'KR' => '\d{3}[\-]\d{3}',
1132
		'KW' => '\d{5}',
1133
		'KZ' => '\d{6}',
1134
		'LA' => '\d{5}',
1135
		'LB' => '(\d{4}([ ]?\d{4})?)?',
1136
		'LI' => '(948[5-9])|(949[0-7])',
1137
		'LK' => '\d{5}',
1138
		'LR' => '\d{4}',
1139
		'LS' => '\d{3}',
1140
		'LT' => '\d{5}',
1141
		'LU' => '\d{4}',
1142
		'LV' => '\d{4}',
1143
		'MA' => '\d{5}',
1144
		'MC' => '980\d{2}',
1145
		'MD' => '\d{4}',
1146
		'ME' => '8\d{4}',
1147
		'MG' => '\d{3}',
1148
		'MH' => '969[67]\d([ \-]\d{4})?',
1149
		'MK' => '\d{4}',
1150
		'MN' => '\d{6}',
1151
		'MP' => '9695[012]([ \-]\d{4})?',
1152
		'MQ' => '9[78]2\d{2}',
1153
		'MT' => '[A-Z]{3}[ ]?\d{2,4}',
1154
		'MU' => '(\d{3}[A-Z]{2}\d{3})?',
1155
		'MV' => '\d{5}',
1156
		'MX' => '\d{5}',
1157
		'MY' => '\d{5}',
1158
		'NC' => '988\d{2}',
1159
		'NE' => '\d{4}',
1160
		'NF' => '2899',
1161
		'NG' => '(\d{6})?',
1162
		'NI' => '((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?',
1163
		'NL' => '^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$',
1164
		'NO' => '\d{4}',
1165
		'NP' => '\d{5}',
1166
		'NZ' => '\d{4}',
1167
		'OM' => '(PC )?\d{3}',
1168
		'PF' => '987\d{2}',
1169
		'PG' => '\d{3}',
1170
		'PH' => '\d{4}',
1171
		'PK' => '\d{5}',
1172
		'PL' => '\d{2}-\d{3}',
1173
		'PM' => '9[78]5\d{2}',
1174
		'PN' => 'PCRN 1ZZ',
1175
		'PR' => '00[679]\d{2}([ \-]\d{4})?',
1176
		'PT' => '\d{4}([\-]\d{3})?',
1177
		'PW' => '96940',
1178
		'PY' => '\d{4}',
1179
		'RE' => '9[78]4\d{2}',
1180
		'RO' => '\d{6}',
1181
		'RS' => '\d{5}',
1182
		'RU' => '\d{6}',
1183
		'SA' => '\d{5}',
1184
		'SE' => '^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$',
1185
		'SG' => '\d{6}',
1186
		'SH' => '(ASCN|STHL) 1ZZ',
1187
		'SI' => '\d{4}',
1188
		'SJ' => '\d{4}',
1189
		'SK' => '\d{3}[ ]?\d{2}',
1190
		'SM' => '4789\d',
1191
		'SN' => '\d{5}',
1192
		'SO' => '\d{5}',
1193
		'SZ' => '[HLMS]\d{3}',
1194
		'TC' => 'TKCA 1ZZ',
1195
		'TH' => '\d{5}',
1196
		'TJ' => '\d{6}',
1197
		'TM' => '\d{6}',
1198
		'TN' => '\d{4}',
1199
		'TR' => '\d{5}',
1200
		'TW' => '\d{3}(\d{2})?',
1201
		'UA' => '\d{5}',
1202
		'UK' => '^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$',
1203
		'US' => '^\d{5}([\-]?\d{4})?$',
1204
		'UY' => '\d{5}',
1205
		'UZ' => '\d{6}',
1206
		'VA' => '00120',
1207
		'VE' => '\d{4}',
1208
		'VI' => '008(([0-4]\d)|(5[01]))([ \-]\d{4})?',
1209
		'WF' => '986\d{2}',
1210
		'YT' => '976\d{2}',
1211
		'YU' => '\d{5}',
1212
		'ZA' => '\d{4}',
1213
		'ZM' => '\d{5}',
1214
	);
1215
1216
	if ( ! isset( $zip_regex[ $country_code ] ) || preg_match( '/' . $zip_regex[ $country_code ] . '/i', $zip ) ) {
1217
		$ret = true;
1218
	}
1219
1220
	return apply_filters( 'give_is_zip_valid', $ret, $zip, $country_code );
1221
}
1222
1223
/**
1224
 * Validate donation amount and auto set correct donation level id on basis of amount.
1225
 *
1226
 * 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.
1227
 *
1228
 * @param array $valid_data List of Valid Data.
1229
 *
1230
 * @return bool
1231
 */
1232
function give_validate_donation_amount( $valid_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...
1233
	$data = $_POST;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
1234
1235
	/* @var Give_Donate_Form $form */
1236
	$form = new Give_Donate_Form( $data['give-form-id'] );
1237
1238
	$donation_level_matched = false;
1239
1240
	if ( $form->is_set_type_donation_form() ) {
1241
		// Sanitize donation amount.
1242
		$data['give-amount'] = give_maybe_sanitize_amount( $data['give-amount'] );
1243
1244
		// Backward compatibility.
1245
		if ( $form->is_custom_price( $data['give-amount'] ) ) {
1246
			$_POST['give-price-id'] = 'custom';
1247
		}
1248
1249
		$donation_level_matched = true;
1250
1251
	} elseif ( $form->is_multi_type_donation_form() ) {
1252
1253
		// Bailout.
1254
		if ( ! ( $variable_prices = $form->get_prices() ) ) {
1255
			return false;
1256
		}
1257
1258
		// Sanitize donation amount.
1259
		$data['give-amount'] = give_maybe_sanitize_amount( $data['give-amount'] );
1260
1261
		if ( $data['give-amount'] === give_maybe_sanitize_amount( give_get_price_option_amount( $data['give-form-id'], $data['give-price-id'] ) ) ) {
1262
			return true;
1263
		}
1264
1265
		if ( $form->is_custom_price( $data['give-amount'] ) ) {
1266
			$_POST['give-price-id'] = 'custom';
1267
		} else {
1268
			// Find correct donation level from all donation levels.
1269
			foreach ( $variable_prices as $variable_price ) {
1270
				// Sanitize level amount.
1271
				$variable_price['_give_amount'] = give_maybe_sanitize_amount( $variable_price['_give_amount'] );
1272
1273
				// Set first match donation level ID.
1274
				if ( $data['give-amount'] === $variable_price['_give_amount'] ) {
1275
					$_POST['give-price-id'] = $variable_price['_give_id']['level_id'];
1276
					break;
1277
				}
1278
			}
1279
		}
1280
1281
		// If donation amount is not find in donation levels then check if form has custom donation feature enable or not.
1282
		// If yes then set price id to custom if amount is greater then custom minimum amount (if any).
1283
		if ( ! empty( $_POST['give-price-id'] ) ) {
1284
			$donation_level_matched = true;
1285
		}
1286
	}// End if().
1287
1288
	return ( $donation_level_matched ? true : false );
1289
}
1290
1291
add_action( 'give_checkout_error_checks', 'give_validate_donation_amount', 10, 1 );
1292
1293
/**
1294
 * Validate Required Form Fields.
1295
 *
1296
 * @param int $form_id Form ID.
1297
 *
1298
 * @since 2.0
1299
 */
1300
function give_validate_required_form_fields( $form_id ) {
1301
1302
	// Loop through required fields and show error messages.
1303
	foreach ( give_get_required_fields( $form_id ) as $field_name => $value ) {
1304
1305
		// Clean Up Data of the input fields.
1306
		$field_value = give_clean( $_POST[ $field_name ] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
1307
1308
		// Check whether the required field is empty, then show the error message.
1309
		if ( in_array( $value, give_get_required_fields( $form_id ) ) && empty( $field_value ) ) {
1310
			give_set_error( $value['error_id'], $value['error_message'] );
1311
		}
1312
	}
1313
}
1314
1315
/**
1316
 * Validates and checks if name fields don't contain email addresses.
1317
 *
1318
 * @since 2.1
1319
 * @return void
1320
 */
1321
function give_donation_form_validate_name_fields() {
1322
	$is_first_name = is_email( $_POST['give_first'] ) ? true : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
1323
	$is_last_name  = is_email( $_POST['give_last'] ) ? true : false;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
1324
1325
	if ( $is_first_name || $is_last_name ) {
1326
		give_set_error( 'invalid_name', esc_html__( '<First Name | Last Name> cannot contain email address.', 'give' ) );
1327
	}
1328
}