Test Failed
Push — issues/370 ( 51cc5e...d56982 )
by Ravinder
05:20
created

user-functions.php ➔ give_get_donor_address()   C

Complexity

Conditions 9
Paths 20

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 31
nc 20
nop 2
dl 0
loc 51
rs 6.2727
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
2
/**
3
 * User Functions
4
 *
5
 * Functions related to users / donors
6
 *
7
 * @package     Give
8
 * @subpackage  Functions
9
 * @copyright   Copyright (c) 2016, WordImpress
10
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
11
 * @since       1.0
12
 */
13
14
// Exit if accessed directly.
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
18
19
/**
20
 * Get Users Donations
21
 *
22
 * Retrieves a list of all donations by a specific user.
23
 *
24
 * @since  1.0
25
 *
26
 * @param int    $user   User ID or email address.
27
 * @param int    $number Number of donations to retrieve.
28
 * @param bool   $pagination
29
 * @param string $status
30
 *
31
 * @return bool|array List of all user donations.
32
 */
33
function give_get_users_donations( $user = 0, $number = 20, $pagination = false, $status = 'complete' ) {
34
35
	if ( empty( $user ) ) {
36
		$user = get_current_user_id();
37
	}
38
39
	if ( 0 === $user && ! Give()->email_access->token_exists ) {
40
		return false;
41
	}
42
43
	$status = ( 'complete' === $status ) ? 'publish' : $status;
44
	$paged = 1;
45
46
	if ( $pagination ) {
47
		if ( get_query_var( 'paged' ) ) {
48
			$paged = get_query_var( 'paged' );
49
		} elseif ( get_query_var( 'page' ) ) {
50
			$paged = get_query_var( 'page' );
51
		}
52
	}
53
54
	$args = apply_filters( 'give_get_users_donations_args', array(
55
		'user'    => $user,
56
		'number'  => $number,
57
		'status'  => $status,
58
		'orderby' => 'date',
59
	) );
60
61
	if ( $pagination ) {
62
		$args['page'] = $paged;
63
	} else {
64
		$args['nopaging'] = true;
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
65
	}
66
67
	$by_user_id = is_numeric( $user ) ? true : false;
68
	$donor   = new Give_Donor( $user, $by_user_id );
69
70
	if ( ! empty( $donor->payment_ids ) ) {
71
72
		unset( $args['user'] );
73
		$args['post__in'] = array_map( 'absint', explode( ',', $donor->payment_ids ) );
74
75
	}
76
77
	$donations = give_get_payments( apply_filters( 'give_get_users_donations_args', $args ) );
78
79
	// No donations.
80
	if ( ! $donations ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $donations of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
81
		return false;
82
	}
83
84
	return $donations;
85
}
86
87
/**
88
 * Get Users Donations
89
 *
90
 * Returns a list of unique donation forms given to by a specific user.
91
 *
92
 * @since  1.0
93
 *
94
 * @param int    $user User ID or email address
95
 * @param string $status
96
 *
97
 * @return bool|object List of unique forms donated by user
98
 */
