Test Failed
Push — issues/2397 ( 942cc4...f0e197 )
by Ravinder
05:30
created

functions.php ➔ give_count_payments()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 8
nop 1
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * Payment Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Payments
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
 * Get Payments
19
 *
20
 * Retrieve payments from the database.
21
 *
22
 * Since 1.0, this function takes an array of arguments, instead of individual
23
 * parameters. All of the original parameters remain, but can be passed in any
24
 * order via the array.
25
 *
26
 * @since 1.0
27
 *
28
 * @param array $args     {
29
 *                        Optional. Array of arguments passed to payments query.
30
 *
31
 * @type int    $offset   The number of payments to offset before retrieval.
32
 *                            Default is 0.
33
 * @type int    $number   The number of payments to query for. Use -1 to request all
34
 *                            payments. Default is 20.
35
 * @type string $mode     Default is 'live'.
36
 * @type string $order    Designates ascending or descending order of payments.
37
 *                            Accepts 'ASC', 'DESC'. Default is 'DESC'.
38
 * @type string $orderby  Sort retrieved payments by parameter. Default is 'ID'.
39
 * @type string $status   The status of the payments. Default is 'any'.
40
 * @type string $user     User. Default is null.
41
 * @type string $meta_key Custom field key. Default is null.
42
 * }
43
 *
44
 * @return array $payments Payments retrieved from the database
45
 */
46
function give_get_payments( $args = array() ) {
47
48
	// Fallback to post objects to ensure backwards compatibility.
49
	if ( ! isset( $args['output'] ) ) {
50
		$args['output'] = 'posts';
51
	}
52
53
	$args     = apply_filters( 'give_get_payments_args', $args );
54
	$payments = new Give_Payments_Query( $args );
55
56
	return $payments->get_payments();
57
}
58
59
/**
60
 * Retrieve payment by a given field
61
 *
62
 * @since  1.0
63
 *
64
 * @param  string $field The field to retrieve the payment with.
65
 * @param  mixed  $value The value for $field.
66
 *
67
 * @return mixed
68
 */
69
function give_get_payment_by( $field = '', $value = '' ) {
70
71
	if ( empty( $field ) || empty( $value ) ) {
72
		return false;
73
	}
74
75
	switch ( strtolower( $field ) ) {
76
77
		case 'id':
78
			$payment = new Give_Payment( $value );
79
			$id      = $payment->ID;
80
81
			if ( empty( $id ) ) {
82
				return false;
83
			}
84
85
			break;
86
87 View Code Duplication
		case 'key':
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...
88
			$payment = give_get_payments( array(
89
				'meta_key'       => '_give_payment_purchase_key',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
90
				'meta_value'     => $value,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
91
				'posts_per_page' => 1,
92
				'fields'         => 'ids',
93
			) );
94
95
			if ( $payment ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment 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...
96
				$payment = new Give_Payment( $payment[0] );
97
			}
98
99
			break;
100
101 View Code Duplication
		case 'payment_number':
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...
102
			$payment = give_get_payments( array(
103
				'meta_key'       => '_give_payment_number',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
104
				'meta_value'     => $value,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
105
				'posts_per_page' => 1,
106
				'fields'         => 'ids',
107
			) );
108
109
			if ( $payment ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment 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...
110
				$payment = new Give_Payment( $payment[0] );
111
			}
112
113
			break;
114
115
		default:
116
			return false;
117
	}// End switch().
118
119
	if ( $payment ) {
120
		return $payment;
121
	}
122
123
	return false;
124
}
125
126
/**
127
 * Insert Payment
128
 *
129
 * @since  1.0
130
 *
131
 * @param  array $payment_data Arguments passed.
132
 *
133
 * @return int|bool Payment ID if payment is inserted, false otherwise.
134
 */
135
function give_insert_payment( $payment_data = array() ) {
136
137
	if ( empty( $payment_data ) ) {
138
		return false;
139
	}
140
141
	/**
142
	 * Fire the filter on donation data before insert.
143
	 *
144
	 * @since 1.8.15
145
	 *
146
	 * @param array $payment_data Arguments passed.
147
	 */
148
	$payment_data = apply_filters( 'give_pre_insert_payment', $payment_data );
149
150
	$payment    = new Give_Payment();
151
	$gateway    = ! empty( $payment_data['gateway'] ) ? $payment_data['gateway'] : '';
152
	$gateway    = empty( $gateway ) && isset( $_POST['give-gateway'] ) ? $_POST['give-gateway'] : $gateway;
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...
153
	$form_id    = isset( $payment_data['give_form_id'] ) ? $payment_data['give_form_id'] : 0;
154
	$price_id   = give_get_payment_meta_price_id( $payment_data );
155
	$form_title = isset( $payment_data['give_form_title'] ) ? $payment_data['give_form_title'] : get_the_title( $form_id );
156
157
	// Set properties.
158
	$payment->total          = $payment_data['price'];
159
	$payment->status         = ! empty( $payment_data['status'] ) ? $payment_data['status'] : 'pending';
160
	$payment->currency       = ! empty( $payment_data['currency'] ) ? $payment_data['currency'] : give_get_currency( $payment_data['give_form_id'], $payment_data );
161
	$payment->user_info      = $payment_data['user_info'];
162
	$payment->gateway        = $gateway;
163
	$payment->form_title     = $form_title;
164
	$payment->form_id        = $form_id;
165
	$payment->price_id       = $price_id;
166
	$payment->donor_id       = ( ! empty( $payment_data['donor_id'] ) ? $payment_data['donor_id'] : '' );
167
	$payment->user_id        = $payment_data['user_info']['id'];
168
	$payment->email          = $payment_data['user_email'];
169
	$payment->first_name     = $payment_data['user_info']['first_name'];
170
	$payment->last_name      = $payment_data['user_info']['last_name'];
171
	$payment->email          = $payment_data['user_info']['email'];
172
	$payment->ip             = give_get_ip();
0 ignored issues
show
Documentation Bug introduced by
It seems like give_get_ip() can also be of type array. However, the property $ip is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
173
	$payment->key            = $payment_data['purchase_key'];
174
	$payment->mode           = ( ! empty( $payment_data['mode'] ) ? (string) $payment_data['mode'] : ( give_is_test_mode() ? 'test' : 'live' ) );
175
	$payment->parent_payment = ! empty( $payment_data['parent'] ) ? absint( $payment_data['parent'] ) : '';
176
177
	// Add the donation.
178
	$args = array(
179
		'price'    => $payment->total,
180
		'price_id' => $payment->price_id,
181
	);
182
183
	$payment->add_donation( $payment->form_id, $args );
184
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
185
186
	// Set date if present.
187
	if ( isset( $payment_data['post_date'] ) ) {
188
		$payment->date = $payment_data['post_date'];
189
	}
190
191
	// Handle sequential payments.
192
	if ( give_get_option( 'enable_sequential' ) ) {
193
		$number          = give_get_next_payment_number();
194
		$payment->number = give_format_payment_number( $number );
195
		update_option( 'give_last_payment_number', $number );
196
	}
197
198
	// Save payment.
199
	$payment->save();
200
201
	/**
202
	 * Fires while inserting payments.
203
	 *
204
	 * @since 1.0
205
	 *
206
	 * @param int   $payment_id   The payment ID.
207
	 * @param array $payment_data Arguments passed.
208
	 */
209
	do_action( 'give_insert_payment', $payment->ID, $payment_data );
210
211
	// Return payment ID upon success.
212
	if ( ! empty( $payment->ID ) ) {
213
		return $payment->ID;
214
	}
215
216
	// Return false if no payment was inserted.
217
	return false;
218
219
}
220
221
/**
222
 * Create payment.
223
 *
224
 * @param $payment_data
225
 *
226
 * @return bool|int
227
 */