99
function give_get_users_completed_donations( $user = 0, $status = 'complete' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $status 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...
100
	if ( empty( $user ) ) {
101
		$user = get_current_user_id();
102
	}
103
104
	if ( empty( $user ) ) {
105
		return false;
106
	}
107
108
	$by_user_id = is_numeric( $user ) ? true : false;
109
110
	$donor = new Give_Donor( $user, $by_user_id );
111
112
	if ( empty( $donor->payment_ids ) ) {
113
		return false;
114
	}
115
116
	// Get all the items donated.
117
	$payment_ids    = array_reverse( explode( ',', $donor->payment_ids ) );
118
	$limit_payments = apply_filters( 'give_users_completed_donations_payments', 50 );
119
	if ( ! empty( $limit_payments ) ) {
120
		$payment_ids = array_slice( $payment_ids, 0, $limit_payments );
121
	}
122
	$donation_data = array();
123
	foreach ( $payment_ids as $payment_id ) {
124
		$donation_data[] = give_get_payment_meta( $payment_id );
125
	}
126
127
	if ( empty( $donation_data ) ) {
128
		return false;
129
	}
130
131
	// Grab only the post ids "form_id" of the forms donated on this order.
132
	$completed_donations_ids = array();
133
	foreach ( $donation_data as $donation_meta ) {
134
		$completed_donations_ids[] = isset( $donation_meta['form_id'] ) ? $donation_meta['form_id'] : '';
135
	}
136
137
	if ( empty( $completed_donations_ids ) ) {
138
		return false;
139
	}
140
141
	// Only include each donation once.
142
	$form_ids = array_unique( $completed_donations_ids );
143
144
	// Make sure we still have some products and a first item.
145
	if ( empty( $form_ids ) || ! isset( $form_ids[0] ) ) {
146
		return false;
147
	}
148
149
	$post_type = get_post_type( $form_ids[0] );
150
151
	$args = apply_filters( 'give_get_users_completed_donations_args', array(
152
		'include'        => $form_ids,
153
		'post_type'      => $post_type,
154
		'posts_per_page' => - 1,
155
	) );
156
157
	return apply_filters( 'give_users_completed_donations_list', get_posts( $args ) );
158
}
159
160
161
/**
162
 * Has donations
163
 *
164
 * Checks to see if a user has donated to at least one form.
165
 *
166
 * @access      public
167
 * @since       1.0
168
 *
169
 * @param       int $user_id The ID of the user to check.
170
 *
171
 * @return      bool True if has donated, false other wise.
172
 */
173
function give_has_donations( $user_id = null ) {
174
	if ( empty( $user_id ) ) {
175
		$user_id = get_current_user_id();
176
	}
177
178
	if ( give_get_users_donations( $user_id, 1 ) ) {
179
		return true; // User has at least one donation.
180
	}
181
182
	// User has never donated anything.
183
	return false;
184
}
185
186
187
/**
188
 * Get Donation Status for User.
189
 *
190
 * Retrieves the donation count and the total amount spent for a specific user.
191
 *
192
 * @access      public
193
 * @since       1.0
194
 *
195
 * @param       int|string $user The ID or email of the donor to retrieve stats for.
196
 *
197
 * @return      array
198
 */
199
function give_get_donation_stats_by_user( $user = '' ) {
200
201
	$field = '';
202
203
	if ( is_email( $user ) ) {
204
		$field = 'email';
205
	} elseif ( is_numeric( $user ) ) {
206
		$field = 'user_id';
207
	}
208
209
	$stats    = array();
210
	$donor = Give()->donors->get_donor_by( $field, $user );
211
212
	if ( $donor ) {
213
		$donor = new Give_Donor( $donor->id );
214
		$stats['purchases']   = absint( $donor->purchase_count );
215
		$stats['total_spent'] = give_maybe_sanitize_amount( $donor->purchase_value );
216
	}
217
218
	/**
219
	 * Filter the donation stats.
220
	 *
221
	 * @since 1.7
222
	 */
223
	$stats = (array) apply_filters( 'give_donation_stats_by_user', $stats, $user );
224
225
	return $stats;
226
}
227
228
229
/**
230
 * Count number of donations of a donor.
231
 *
232
 * Returns total number of donations a donor has made.
233
 *
234
 * @access      public
235
 * @since       1.0
236
 *
237
 * @param       int|string $user The ID or email of the donor.
238
 *
239
 * @return      int The total number of donations.
240
 */
241
function give_count_donations_of_donor( $user = null ) {
242
243
	// Logged in?
244
	if ( empty( $user ) ) {
245
		$user = get_current_user_id();
246
	}
247
248
	// Email access?
249
	if ( empty( $user ) && Give()->email_access->token_email ) {
250
		$user = Give()->email_access->token_email;
251
	}
252
253
	$stats = ! empty( $user ) ? give_get_donation_stats_by_user( $user ) : false;
254
255
	return isset( $stats['purchases'] ) ? $stats['purchases'] : 0;
256
}
257
258
/**
259
 * Calculates the total amount spent by a user.
260
 *
261
 * @access      public
262
 * @since       1.0
263
 *
264
 * @param       int|string $user The ID or email of the donor.
265
 *
266
 * @return      float The total amount the user has spent
267
 */