228
function give_create_payment( $payment_data ) {
229
230
	$form_id  = intval( $payment_data['post_data']['give-form-id'] );
231
	$price_id = isset( $payment_data['post_data']['give-price-id'] ) ? $payment_data['post_data']['give-price-id'] : '';
232
233
	// Collect payment data.
234
	$insert_payment_data = array(
235
		'price'           => $payment_data['price'],
236
		'give_form_title' => $payment_data['post_data']['give-form-title'],
237
		'give_form_id'    => $form_id,
238
		'give_price_id'   => $price_id,
239
		'date'            => $payment_data['date'],
240
		'user_email'      => $payment_data['user_email'],
241
		'purchase_key'    => $payment_data['purchase_key'],
242
		'currency'        => give_get_currency( $form_id, $payment_data ),
243
		'user_info'       => $payment_data['user_info'],
244
		'status'          => 'pending',
245
		'gateway'         => 'paypal',
246
	);
247
248
	/**
249
	 * Filter the payment params.
250
	 *
251
	 * @since 1.8
252
	 *
253
	 * @param array $insert_payment_data
254
	 */
255
	$insert_payment_data = apply_filters( 'give_create_payment', $insert_payment_data );
256
257
	// Record the pending payment.
258
	return give_insert_payment( $insert_payment_data );
259
}
260
261
/**
262
 * Updates a payment status.
263
 *
264
 * @param  int    $payment_id Payment ID.
265
 * @param  string $new_status New Payment Status. Default is 'publish'.
266
 *
267
 * @since  1.0
268
 *
269
 * @return bool
270
 */
271
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
272
273
	$updated = false;
274
	$payment = new Give_Payment( $payment_id );
275
276
	if ( $payment && $payment->ID > 0 ) {
277
278
		$payment->status = $new_status;
279
		$updated         = $payment->save();
280
281
	}
282
283
	return $updated;
284
}
285
286
287
/**
288
 * Deletes a Donation
289
 *
290
 * @param  int  $payment_id   Payment ID (default: 0).
291
 * @param  bool $update_donor If we should update the donor stats (default:true).
292
 *
293
 * @since  1.0
294
 * @global      $give_logs
295
 *
296
 * @return void
297
 */
298
function give_delete_donation( $payment_id = 0, $update_donor = true ) {
299
300
	global $give_logs;
301
302
	$payment  = new Give_Payment( $payment_id );
303
304
	// Bailout.
305
	if( ! $payment->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...
306
		return;
307
	}
308
309
	$amount   = give_donation_amount( $payment_id );
310
	$status   = $payment->post_status;
311
	$donor_id = give_get_payment_donor_id( $payment_id );
312
	$donor    = new Give_Donor( $donor_id );
0 ignored issues
show
Documentation introduced by
$donor_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...
313
314
	// Only undo donations that aren't these statuses.
315
	$dont_undo_statuses = apply_filters( 'give_undo_donation_statuses', array(
316
		'pending',
317
		'cancelled',
318
	) );
319
320
	if ( ! in_array( $status, $dont_undo_statuses ) ) {
321
		give_undo_donation( $payment_id );
322
	}
323
324
	// Only undo donations that aren't these statuses.
325
	$status_to_decrease_stats = apply_filters( 'give_decrease_donor_statuses', array( 'publish' ) );
326
327
	if ( in_array( $status, $status_to_decrease_stats ) ) {
328
329
		// Only decrease earnings if they haven't already been decreased (or were never increased for this payment).
330
		give_decrease_total_earnings( $amount );
331
332
		// @todo: Refresh only range related stat cache
333
		give_delete_donation_stats();
334
335
		if ( $donor->id && $update_donor ) {
336
337
			// Decrement the stats for the donor.
338
			$donor->decrease_donation_count();
339
			$donor->decrease_value( $amount );
340
341
		}
342
	}
343
344
	/**
345
	 * Fires before deleting payment.
346
	 *
347
	 * @param int $payment_id Payment ID.
348
	 *
349
	 * @since 1.0
350
	 */
351
	do_action( 'give_payment_delete', $payment_id );
352
353
	if ( $donor->id && $update_donor ) {
354
		// Remove the payment ID from the donor.
355
		$donor->remove_payment( $payment_id );
356
	}
357
358
	// Remove the payment.
359
	wp_delete_post( $payment_id, true );
360
361
	// Remove related sale log entries.
362
	$give_logs->delete_logs( null, 'sale', array(
363
		array(
364
			'key'   => '_give_log_payment_id',
365
			'value' => $payment_id,
366
		),
367
	) );
368
369
	/**
370
	 * Fires after payment deleted.
371
	 *
372
	 * @param int $payment_id Payment ID.
373
	 *
374
	 * @since 1.0
375
	 */
376
	do_action( 'give_payment_deleted', $payment_id );
377
}
378
379
/**
380
 * Undo Donation
381
 *
382
 * Undoes a donation, including the decrease of donations and earning stats.
383
 * Used for when refunding or deleting a donation.
384
 *
385
 * @param  int $payment_id Payment ID.
386
 *
387
 * @since  1.0
388
 *
389
 * @return void
390
 */
391
function give_undo_donation( $payment_id ) {
392
393
	$payment = new Give_Payment( $payment_id );
394
395
	$maybe_decrease_earnings = apply_filters( 'give_decrease_earnings_on_undo', true, $payment, $payment->form_id );
396
	if ( true === $maybe_decrease_earnings ) {
397
		// Decrease earnings.
398
		give_decrease_form_earnings( $payment->form_id, $payment->total );
399
	}
400
401
	$maybe_decrease_donations = apply_filters( 'give_decrease_donations_on_undo', true, $payment, $payment->form_id );
402
	if ( true === $maybe_decrease_donations ) {
403
		// Decrease donation count.
404
		give_decrease_donation_count( $payment->form_id );
405
	}
406
407
}
408
409
410
/**
411
 * Count Payments
412
 *
413
 * Returns the total number of payments recorded.
414
 *
415
 * @param  array $args Arguments passed.
416
 *
417
 * @since  1.0
418
 *
419
 * @return object $stats Contains the number of payments per payment status.
420
 */
421
function give_count_payments( $args = array() ) {
422
	// Backward compatibility.
423
	if( ! empty( $args['start-date'] ) ) {
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...
424
		$args['start_date'] = $args['start-date'];
425
		unset( $args['start-date'] );
426
	}
427
428
	if( ! empty( $args['end-date'] ) ) {
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...
429
		$args['end_date'] = $args['end-date'];
430
		unset( $args['end-date'] );
431
	}
432
433
	if( ! empty( $args['form_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...
434
		$args['give_forms'] = $args['form_id'];
435
		unset( $args['form_id'] );
436
	}
437
438
	// Extract all donations
439
	$args['number']   = - 1;
440
	$args['group_by'] = 'post_status';
441
	$args['count']    = 'true';
442
443
	$donations_obj = new Give_Payments_Query( $args );
444
	$donations_count = $donations_obj->get_payment_by_group();
445
446
	return (object) apply_filters( 'give_count_payments', $donations_count, $args, $donations_obj );
447
}
448
449
450
/**
451
 * Check For Existing Payment
452
 *
453
 * @param  int $payment_id Payment ID.
454
 *
455
 * @since  1.0
456
 *
457
 * @return bool $exists True if payment exists, false otherwise.
458
 */
459
function give_check_for_existing_payment( $payment_id ) {
460
	$exists  = false;
461
	$payment = new Give_Payment( $payment_id );
462
463
	if ( $payment_id === $payment->ID && 'publish' === $payment->status ) {
464
		$exists = true;
465
	}
466
467
	return $exists;
468
}
469
470
/**
471
 * Get Payment Status
472
 *
473
 * @param WP_Post|Give_Payment|int $payment      Payment object or payment ID.
474
 * @param bool                     $return_label Whether to return the translated status label instead of status value. Default false.
475
 *
476
 * @since 1.0
477
 *
478
 * @return bool|mixed True if payment status exists, false otherwise.
479
 */
480
function give_get_payment_status( $payment, $return_label = false ) {
481
482
	if ( is_numeric( $payment ) ) {
483
484
		$payment = new Give_Payment( $payment );
485
486
		if ( ! $payment->ID > 0 ) {
487
			return false;
488
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
489
490
	}
491
492
	if ( ! is_object( $payment ) || ! isset( $payment->post_status ) ) {
493
		return false;
494
	}
495
496
	$statuses = give_get_payment_statuses();
497
498
	if ( ! is_array( $statuses ) || empty( $statuses ) ) {
499
		return false;
500
	}
501
502
	// Get payment object if not already given.
503
	$payment = $payment instanceof Give_Payment ? $payment : new Give_Payment( $payment->ID );
504
505
	if ( array_key_exists( $payment->status, $statuses ) ) {
506
		if ( true === $return_label ) {
507
			// Return translated status label.
508
			return $statuses[ $payment->status ];
509
		} else {
510
			// Account that our 'publish' status is labeled 'Complete'
511
			$post_status = 'publish' === $payment->status ? 'Complete' : $payment->post_status;
512
513
			// Make sure we're matching cases, since they matter
514
			return array_search( strtolower( $post_status ), array_map( 'strtolower', $statuses ) );
515
		}
516
	}
517
518
	return false;
519
}
520
521
/**
522
 * Retrieves all available statuses for payments.
523
 *
524
 * @since  1.0
525
 *
526
 * @return array $payment_status All the available payment statuses.
527
 */
528
function give_get_payment_statuses() {
529
	$payment_statuses = array(
530
		'pending'     => __( 'Pending', 'give' ),
531
		'publish'     => __( 'Complete', 'give' ),
532
		'refunded'    => __( 'Refunded', 'give' ),
533
		'failed'      => __( 'Failed', 'give' ),
534
		'cancelled'   => __( 'Cancelled', 'give' ),
535
		'abandoned'   => __( 'Abandoned', 'give' ),
536
		'preapproval' => __( 'Pre-Approved', 'give' ),
537
		'processing'  => __( 'Processing', 'give' ),
538
		'revoked'     => __( 'Revoked', 'give' ),
539
	);
540
541
	return apply_filters( 'give_payment_statuses', $payment_statuses );
542
}
543
544
/**
545
 * Get Payment Status Keys
546
 *
547
 * Retrieves keys for all available statuses for payments
548
 *
549
 * @since 1.0
550
 *
551
 * @return array $payment_status All the available payment statuses.
552
 */
553
function give_get_payment_status_keys() {
554
	$statuses = array_keys( give_get_payment_statuses() );
555
	asort( $statuses );
556
557
	return array_values( $statuses );
558
}
559
560
/**
561
 * Get Earnings By Date
562
 *
563
 * @param int $day       Day number. Default is null.
564
 * @param int $month_num Month number. Default is null.
565
 * @param int $year      Year number. Default is null.
566
 * @param int $hour      Hour number. Default is null.
567
 *
568
 * @since 1.0
569
 *
570
 * @return int $earnings Earnings
571
 */
572
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
573
574
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead.
575
	global $wpdb;
576
577
	$args = array(
578
		'post_type'              => 'give_payment',
579
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
580
		'year'                   => $year,
581
		'monthnum'               => $month_num,
582
		'post_status'            => array( 'publish' ),
583
		'fields'                 => 'ids',
584
		'update_post_term_cache' => false,
585
	);
586
	if ( ! empty( $day ) ) {
587
		$args['day'] = $day;
588
	}
589
590
	if ( isset( $hour ) ) {
591
		$args['hour'] = $hour;
592
	}
593
594
	$args = apply_filters( 'give_get_earnings_by_date_args', $args );
595
	$key  = Give_Cache::get_key( 'give_stats', $args );
596
597 View Code Duplication
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
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...
598
		$earnings = false;
599
	} else {
600
		$earnings = Give_Cache::get( $key );
601
	}
602
603
	if ( false === $earnings ) {
604
		$donations = get_posts( $args );
605
		$earnings  = 0;
606
		if ( $donations ) {
607
			$donations      = implode( ',', $donations );
608
			$earning_totals = $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN ({$donations})" );
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...
609
610
			/**
611
			 * Filter The earnings by dates.
612
			 *
613
			 * @since 1.8.17
614
			 *
615
			 * @param float $earning_totals Total earnings between the dates.
616
			 * @param array $donations      Donations lists.
617
			 * @param array $args           Donation query args.
618
			 */
619
			$earnings = apply_filters( 'give_get_earnings_by_date', $earning_totals, $donations, $args );
620
		}
621
		// Cache the results for one hour.
622
		Give_Cache::set( $key, $earnings, HOUR_IN_SECONDS );
623
	}
624
625
	return round( $earnings, 2 );
626
}
627
628
/**
629
 * Get Donations (sales) By Date
630
 *
631
 * @param int $day       Day number. Default is null.
632
 * @param int $month_num Month number. Default is null.
633
 * @param int $year      Year number. Default is null.
634
 * @param int $hour      Hour number. Default is null.
635
 *
636
 * @since 1.0
637
 *
638
 * @return int $count Sales
639
 */
640
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
641
642
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead.
643
	$args = array(
644
		'post_type'              => 'give_payment',
645
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
646
		'year'                   => $year,
647
		'fields'                 => 'ids',
648
		'post_status'            => array( 'publish' ),
649
		'update_post_meta_cache' => false,
650
		'update_post_term_cache' => false,
651
	);
652
653
	$show_free = apply_filters( 'give_sales_by_date_show_free', true, $args );
654
655
	if ( false === $show_free ) {
656
		$args['meta_query'] = array(
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
657
			array(
658
				'key'     => '_give_payment_total',
659
				'value'   => 0,
660
				'compare' => '>',
661
				'type'    => 'NUMERIC',
662
			),
663
		);
664
	}
665
666
	if ( ! empty( $month_num ) ) {
667
		$args['monthnum'] = $month_num;
668
	}
669
670
	if ( ! empty( $day ) ) {
671
		$args['day'] = $day;
672
	}
673
674
	if ( isset( $hour ) ) {
675
		$args['hour'] = $hour;
676
	}
677
678
	$args = apply_filters( 'give_get_sales_by_date_args', $args );
679
680
	$key = Give_Cache::get_key( 'give_stats', $args );
681
682 View Code Duplication
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
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...
683
		$count = false;
684
	} else {
685
		$count = Give_Cache::get( $key );
686
	}