268
function give_donation_total_of_user( $user = null ) {
269
270
	$stats = give_get_donation_stats_by_user( $user );
271
272
	return $stats['total_spent'];
273
}
274
275
276
/**
277
 * Validate a potential username.
278
 *
279
 * @since 1.0
280
 *
281
 * @param string $username The username to validate.
282
 * @param int    $form_id
283
 *
284
 * @return bool
285
 */
286
function give_validate_username( $username, $form_id = 0 ) {
287
	$valid = true;
288
289
	// Validate username.
290
	if ( ! empty( $username ) ) {
291
292
		// Sanitize username.
293
		$sanitized_user_name = sanitize_user( $username, false );
294
295
		// We have an user name, check if it already exists.
296
		if ( username_exists( $username ) ) {
297
			// Username already registered.
298
			give_set_error( 'username_unavailable', __( 'Username already taken.', 'give' ) );
299
			$valid = false;
300
301
			// Check if it's valid.
302
		} elseif ( $sanitized_user_name !== $username ) {
303
			// Invalid username.
304
			if ( is_multisite() ) {
305
				give_set_error( 'username_invalid', __( 'Invalid username. Only lowercase letters (a-z) and numbers are allowed.', 'give' ) );
306
				$valid = false;
307
			} else {
308
				give_set_error( 'username_invalid', __( 'Invalid username.', 'give' ) );
309
				$valid = false;
310
			}
311
		}
312
	} else {
313
		// Username is empty.
314
		give_set_error( 'username_empty', __( 'Enter a username.', 'give' ) );
315
		$valid = false;
316
317
		// Check if guest checkout is disable for form.
318
		if ( $form_id && give_logged_in_only( $form_id ) ) {
319
			give_set_error( 'registration_required', __( 'You must register or login to complete your donation.', 'give' ) );
320
			$valid = false;
321
		}
322
	}
323
324
	/**
325
	 * Filter the username validation result.
326
	 *
327
	 * @since 1.8
328
	 *
329
	 * @param bool   $valid
330
	 * @param string $username
331
	 * @param bool   $form_id
332
	 */
333
	$valid = (bool) apply_filters( 'give_validate_username', $valid, $username, $form_id );
334
335
	return $valid;
336
}
337
338
339
/**
340
 * Validate user email.
341
 *
342
 * @since 1.8
343
 *
344
 * @param string $email                User email.
345
 * @param bool   $registering_new_user Flag to check user register or not.
346
 *
347
 * @return bool
348
 */
349
function give_validate_user_email( $email, $registering_new_user = false ) {
350
	$valid = true;
351
352
	if ( empty( $email ) ) {
353
		// No email.
354
		give_set_error( 'email_empty', __( 'Enter an email.', 'give' ) );
355
		$valid = false;
356
357
	} elseif ( email_exists( $email ) ) {
358
		// Email already exists.
359
		give_set_error( 'email_exists', __( 'Email already exists.', 'give' ) );
360
		$valid = false;
361
362
	} elseif ( ! is_email( $email ) ) {
363
		// Validate email.
364
		give_set_error( 'email_invalid', __( 'Invalid email.', 'give' ) );
365
		$valid = false;
366
367
	} elseif ( $registering_new_user ) {
368
369
		// If donor email is not primary
370
		if ( ! email_exists( $email ) && give_donor_email_exists( $email ) && give_is_additional_email( $email ) ) {
371
			// Check if email exists.
372
			give_set_error( 'email_used', __( 'The email address provided is already active for another user.', 'give' ) );
373
			$valid = false;
374
		}
375
	}
376
377
	/**
378
	 * Filter the email validation result.
379
	 *
380
	 * @since 1.8
381
	 *
382
	 * @param bool   $valid
383
	 * @param string $email
384
	 * @param bool   $registering_new_user
385
	 */
386
	$valid = (bool) apply_filters( 'give_validate_user_email', $valid, $email, $registering_new_user );
387
388
	return $valid;
389
}
390
391
/**
392
 * Validate password.
393
 *
394
 * @since 1.8
395
 *
396
 * @param string $password
397
 * @param string $confirm_password
398
 * @param bool   $registering_new_user
399
 *
400
 * @return bool
401
 */