687
688
	if ( false === $count ) {
689
		$donations = new WP_Query( $args );
690
		$count     = (int) $donations->post_count;
691
		// Cache the results for one hour.
692
		Give_Cache::set( $key, $count, HOUR_IN_SECONDS );
693
	}
694
695
	return $count;
696
}
697
698
/**
699
 * Checks whether a payment has been marked as complete.
700
 *
701
 * @param int $payment_id Payment ID to check against.
702
 *
703
 * @since 1.0
704
 *
705
 * @return bool $ret True if complete, false otherwise.
706
 */
707
function give_is_payment_complete( $payment_id ) {
708
	$payment = new Give_Payment( $payment_id );
709
710
	$ret = false;
711
712
	if ( $payment->ID > 0 ) {
713
714
		if ( (int) $payment_id === (int) $payment->ID && 'publish' == $payment->status ) {
715
			$ret = true;
716
		}
717
	}
718
719
	return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
720
}
721
722
/**
723
 * Get Total Donations.
724
 *
725
 * @since 1.0
726
 *
727
 * @return int $count Total number of donations.
728
 */
729
function give_get_total_donations() {
730
731
	$payments = give_count_payments();
732
733
	return $payments->publish;
734
}
735
736
/**
737
 * Get Total Earnings
738
 *
739
 * @param bool $recalculate Recalculate earnings forcefully.
740
 *
741
 * @since 1.0
742
 *
743
 * @return float $total Total earnings.
744
 */
745
function give_get_total_earnings( $recalculate = false ) {
746
747
	$total = get_option( 'give_earnings_total', 0 );
748
749
	// Calculate total earnings.
750
	if ( ! $total || $recalculate ) {
751
		global $wpdb;
752
753
		$total = (float) 0;
754
755
		$args = apply_filters( 'give_get_total_earnings_args', array(
756
			'offset' => 0,
757
			'number' => - 1,
758
			'status' => array( 'publish' ),
759
			'fields' => 'ids',
760
		) );
761
762
		$payments = give_get_payments( $args );
763
		if ( $payments ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payments 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...
764
765
			/**
766
			 * If performing a donation, we need to skip the very last payment in the database,
767
			 * since it calls give_increase_total_earnings() on completion,
768
			 * which results in duplicated earnings for the very first donation.
769
			 */
770
			if ( did_action( 'give_update_payment_status' ) ) {
771
				array_pop( $payments );
772
			}
773
774
			if ( ! empty( $payments ) ) {
775
				$payments = implode( ',', $payments );
776
				$total    += $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN({$payments})" );
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...
777
			}
778
		}
779
780
		update_option( 'give_earnings_total', $total, 'no' );
781
	}
782
783
	if ( $total < 0 ) {
784
		$total = 0; // Don't ever show negative earnings.
785
	}
786
787
	return apply_filters( 'give_total_earnings', round( $total, give_get_price_decimals() ), $total );
788
}
789
790
/**
791
 * Increase the Total Earnings
792
 *
793
 * @param int $amount The amount you would like to increase the total earnings by. Default is 0.
794
 *
795
 * @since 1.0
796
 *
797
 * @return float $total Total earnings.
798
 */
799
function give_increase_total_earnings( $amount = 0 ) {
800
	$total = give_get_total_earnings();
801
	$total += $amount;
802
	update_option( 'give_earnings_total', $total );
803
804
	return $total;
805
}
806
807
/**
808
 * Decrease the Total Earnings
809
 *
810
 * @param int $amount The amount you would like to decrease the total earnings by.
811
 *
812
 * @since 1.0
813
 *
814
 * @return float $total Total earnings.
815
 */
816
function give_decrease_total_earnings( $amount = 0 ) {
817
	$total = give_get_total_earnings();
818
	$total -= $amount;
819
	if ( $total < 0 ) {
820
		$total = 0;
821
	}
822
	update_option( 'give_earnings_total', $total );
823
824
	return $total;
825
}
826
827
/**
828
 * Get Payment Meta for a specific Payment
829
 *
830
 * @param int    $payment_id Payment ID.
831
 * @param string $meta_key   The meta key to pull.
832
 * @param bool   $single     Pull single meta entry or as an object.
833
 *
834
 * @since 1.0
835
 *
836
 * @return mixed $meta Payment Meta.
837
 */
838
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
839
	$payment = new Give_Payment( $payment_id );
840
841
	return $payment->get_meta( $meta_key, $single );
842
}
843
844
/**
845
 * Update the meta for a payment
846
 *
847
 * @param  int    $payment_id Payment ID.
848
 * @param  string $meta_key   Meta key to update.
849
 * @param  string $meta_value Value to update to.
850
 * @param  string $prev_value Previous value.
851
 *
852
 * @return mixed Meta ID if successful, false if unsuccessful.
853
 */
854
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
855
	$payment = new Give_Payment( $payment_id );
856
857
	return $payment->update_meta( $meta_key, $meta_value, $prev_value );
858
}
859
860
/**
861
 * Get the user_info Key from Payment Meta
862
 *
863
 * @param int $payment_id Payment ID.
864
 *
865
 * @since 1.0
866
 *
867
 * @return array $user_info User Info Meta Values.
868
 */
869
function give_get_payment_meta_user_info( $payment_id ) {
870
	$payment = new Give_Payment( $payment_id );
871
872
	return $payment->user_info;
873
}
874
875
/**
876
 * Get the donations Key from Payment Meta
877
 *
878
 * Retrieves the form_id from a (Previously titled give_get_payment_meta_donations)
879
 *
880
 * @param int $payment_id Payment ID.
881
 *
882
 * @since 1.0
883
 *
884
 * @return int $form_id Form ID.
885
 */
886
function give_get_payment_form_id( $payment_id ) {
887
	$payment = new Give_Payment( $payment_id );
888
889
	return $payment->form_id;
890
}
891
892
/**
893
 * Get the user email associated with a payment
894
 *
895
 * @param int $payment_id Payment ID.
896
 *
897
 * @since 1.0
898
 *
899
 * @return string $email User email.
900
 */
901
function give_get_payment_user_email( $payment_id ) {
902
	$payment = new Give_Payment( $payment_id );
903
904
	return $payment->email;
905
}
906
907
/**
908
 * Is the payment provided associated with a user account
909
 *
910
 * @param int $payment_id The payment ID.
911
 *
912
 * @since 1.3
913
 *
914
 * @return bool $is_guest_payment If the payment is associated with a user (false) or not (true)
915
 */
916
function give_is_guest_payment( $payment_id ) {
917
	$payment_user_id  = give_get_payment_user_id( $payment_id );
918
	$is_guest_payment = ! empty( $payment_user_id ) && $payment_user_id > 0 ? false : true;
919
920
	return (bool) apply_filters( 'give_is_guest_payment', $is_guest_payment, $payment_id );
921
}
922
923
/**
924
 * Get the user ID associated with a payment
925
 *
926
 * @param int $payment_id Payment ID.
927
 *
928
 * @since 1.3
929
 *
930
 * @return int $user_id User ID.
931
 */