402
function give_validate_user_password( $password = '', $confirm_password = '', $registering_new_user = false ) {
403
	$valid = true;
404
405
	// Passwords Validation For New Donors Only.
406
	if ( $registering_new_user ) {
407
		// Password or confirmation missing.
408
		if ( ! $password ) {
409
			// The password is invalid.
410
			give_set_error( 'password_empty', __( 'Enter a password.', 'give' ) );
411
			$valid = false;
412
		} elseif ( ! $confirm_password ) {
413
			// Confirmation password is invalid.
414
			give_set_error( 'confirmation_empty', __( 'Enter the password confirmation.', 'give' ) );
415
			$valid = false;
416
		}
417
	}
418
	// Passwords Validation For New Donors as well as Existing Donors.
419
	if ( $password || $confirm_password ) {
420
		if ( strlen( $password ) < 6 || strlen( $confirm_password ) < 6 ) {
421
			// Seems Weak Password
422
			give_set_error( 'password_weak', __( 'Passwords should have at least 6 characters.', 'give' ) );
423
			$valid = false;
424
		}
425
		if ( $password && $confirm_password ) {
426
			// Verify confirmation matches.
427
			if ( $password !== $confirm_password ) {
428
				// Passwords do not match.
429
				give_set_error( 'password_mismatch', __( 'Passwords you entered do not match. Please try again.', 'give' ) );
430
				$valid = false;
431
			}
432
		}
433
	}
434
435
	/**
436
	 * Filter the password validation result.
437
	 *
438
	 * @since 1.8
439
	 *
440
	 * @param bool   $valid
441
	 * @param string $password
442
	 * @param string $confirm_password
443
	 * @param bool   $registering_new_user
444
	 */
445
	$valid = (bool) apply_filters( 'give_validate_user_email', $valid, $password, $confirm_password, $registering_new_user );
446
447
	return $valid;
448
}
449
450
/**
451
 * Counts the total number of donors.
452
 *
453
 * @access        public
454
 * @since         1.0
455
 *
456
 * @return        int The total number of donors.
457
 */
458
function give_count_total_donors() {
459
	return Give()->donors->count();
460
}
461
462
463
/**
464
 * Returns the saved address for a donor
465
 *
466
 * @access public
467
 * @since  1.0
468
 *
469
 * @param  int   $donor_id Donor ID
470
 * @param  array $args
471
 *
472
 * @return array The donor's address, if any
473
 */