932
function give_get_payment_user_id( $payment_id ) {
933
	$payment = new Give_Payment( $payment_id );
934
935
	return $payment->user_id;
936
}
937
938
/**
939
 * Get the donor ID associated with a payment.
940
 *
941
 * @param int $payment_id Payment ID.
942
 *
943
 * @since 1.0
944
 *
945
 * @return int $payment->customer_id Donor ID.
946
 */
947
function give_get_payment_donor_id( $payment_id ) {
948
	$payment = new Give_Payment( $payment_id );
949
950
	return $payment->customer_id;
951
}
952
953
/**
954
 * Get the IP address used to make a donation
955
 *
956
 * @param int $payment_id Payment ID.
957
 *
958
 * @since 1.0
959
 *
960
 * @return string $ip User IP.
961
 */
962
function give_get_payment_user_ip( $payment_id ) {
963
	$payment = new Give_Payment( $payment_id );
964
965
	return $payment->ip;
966
}
967
968
/**
969
 * Get the date a payment was completed
970
 *
971
 * @param int $payment_id Payment ID.
972
 *
973
 * @since 1.0
974
 *
975
 * @return string $date The date the payment was completed.
976
 */
977
function give_get_payment_completed_date( $payment_id = 0 ) {
978
	$payment = new Give_Payment( $payment_id );
979
980
	return $payment->completed_date;
981
}
982
983
/**
984
 * Get the gateway associated with a payment
985
 *
986
 * @param int $payment_id Payment ID.
987
 *
988
 * @since 1.0
989
 *
990
 * @return string $gateway Gateway.
991
 */
992
function give_get_payment_gateway( $payment_id ) {
993
	$payment = new Give_Payment( $payment_id );
994
995
	return $payment->gateway;
996
}
997
998
/**
999
 * Get the currency code a payment was made in
1000
 *
1001
 * @param int $payment_id Payment ID.
1002
 *
1003
 * @since 1.0
1004
 *
1005
 * @return string $currency The currency code.
1006
 */
1007
function give_get_payment_currency_code( $payment_id = 0 ) {
1008
	$payment = new Give_Payment( $payment_id );
1009
1010
	return $payment->currency;
1011
}
1012
1013
/**
1014
 * Get the currency name a payment was made in
1015
 *
1016
 * @param int $payment_id Payment ID.
1017
 *
1018
 * @since 1.0
1019
 *
1020
 * @return string $currency The currency name.
1021
 */
1022
function give_get_payment_currency( $payment_id = 0 ) {
1023
	$currency = give_get_payment_currency_code( $payment_id );
1024
1025
	return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
1026
}
1027
1028
/**
1029
 * Get the key for a donation
1030
 *
1031
 * @param int $payment_id Payment ID.
1032
 *
1033
 * @since 1.0
1034
 *
1035
 * @return string $key Donation key.
1036
 */
1037
function give_get_payment_key( $payment_id = 0 ) {
1038
	$payment = new Give_Payment( $payment_id );
1039
1040
	return $payment->key;
1041
}
1042
1043
/**
1044
 * Get the payment order number
1045
 *
1046
 * This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
1047
 *
1048
 * @param int $payment_id Payment ID.
1049
 *
1050
 * @since 1.0
1051
 *
1052
 * @return string $number Payment order number.
1053
 */
1054
function give_get_payment_number( $payment_id = 0 ) {
1055
	$payment = new Give_Payment( $payment_id );
1056
1057
	return $payment->number;
1058
}
1059
1060
/**
1061
 * Formats the payment number with the prefix and postfix
1062
 *
1063
 * @param int $number The payment number to format.
1064
 *
1065
 * @since 1.3
1066
 *
1067
 * @return string      The formatted payment number.
1068
 */
1069
function give_format_payment_number( $number ) {
1070
1071
	if ( ! give_get_option( 'enable_sequential' ) ) {
1072
		return $number;
1073
	}
1074
1075
	if ( ! is_numeric( $number ) ) {
1076
		return $number;
1077
	}
1078
1079
	$prefix  = give_get_option( 'sequential_prefix' );
1080
	$number  = absint( $number );
1081
	$postfix = give_get_option( 'sequential_postfix' );
1082
1083
	$formatted_number = $prefix . $number . $postfix;
1084
1085
	return apply_filters( 'give_format_payment_number', $formatted_number, $prefix, $number, $postfix );
1086
}
1087
1088
/**
1089
 * Gets the next available order number
1090
 *
1091
 * This is used when inserting a new payment
1092
 *
1093
 * @since 1.0
1094
 *
1095
 * @return string $number The next available payment number.
1096
 */
1097
function give_get_next_payment_number() {
1098
1099
	if ( ! give_get_option( 'enable_sequential' ) ) {
1100
		return false;
1101
	}
1102
1103
	$number           = get_option( 'give_last_payment_number' );
1104
	$start            = give_get_option( 'sequential_start', 1 );
1105
	$increment_number = true;
1106
1107
	if ( false !== $number ) {
1108
1109
		if ( empty( $number ) ) {
1110
1111
			$number           = $start;
1112
			$increment_number = false;
1113
1114
		}
1115
	} else {
1116
1117
		// This case handles the first addition of the new option, as well as if it get's deleted for any reason.
1118
		$payments     = new Give_Payments_Query( array(
1119
			'number'  => 1,
1120
			'order'   => 'DESC',
1121
			'orderby' => 'ID',
1122
			'output'  => 'posts',
1123
			'fields'  => 'ids',
1124
		) );
1125
		$last_payment = $payments->get_payments();
1126
1127
		if ( ! empty( $last_payment ) ) {
1128
1129
			$number = give_get_payment_number( $last_payment[0] );
1130
1131
		}
1132
1133
		if ( ! empty( $number ) && $number !== (int) $last_payment[0] ) {
1134
1135
			$number = give_remove_payment_prefix_postfix( $number );
1136
1137
		} else {
1138
1139
			$number           = $start;
1140
			$increment_number = false;
1141
		}
1142
	}// End if().
1143
1144
	$increment_number = apply_filters( 'give_increment_payment_number', $increment_number, $number );
1145
1146
	if ( $increment_number ) {
1147
		$number ++;
1148
	}
1149
1150
	return apply_filters( 'give_get_next_payment_number', $number );
1151
}
1152
1153
/**
1154
 * Given a given a number, remove the pre/postfix
1155
 *
1156
 * @param string $number The formatted Current Number to increment.
1157
 *
1158
 * @since 1.3
1159
 *
1160
 * @return string The new Payment number without prefix and postfix.
1161
 */
1162
function give_remove_payment_prefix_postfix( $number ) {
1163
1164
	$prefix  = give_get_option( 'sequential_prefix' );
1165
	$postfix = give_get_option( 'sequential_postfix' );
1166
1167
	// Remove prefix.
1168
	$number = preg_replace( '/' . $prefix . '/', '', $number, 1 );
1169
1170
	// Remove the postfix.
1171
	$length      = strlen( $number );
1172
	$postfix_pos = strrpos( $number, $postfix );
1173
	if ( false !== $postfix_pos ) {
1174
		$number = substr_replace( $number, '', $postfix_pos, $length );
1175
	}
1176
1177
	// Ensure it's a whole number.
1178
	$number = intval( $number );
1179
1180
	return apply_filters( 'give_remove_payment_prefix_postfix', $number, $prefix, $postfix );
1181
1182
}
1183
1184
/**
1185
 * Get Donation Amount
1186
 *
1187
 * Get the fully formatted or unformatted donation amount which is sent through give_currency_filter()
1188
 * and give_format_amount() to format the amount correctly in case of formatted amount.
1189
 *
1190
 * @param int|Give_Payment $donation    Donation ID or Donation Object.
1191
 * @param bool|array       $format_args Currency Formatting Arguments.
1192
 *
1193
 * @since 1.0
1194
 * @since 1.8.17 Added filter and internally use functions.
1195
 *
1196
 * @return string $amount Fully formatted donation amount.
1197
 */
1198
function give_donation_amount( $donation, $format_args = false ) {
1199
	/* @var Give_Payment $donation */
1200
	if ( ! ( $donation instanceof Give_Payment ) ) {
1201
		$donation = new Give_Payment( absint( $donation ) );
1202
	}
1203
1204
	if ( ! is_array( $format_args ) ) {
1205
		$format_args = array(
1206
			'currency' => (bool) $format_args,
1207
			'amount'   => (bool) $format_args,
1208
		);
1209
	}
1210
1211
	$format_args = wp_parse_args(
1212
		$format_args,
1213
		array(
1214
			'currency' => false,
1215
			'amount'   => false,
1216
		)
1217
	);
1218
1219
	$amount           = $donation->total;
1220
	$formatted_amount = $amount;
1221
1222
	if ( $format_args['amount'] ) {
1223
		$formatted_amount = give_format_amount(
1224
			$amount,
1225
			array(
1226
				'sanitize' => false,
1227
				'currency' => $donation->currency,
1228
			)
1229
		);
1230
	}
1231
1232
	if ( $format_args['currency'] ) {
1233
		$formatted_amount = give_currency_filter(
1234
			$formatted_amount,
1235
			array( 'currency_code' => $donation->currency )
1236
		);
1237
	}
1238
1239
	/**
1240
	 * Filter Donation amount.
1241
	 *
1242
	 * @since 1.8.17
1243
	 *
1244
	 * @param string $formatted_amount Formatted/Un-formatted amount.
1245
	 * @param float  $amount           Donation amount.
1246
	 * @param int    $donation_id      Donation ID.
1247
	 */
1248
	return apply_filters( 'give_donation_amount', (string) $formatted_amount, $amount, $donation );
1249
}
1250
1251
/**
1252
 * Payment Subtotal
1253
 *
1254
 * Retrieves subtotal for payment and then returns a full formatted amount. This
1255
 * function essentially calls give_get_payment_subtotal()
1256
 *
1257
 * @param int $payment_id Payment ID.
1258
 *
1259
 * @since 1.5
1260
 *
1261
 * @see   give_get_payment_subtotal()
1262
 *
1263
 * @return array Fully formatted payment subtotal.
1264
 */
1265
function give_payment_subtotal( $payment_id = 0 ) {
1266
	$subtotal = give_get_payment_subtotal( $payment_id );
1267
1268
	return give_currency_filter( give_format_amount( $subtotal, array( 'sanitize' => false ) ), array( 'currency_code' => give_get_payment_currency_code( $payment_id ) ) );
1269
}
1270
1271
/**
1272
 * Get Payment Subtotal
1273
 *
1274
 * Retrieves subtotal for payment and then returns a non formatted amount.
1275
 *
1276
 * @param int $payment_id Payment ID.
1277
 *
1278
 * @since 1.5
1279
 *
1280
 * @return float $subtotal Subtotal for payment (non formatted).
1281
 */
1282
function give_get_payment_subtotal( $payment_id = 0 ) {
1283
	$payment = new Give_Payment( $payment_id );
1284
1285
	return $payment->subtotal;
1286
}
1287
1288
/**
1289
 * Retrieves the donation ID
1290
 *
1291
 * @param int $payment_id Payment ID.
1292
 *
1293
 * @since  1.0
1294
 *
1295
 * @return string The donation ID.
1296
 */
1297
function give_get_payment_transaction_id( $payment_id = 0 ) {
1298
	$payment = new Give_Payment( $payment_id );
1299
1300
	return $payment->transaction_id;
1301
}
1302
1303
/**
1304
 * Sets a Transaction ID in post meta for the given Payment ID.
1305
 *
1306
 * @param int    $payment_id     Payment ID.
1307
 * @param string $transaction_id The transaction ID from the gateway.
1308
 *
1309
 * @since  1.0
1310
 *
1311
 * @return bool|mixed
1312
 */
1313
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1314
1315
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1316
		return false;
1317
	}
1318
1319
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1320
1321
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1322
}
1323
1324
/**
1325
 * Retrieve the donation ID based on the key
1326
 *
1327
 * @param string  $key  the key to search for.
1328
 *
1329
 * @since 1.0
1330
 * @global object $wpdb Used to query the database using the WordPress Database API.
1331
 *
1332
 * @return int $purchase Donation ID.
1333
 */
1334 View Code Duplication
function give_get_purchase_id_by_key( $key ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

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

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

Loading history...
1335
	global $wpdb;
1336
1337
	$purchase = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_give_payment_purchase_key' AND meta_value = %s LIMIT 1", $key ) );
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...
1338
1339
	if ( $purchase != null ) {
1340
		return $purchase;
1341
	}
1342
1343
	return 0;
1344
}
1345
1346
1347
/**
1348
 * Retrieve the donation ID based on the transaction ID
1349
 *
1350
 * @param string  $key  The transaction ID to search for.
1351
 *
1352
 * @since 1.3
1353
 * @global object $wpdb Used to query the database using the WordPress Database API.
1354
 *
1355
 * @return int $purchase Donation ID.
1356
 */
1357 View Code Duplication
function give_get_purchase_id_by_transaction_id( $key ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

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

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

Loading history...
1358
	global $wpdb;
1359
1360
	$purchase = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_give_payment_transaction_id' AND meta_value = %s LIMIT 1", $key ) );
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...
1361
1362
	if ( $purchase != null ) {
1363
		return $purchase;
1364
	}
1365
1366
	return 0;
1367
}
1368
1369
/**
1370
 * Retrieve all notes attached to a donation
1371
 *
1372
 * @param int    $payment_id The donation ID to retrieve notes for.
1373
 * @param string $search     Search for notes that contain a search term.
1374
 *
1375
 * @since 1.0
1376
 *
1377
 * @return array $notes Donation Notes
1378
 */
1379
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1380
1381
	if ( empty( $payment_id ) && empty( $search ) ) {
1382
		return false;
1383
	}
1384
1385
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1386
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1387
1388
	$notes = get_comments( array(
1389
		'post_id' => $payment_id,
1390
		'order'   => 'ASC',
1391
		'search'  => $search,
1392
	) );
1393
1394
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1395
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1396
1397
	return $notes;
1398
}
1399
1400
1401
/**
1402
 * Add a note to a payment
1403
 *
1404
 * @param int    $payment_id The payment ID to store a note for.
1405
 * @param string $note       The note to store.
1406
 *
1407
 * @since 1.0
1408
 *
1409
 * @return int The new note ID
1410
 */