474
function give_get_donor_address( $donor_id = null, $args = array() ) {
475
	if ( empty( $donor_id ) ) {
476
		$donor_id = get_current_user_id();
477
	}
478
479
	$address = array();
480
	$args = wp_parse_args(
481
		$args,
482
		array(
483
			'address_type' => 'billing'
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
484
		)
485
	);
486
	$default_address = array(
487
		'line1'   => '',
488
		'line2'   => '',
489
		'city'    => '',
490
		'state'   => '',
491
		'country' => '',
492
		'zip'     => '',
493
	);
494
495
	// Backward compatibility for user id param.
496
	$by_user_id = get_user_by( 'id', $donor_id ) ? true : false;
497
498
	// Backward compatibility.
499
	if( ! give_has_upgrade_completed( 'v20_upgrades_user_address' ) && $by_user_id ){
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...
500
		return wp_parse_args(
501
			(array) get_user_meta( $donor_id, '_give_user_address', true ),
0 ignored issues
show
introduced by
get_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
502
			$default_address
503
		);
504
	}
505
506
	$donor = new Give_Donor( $donor_id, $by_user_id );
507
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
508
509
	if ( ! $donor->id || ! array_key_exists( 'billing', $donor->address ) ) {
510
		return $default_address;
511
	}
512
513
	switch ( true ){
514
		case is_string( end( $donor->address[ $args['address_type'] ] ) ) :
515
			$address = wp_parse_args( $donor->address[ $args['address_type'] ], $default_address );
516
			break;
517
518
		case is_array( end( $donor->address[ $args['address_type'] ] ) ) :
519
			$address = wp_parse_args( array_shift( $donor->address[ $args['address_type'] ] ), $default_address );
520
			break;
521
	}
522
523
	return $address;
524
}
525
526
/**
527
 * Give New User Notification
528
 *
529
 * Sends the new user notification email when a user registers within the donation form
530
 *
531
 * @access        public
532
 * @since         1.0
533
 *
534
 * @param int   $user_id
535
 * @param array $user_data
536
 *
537
 * @return        void
538
 */
539
function give_new_user_notification( $user_id = 0, $user_data = array() ) {
540
	// Bailout.
541
	if ( empty( $user_id ) || empty( $user_data ) ) {
542
		return;
543
	}
544
545
	do_action( 'give_new-donor-register_email_notification', $user_id, $user_data );
546
	do_action( 'give_donor-register_email_notification', $user_id, $user_data );
547
}
548
549
add_action( 'give_insert_user', 'give_new_user_notification', 10, 2 );
550
551
552
/**
553
 * Get Donor Name By
554
 *
555
 * Retrieves the donor name based on the id and the name of the user or donation
556
 *
557
 * @access      public
558
 * @since       1.8.9
559
 *
560
 * @param       int    $id     The ID of donation or donor
561
 * @param       string $from   From will be a string to be passed as donation or donor
562
 *
563
 * @return      string
564
 */
565
function give_get_donor_name_by( $id = 0, $from = 'donation' ) {
566
567
	// ID shouldn't be empty.
568
	if ( empty( $id ) ) {
569
		return;
570
	}
571
572
	$name = '';
573
574
	switch ( $from ) {
575
576
		case 'donation':
577
578
			$user_info = give_get_payment_meta_user_info( $id );
579
			$name = $user_info['first_name'] . ' ' . $user_info['last_name'];
580
581
		break;
582
583
		case 'donor':
584
585
			$donor = new Give_Donor( $id );
0 ignored issues
show
Documentation introduced by
$id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
586
			$name = $donor->name;
587
588
		break;
589
590
	}
591
592
	return trim( $name );
593
594
}
595
596
/**
597
 * Checks whether the given donor email exists in users as well as additional_email of donors.
598
 *
599
 * @since 1.8.9
600
 *
601
 * @param  string   $email Donor Email.
602
 * @return boolean  The user's ID on success, and false on failure.
603
 */
604
function give_donor_email_exists( $email ) {
605
	if ( Give()->donors->get_donor_by( 'email', $email ) ) {
606
		return true;
607
	}
608
	return false;
609
}
610
611
/**
612
 * This function will check whether the donor email is primary or additional.
613
 *
614
 * @param string $email Donor Email.
615
 *
616
 * @since 1.8.13
617
 *
618
 * @return bool
619
 */
620
function give_is_additional_email( $email ) {
621
	global $wpdb;
622
	
623
	$meta_table = Give()->donor_meta->table_name;
624
	$meta_type  = Give()->donor_meta->meta_type;
625
	$donor_id   = $wpdb->get_var( $wpdb->prepare( "SELECT {$meta_type}_id FROM {$meta_table} WHERE meta_key = 'additional_email' AND meta_value = %s LIMIT 1", $email ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
626
627
	if ( empty( $donor_id ) ) {
628
		return false;
629
	}
630
631
	return true;
632
}