1411
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1412
	if ( empty( $payment_id ) ) {
1413
		return false;
1414
	}
1415
1416
	/**
1417
	 * Fires before inserting payment note.
1418
	 *
1419
	 * @param int    $payment_id Payment ID.
1420
	 * @param string $note       The note.
1421
	 *
1422
	 * @since 1.0
1423
	 */
1424
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1425
1426
	$note_id = wp_insert_comment( wp_filter_comment( array(
1427
		'comment_post_ID'      => $payment_id,
1428
		'comment_content'      => $note,
1429
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1430
		'comment_date'         => current_time( 'mysql' ),
1431
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1432
		'comment_approved'     => 1,
1433
		'comment_parent'       => 0,
1434
		'comment_author'       => '',
1435
		'comment_author_IP'    => '',
1436
		'comment_author_url'   => '',
1437
		'comment_author_email' => '',
1438
		'comment_type'         => 'give_payment_note',
1439
1440
	) ) );
1441
1442
	/**
1443
	 * Fires after payment note inserted.
1444
	 *
1445
	 * @param int    $note_id    Note ID.
1446
	 * @param int    $payment_id Payment ID.
1447
	 * @param string $note       The note.
1448
	 *
1449
	 * @since 1.0
1450
	 */
1451
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1452
1453
	return $note_id;
1454
}
1455
1456
/**
1457
 * Deletes a payment note
1458
 *
1459
 * @param int $comment_id The comment ID to delete.
1460
 * @param int $payment_id The payment ID the note is connected to.
1461
 *
1462
 * @since 1.0
1463
 *
1464
 * @return bool True on success, false otherwise.
1465
 */
1466
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1467
	if ( empty( $comment_id ) ) {
1468
		return false;
1469
	}
1470
1471
	/**
1472
	 * Fires before deleting donation note.
1473
	 *
1474
	 * @param int $comment_id Note ID.
1475
	 * @param int $payment_id Payment ID.
1476
	 *
1477
	 * @since 1.0
1478
	 */
1479
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1480
1481
	$ret = wp_delete_comment( $comment_id, true );
1482
1483
	/**
1484
	 * Fires after donation note deleted.
1485
	 *
1486
	 * @param int $comment_id Note ID.
1487
	 * @param int $payment_id Payment ID.
1488
	 *
1489
	 * @since 1.0
1490
	 */
1491
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1492
1493
	return $ret;
1494
}
1495
1496
/**
1497
 * Gets the payment note HTML
1498
 *
1499
 * @param object|int $note       The comment object or ID.
1500
 * @param int        $payment_id The payment ID the note is connected to.
1501
 *
1502
 * @since 1.0
1503
 *
1504
 * @return string
1505
 */
1506
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1507
1508
	if ( is_numeric( $note ) ) {
1509
		$note = get_comment( $note );
1510
	}
1511
1512
	if ( ! empty( $note->user_id ) ) {
1513
		$user = get_userdata( $note->user_id );
1514
		$user = $user->display_name;
1515
	} else {
1516
		$user = __( 'System', 'give' );
1517
	}
1518
1519
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1520
1521
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1522
		'give-action' => 'delete_payment_note',
1523
		'note_id'     => $note->comment_ID,
1524
		'payment_id'  => $payment_id,
1525
	) ), 'give_delete_payment_note_' . $note->comment_ID );
1526
1527
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1528
	$note_html .= '<p>';
1529
	$note_html .= '<strong>' . $user . '</strong>&nbsp;&ndash;&nbsp;<span style="color:#aaa;font-style:italic;">' . date_i18n( $date_format, strtotime( $note->comment_date ) ) . '</span><br/>';
1530
	$note_html .= $note->comment_content;
1531
	$note_html .= '&nbsp;&ndash;&nbsp;<a href="' . esc_url( $delete_note_url ) . '" class="give-delete-payment-note" data-note-id="' . absint( $note->comment_ID ) . '" data-payment-id="' . absint( $payment_id ) . '" aria-label="' . __( 'Delete this donation note.', 'give' ) . '">' . __( 'Delete', 'give' ) . '</a>';
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw '__'
Loading history...
1532
	$note_html .= '</p>';
1533
	$note_html .= '</div>';
1534
1535
	return $note_html;
1536
1537
}
1538
1539
/**
1540
 * Exclude notes (comments) on give_payment post type from showing in Recent
1541
 * Comments widgets
1542
 *
1543
 * @param object $query WordPress Comment Query Object.
1544
 *
1545
 * @since 1.0
1546
 *
1547
 * @return void
1548
 */
1549
function give_hide_payment_notes( $query ) {
1550
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1551
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1552
		if ( ! is_array( $types ) ) {
1553
			$types = array( $types );
1554
		}
1555
		$types[]                           = 'give_payment_note';
1556
		$query->query_vars['type__not_in'] = $types;
1557
	}
1558
}
1559
1560
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1561
1562
/**
1563
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1564
 *
1565
 * @param array  $clauses          Comment clauses for comment query.
1566
 * @param object $wp_comment_query WordPress Comment Query Object.
1567
 *
1568
 * @since 1.0
1569
 *
1570
 * @return array $clauses Updated comment clauses.
1571
 */
1572
function give_hide_payment_notes_pre_41( $clauses, $wp_comment_query ) {
0 ignored issues
show
Unused Code introduced by
The parameter $wp_comment_query 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...
1573
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1574
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1575
	}
1576
1577
	return $clauses;
1578
}
1579
1580
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1581
1582
1583
/**
1584
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1585
 *
1586
 * @param string $where
1587
 * @param object $wp_comment_query WordPress Comment Query Object.
1588
 *
1589
 * @since 1.0
1590
 *
1591
 * @return string $where
1592
 */
1593
function give_hide_payment_notes_from_feeds( $where, $wp_comment_query ) {
0 ignored issues
show
Unused Code introduced by
The parameter $wp_comment_query 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...
1594
	global $wpdb;
1595
1596
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1597
1598
	return $where;
1599
}
1600
1601
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1602
1603
1604
/**
1605
 * Remove Give Comments from the wp_count_comments function
1606
 *
1607
 * @param array $stats   (empty from core filter).
1608
 * @param int   $post_id Post ID.
1609
 *
1610
 * @access public
1611
 * @since  1.0
1612
 *
1613
 * @return array|object Array of comment counts.
1614
 */
1615
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1616
	global $wpdb, $pagenow;
1617
1618
	if ( 'index.php' != $pagenow ) {
1619
		return $stats;
1620
	}
1621
1622
	$post_id = (int) $post_id;
1623
1624
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1625
		return $stats;
1626
	}
1627
1628
	$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
1629
1630
	if ( false !== $stats ) {
1631
		return $stats;
1632
	}
1633
1634
	$where = 'WHERE comment_type != "give_payment_note"';
1635
1636
	if ( $post_id > 0 ) {
1637
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1638
	}
1639
1640
	$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1641
1642
	$total    = 0;
1643
	$approved = array(
1644
		'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
1645
		'1'            => 'approved',
1646
		'spam'         => 'spam',
1647
		'trash'        => 'trash',
1648
		'post-trashed' => 'post-trashed',
1649
	);
1650
	foreach ( (array) $count as $row ) {
1651
		// Don't count post-trashed toward totals.
1652
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1653
			$total += $row['num_comments'];
1654
		}
1655
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1656
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1657
		}
1658
	}
1659
1660
	$stats['total_comments'] = $total;
1661
	foreach ( $approved as $key ) {
1662
		if ( empty( $stats[ $key ] ) ) {
1663
			$stats[ $key ] = 0;
1664
		}
1665
	}
1666
1667
	$stats = (object) $stats;
1668
	wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
1669
1670
	return $stats;
1671
}
1672
1673
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1674
1675
1676
/**
1677
 * Filter where older than one week
1678
 *
1679
 * @param string $where Where clause.
1680
 *
1681
 * @access public
1682
 * @since  1.0
1683
 *
1684
 * @return string $where Modified where clause.
1685
 */
1686
function give_filter_where_older_than_week( $where = '' ) {
1687
	// Payments older than one week.
1688
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1689
	$where .= " AND post_date <= '{$start}'";
1690
1691
	return $where;
1692
}
1693
1694
1695
/**
1696
 * Get Payment Form ID.
1697
 *
1698
 * Retrieves the form title and appends the level name if present.
1699
 *
1700
 * @param array  $payment_meta Payment meta data.
1701
 * @param bool   $only_level   If set to true will only return the level name if multi-level enabled.
1702
 * @param string $separator    The separator between the .
1703
 *
1704
 * @since 1.5
1705
 *
1706
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1707
 */
1708
function give_get_payment_form_title( $payment_meta, $only_level = false, $separator = '' ) {
1709
1710
	$form_id    = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
1711
	$price_id   = isset( $payment_meta['price_id'] ) ? $payment_meta['price_id'] : null;
1712
	$form_title = isset( $payment_meta['form_title'] ) ? $payment_meta['form_title'] : '';
1713
1714
	if ( $only_level == true ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
introduced by
Found "== true". Use Yoda Condition checks, you must
Loading history...
1715
		$form_title = '';
1716
	}
1717
1718
	// If multi-level, append to the form title.
1719
	if ( give_has_variable_prices( $form_id ) ) {
1720
1721
		// Only add separator if there is a form title.
1722
		if ( ! empty( $form_title ) ) {
1723
			$form_title .= ' ' . $separator . ' ';
1724
		}
1725
1726
		$form_title .= '<span class="donation-level-text-wrap">';
1727
1728
		if ( 'custom' === $price_id ) {
1729
			$custom_amount_text = give_get_meta( $form_id, '_give_custom_amount_text', true );
1730
			$form_title         .= ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1731
		} else {
1732
			$form_title .= give_get_price_option_name( $form_id, $price_id );
1733
		}
1734
1735
		$form_title .= '</span>';
1736
1737
	}
1738
1739
	return apply_filters( 'give_get_payment_form_title', $form_title, $payment_meta );
1740
1741
}
1742
1743
/**
1744
 * Get Price ID
1745
 *
1746
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1747
 *
1748
 * @param int    $form_id Form ID.
1749
 * @param string $price   Price ID.
1750
 *
1751
 * @return string $price_id
1752
 */
1753
function give_get_price_id( $form_id, $price ) {
1754
	$price_id = null;
1755
1756
	if ( give_has_variable_prices( $form_id ) ) {
1757
1758
		$levels = give_get_meta( $form_id, '_give_donation_levels', true );
1759
1760
		foreach ( $levels as $level ) {
1761
1762
			$level_amount = give_maybe_sanitize_amount( $level['_give_amount'] );
1763
1764
			// Check that this indeed the recurring price.
1765
			if ( $level_amount == $price ) {
1766
1767
				$price_id = $level['_give_id']['level_id'];
1768
				break;
1769
1770
			}
1771
		}
1772
1773
		if ( is_null( $price_id ) && give_is_custom_price_mode( $form_id ) ) {
1774
			$price_id = 'custom';
1775
		}
1776
	}
1777
1778
	// Price ID must be numeric or string.
1779
	$price_id = ! is_numeric( $price_id ) && ! is_string( $price_id ) ? 0 : $price_id;
1780
1781
	return $price_id;
1782
}
1783
1784
/**
1785
 * Get/Print give form dropdown html
1786
 *
1787
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1788
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1789
 *
1790
 * @param array $args Arguments for form dropdown.
1791
 * @param bool  $echo This parameter decides if print form dropdown html output or not.
1792
 *
1793
 * @since 1.6
1794
 *
1795
 * @return string
1796
 */
1797
function give_get_form_dropdown( $args = array(), $echo = false ) {
1798
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1799
1800
	if ( ! $echo ) {
1801
		return $form_dropdown_html;
1802
	}
1803
1804
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1805
}
1806
1807
/**
1808
 * Get/Print give form variable price dropdown html
1809
 *
1810
 * @param array $args Arguments for form dropdown.
1811
 * @param bool  $echo This parameter decide if print form dropdown html output or not.
1812
 *
1813
 * @since 1.6
1814
 *
1815
 * @return string|bool
1816
 */
1817
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1818
1819
	// Check for give form id.
1820
	if ( empty( $args['id'] ) ) {
1821
		return false;
1822
	}
1823
1824
	$form = new Give_Donate_Form( $args['id'] );
1825
1826
	// Check if form has variable prices or not.
1827
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1828
		return false;
1829
	}
1830
1831
	$variable_prices        = $form->get_prices();
1832
	$variable_price_options = array();
1833
1834
	// Check if multi donation form support custom donation or not.
1835
	if ( $form->is_custom_price_mode() ) {
1836
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1837
	}
1838
1839
	// Get variable price and ID from variable price array.
1840
	foreach ( $variable_prices as $variable_price ) {
1841
		$variable_price_options[ $variable_price['_give_id']['level_id'] ] = ! empty( $variable_price['_give_text'] ) ? $variable_price['_give_text'] : give_currency_filter( give_format_amount( $variable_price['_give_amount'], array( 'sanitize' => false ) ) );
1842
	}
1843
1844
	// Update options.
1845
	$args = array_merge( $args, array(
1846
		'options' => $variable_price_options,
1847
	) );
1848
1849
	// Generate select html.
1850
	$form_dropdown_html = Give()->html->select( $args );
1851
1852
	if ( ! $echo ) {
1853
		return $form_dropdown_html;
1854
	}
1855
1856
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1857
}
1858
1859
/**
1860
 * Get the price_id from the payment meta.
1861
 *
1862
 * Some gateways use `give_price_id` and others were using just `price_id`;
1863
 * This checks for the difference and falls back to retrieving it from the form as a last resort.
1864
 *
1865
 * @param array $payment_meta Payment Meta.
1866
 *
1867
 * @since 1.8.6
1868
 *
1869
 * @return string
1870
 */
1871
function give_get_payment_meta_price_id( $payment_meta ) {
1872
1873
	if ( isset( $payment_meta['give_price_id'] ) ) {
1874
		$price_id = $payment_meta['give_price_id'];
1875
	} elseif ( isset( $payment_meta['price_id'] ) ) {
1876
		$price_id = $payment_meta['price_id'];
1877
	} else {
1878
		$price_id = give_get_price_id( $payment_meta['give_form_id'], $payment_meta['price'] );
1879
	}
1880
1881
	return apply_filters( 'give_get_payment_meta_price_id', $price_id );
1882
1883
}
1884