Test Failed
Push — release/1.8.17 ( baf467...e6f68c )
by Ravinder
05:06
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();
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_get_payment_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_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 Payment Amount
1186
 *
1187
 * Get the fully formatted donation amount. The donation amount is retrieved using give_get_donation_amount() and is then
1188
 * sent through give_currency_filter() and  give_format_amount() to format the amount correctly.
1189
 *
1190
 * @param int    $donation_id Donation ID.
1191
 * @param string $type        String parameter which will define context of donation amount.
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_id = 0, $type = '' ) {
1199
	$donation_currency = give_get_payment_currency_code( $donation_id );
1200
	$amount            = give_get_payment_amount( $donation_id );
1201
1202
	$formatted_amount = give_currency_filter(
1203
		give_format_amount(
1204
			$amount,
1205
			array(
1206
				'sanitize' => false,
1207
				'currency' => $donation_currency,
1208
			)
1209
		),
1210
		$donation_currency
1211
	);
1212
1213
	/**
1214
	 * Filter payment amount.
1215
	 *
1216
	 * @since 1.8.17
1217
	 *
1218
	 * @param string  $formatted_amount Formatted amount.
1219
	 * @param double  $amount           Donation amount.
1220
	 * @param integer $donation_id      Donation ID.
1221
	 * @param string  $type             String parameter which will define context of donation amount..
1222
	 */
1223
	return apply_filters( 'give_get_donation_amount', $formatted_amount, $amount, $donation_id, $type );
1224
}
1225
1226
/**
1227
 * Get the amount associated with a payment
1228
 *
1229
 * @param int $payment_id Payment ID.
1230
 *
1231
 * @access public
1232
 * @since  1.0
1233
 *
1234
 * @return mixed
1235
 */
1236
function give_get_payment_amount( $payment_id ) {
1237
1238
	$payment = new Give_Payment( $payment_id );
1239
1240
	return apply_filters( 'give_payment_amount', floatval( $payment->total ), $payment_id );
1241
}
1242
1243
/**
1244
 * Payment Subtotal
1245
 *
1246
 * Retrieves subtotal for payment and then returns a full formatted amount. This
1247
 * function essentially calls give_get_payment_subtotal()
1248
 *
1249
 * @param int $payment_id Payment ID.
1250
 *
1251
 * @since 1.5
1252
 *
1253
 * @see   give_get_payment_subtotal()
1254
 *
1255
 * @return array Fully formatted payment subtotal.
1256
 */
1257
function give_payment_subtotal( $payment_id = 0 ) {
1258
	$subtotal = give_get_payment_subtotal( $payment_id );
1259
1260
	return give_currency_filter( give_format_amount( $subtotal, array( 'sanitize' => false ) ), give_get_payment_currency_code( $payment_id ) );
1261
}
1262
1263
/**
1264
 * Get Payment Subtotal
1265
 *
1266
 * Retrieves subtotal for payment and then returns a non formatted amount.
1267
 *
1268
 * @param int $payment_id Payment ID.
1269
 *
1270
 * @since 1.5
1271
 *
1272
 * @return float $subtotal Subtotal for payment (non formatted).
1273
 */
1274
function give_get_payment_subtotal( $payment_id = 0 ) {
1275
	$payment = new Give_Payment( $payment_id );
1276
1277
	return $payment->subtotal;
1278
}
1279
1280
/**
1281
 * Retrieves the donation ID
1282
 *
1283
 * @param int $payment_id Payment ID.
1284
 *
1285
 * @since  1.0
1286
 *
1287
 * @return string The donation ID.
1288
 */
1289
function give_get_payment_transaction_id( $payment_id = 0 ) {
1290
	$payment = new Give_Payment( $payment_id );
1291
1292
	return $payment->transaction_id;
1293
}
1294
1295
/**
1296
 * Sets a Transaction ID in post meta for the given Payment ID.
1297
 *
1298
 * @param int    $payment_id     Payment ID.
1299
 * @param string $transaction_id The transaction ID from the gateway.
1300
 *
1301
 * @since  1.0
1302
 *
1303
 * @return bool|mixed
1304
 */
1305
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1306
1307
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1308
		return false;
1309
	}
1310
1311
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1312
1313
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1314
}
1315
1316
/**
1317
 * Retrieve the donation ID based on the key
1318
 *
1319
 * @param string  $key  the key to search for.
1320
 *
1321
 * @since 1.0
1322
 * @global object $wpdb Used to query the database using the WordPress Database API.
1323
 *
1324
 * @return int $purchase Donation ID.
1325
 */
1326 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...
1327
	global $wpdb;
1328
1329
	$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...
1330
1331
	if ( $purchase != null ) {
1332
		return $purchase;
1333
	}
1334
1335
	return 0;
1336
}
1337
1338
1339
/**
1340
 * Retrieve the donation ID based on the transaction ID
1341
 *
1342
 * @param string  $key  The transaction ID to search for.
1343
 *
1344
 * @since 1.3
1345
 * @global object $wpdb Used to query the database using the WordPress Database API.
1346
 *
1347
 * @return int $purchase Donation ID.
1348
 */
1349 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...
1350
	global $wpdb;
1351
1352
	$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...
1353
1354
	if ( $purchase != null ) {
1355
		return $purchase;
1356
	}
1357
1358
	return 0;
1359
}
1360
1361
/**
1362
 * Retrieve all notes attached to a donation
1363
 *
1364
 * @param int    $payment_id The donation ID to retrieve notes for.
1365
 * @param string $search     Search for notes that contain a search term.
1366
 *
1367
 * @since 1.0
1368
 *
1369
 * @return array $notes Donation Notes
1370
 */
1371
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1372
1373
	if ( empty( $payment_id ) && empty( $search ) ) {
1374
		return false;
1375
	}
1376
1377
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1378
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1379
1380
	$notes = get_comments( array(
1381
		'post_id' => $payment_id,
1382
		'order'   => 'ASC',
1383
		'search'  => $search,
1384
	) );
1385
1386
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1387
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1388
1389
	return $notes;
1390
}
1391
1392
1393
/**
1394
 * Add a note to a payment
1395
 *
1396
 * @param int    $payment_id The payment ID to store a note for.
1397
 * @param string $note       The note to store.
1398
 *
1399
 * @since 1.0
1400
 *
1401
 * @return int The new note ID
1402
 */
1403
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1404
	if ( empty( $payment_id ) ) {
1405
		return false;
1406
	}
1407
1408
	/**
1409
	 * Fires before inserting payment note.
1410
	 *
1411
	 * @param int    $payment_id Payment ID.
1412
	 * @param string $note       The note.
1413
	 *
1414
	 * @since 1.0
1415
	 */
1416
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1417
1418
	$note_id = wp_insert_comment( wp_filter_comment( array(
1419
		'comment_post_ID'      => $payment_id,
1420
		'comment_content'      => $note,
1421
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1422
		'comment_date'         => current_time( 'mysql' ),
1423
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1424
		'comment_approved'     => 1,
1425
		'comment_parent'       => 0,
1426
		'comment_author'       => '',
1427
		'comment_author_IP'    => '',
1428
		'comment_author_url'   => '',
1429
		'comment_author_email' => '',
1430
		'comment_type'         => 'give_payment_note',
1431
1432
	) ) );
1433
1434
	/**
1435
	 * Fires after payment note inserted.
1436
	 *
1437
	 * @param int    $note_id    Note ID.
1438
	 * @param int    $payment_id Payment ID.
1439
	 * @param string $note       The note.
1440
	 *
1441
	 * @since 1.0
1442
	 */
1443
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1444
1445
	return $note_id;
1446
}
1447
1448
/**
1449
 * Deletes a payment note
1450
 *
1451
 * @param int $comment_id The comment ID to delete.
1452
 * @param int $payment_id The payment ID the note is connected to.
1453
 *
1454
 * @since 1.0
1455
 *
1456
 * @return bool True on success, false otherwise.
1457
 */
1458
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1459
	if ( empty( $comment_id ) ) {
1460
		return false;
1461
	}
1462
1463
	/**
1464
	 * Fires before deleting donation note.
1465
	 *
1466
	 * @param int $comment_id Note ID.
1467
	 * @param int $payment_id Payment ID.
1468
	 *
1469
	 * @since 1.0
1470
	 */
1471
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1472
1473
	$ret = wp_delete_comment( $comment_id, true );
1474
1475
	/**
1476
	 * Fires after donation note deleted.
1477
	 *
1478
	 * @param int $comment_id Note ID.
1479
	 * @param int $payment_id Payment ID.
1480
	 *
1481
	 * @since 1.0
1482
	 */
1483
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1484
1485
	return $ret;
1486
}
1487
1488
/**
1489
 * Gets the payment note HTML
1490
 *
1491
 * @param object|int $note       The comment object or ID.
1492
 * @param int        $payment_id The payment ID the note is connected to.
1493
 *
1494
 * @since 1.0
1495
 *
1496
 * @return string
1497
 */
1498
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1499
1500
	if ( is_numeric( $note ) ) {
1501
		$note = get_comment( $note );
1502
	}
1503
1504
	if ( ! empty( $note->user_id ) ) {
1505
		$user = get_userdata( $note->user_id );
1506
		$user = $user->display_name;
1507
	} else {
1508
		$user = __( 'System', 'give' );
1509
	}
1510
1511
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1512
1513
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1514
		'give-action' => 'delete_payment_note',
1515
		'note_id'     => $note->comment_ID,
1516
		'payment_id'  => $payment_id,
1517
	) ), 'give_delete_payment_note_' . $note->comment_ID );
1518
1519
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1520
	$note_html .= '<p>';
1521
	$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/>';
1522
	$note_html .= $note->comment_content;
1523
	$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...
1524
	$note_html .= '</p>';
1525
	$note_html .= '</div>';
1526
1527
	return $note_html;
1528
1529
}
1530
1531
/**
1532
 * Exclude notes (comments) on give_payment post type from showing in Recent
1533
 * Comments widgets
1534
 *
1535
 * @param object $query WordPress Comment Query Object.
1536
 *
1537
 * @since 1.0
1538
 *
1539
 * @return void
1540
 */
1541
function give_hide_payment_notes( $query ) {
1542
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1543
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1544
		if ( ! is_array( $types ) ) {
1545
			$types = array( $types );
1546
		}
1547
		$types[]                           = 'give_payment_note';
1548
		$query->query_vars['type__not_in'] = $types;
1549
	}
1550
}
1551
1552
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1553
1554
/**
1555
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1556
 *
1557
 * @param array  $clauses          Comment clauses for comment query.
1558
 * @param object $wp_comment_query WordPress Comment Query Object.
1559
 *
1560
 * @since 1.0
1561
 *
1562
 * @return array $clauses Updated comment clauses.
1563
 */
1564
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...
1565
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1566
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1567
	}
1568
1569
	return $clauses;
1570
}
1571
1572
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1573
1574
1575
/**
1576
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1577
 *
1578
 * @param string $where
1579
 * @param object $wp_comment_query WordPress Comment Query Object.
1580
 *
1581
 * @since 1.0
1582
 *
1583
 * @return string $where
1584
 */
1585
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...
1586
	global $wpdb;
1587
1588
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1589
1590
	return $where;
1591
}
1592
1593
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1594
1595
1596
/**
1597
 * Remove Give Comments from the wp_count_comments function
1598
 *
1599
 * @param array $stats   (empty from core filter).
1600
 * @param int   $post_id Post ID.
1601
 *
1602
 * @access public
1603
 * @since  1.0
1604
 *
1605
 * @return array|object Array of comment counts.
1606
 */
1607
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1608
	global $wpdb, $pagenow;
1609
1610
	if ( 'index.php' != $pagenow ) {
1611
		return $stats;
1612
	}
1613
1614
	$post_id = (int) $post_id;
1615
1616
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1617
		return $stats;
1618
	}
1619
1620
	$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
1621
1622
	if ( false !== $stats ) {
1623
		return $stats;
1624
	}
1625
1626
	$where = 'WHERE comment_type != "give_payment_note"';
1627
1628
	if ( $post_id > 0 ) {
1629
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1630
	}
1631
1632
	$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...
1633
1634
	$total    = 0;
1635
	$approved = array(
1636
		'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
1637
		'1'            => 'approved',
1638
		'spam'         => 'spam',
1639
		'trash'        => 'trash',
1640
		'post-trashed' => 'post-trashed',
1641
	);
1642
	foreach ( (array) $count as $row ) {
1643
		// Don't count post-trashed toward totals.
1644
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1645
			$total += $row['num_comments'];
1646
		}
1647
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1648
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1649
		}
1650
	}
1651
1652
	$stats['total_comments'] = $total;
1653
	foreach ( $approved as $key ) {
1654
		if ( empty( $stats[ $key ] ) ) {
1655
			$stats[ $key ] = 0;
1656
		}
1657
	}
1658
1659
	$stats = (object) $stats;
1660
	wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
1661
1662
	return $stats;
1663
}
1664
1665
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1666
1667
1668
/**
1669
 * Filter where older than one week
1670
 *
1671
 * @param string $where Where clause.
1672
 *
1673
 * @access public
1674
 * @since  1.0
1675
 *
1676
 * @return string $where Modified where clause.
1677
 */
1678
function give_filter_where_older_than_week( $where = '' ) {
1679
	// Payments older than one week.
1680
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1681
	$where .= " AND post_date <= '{$start}'";
1682
1683
	return $where;
1684
}
1685
1686
1687
/**
1688
 * Get Payment Form ID.
1689
 *
1690
 * Retrieves the form title and appends the level name if present.
1691
 *
1692
 * @param array  $payment_meta Payment meta data.
1693
 * @param bool   $only_level   If set to true will only return the level name if multi-level enabled.
1694
 * @param string $separator    The separator between the .
1695
 *
1696
 * @since 1.5
1697
 *
1698
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1699
 */
1700
function give_get_payment_form_title( $payment_meta, $only_level = false, $separator = '' ) {
1701
1702
	$form_id    = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
1703
	$price_id   = isset( $payment_meta['price_id'] ) ? $payment_meta['price_id'] : null;
1704
	$form_title = isset( $payment_meta['form_title'] ) ? $payment_meta['form_title'] : '';
1705
1706
	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...
1707
		$form_title = '';
1708
	}
1709
1710
	// If multi-level, append to the form title.
1711
	if ( give_has_variable_prices( $form_id ) ) {
1712
1713
		// Only add separator if there is a form title.
1714
		if ( ! empty( $form_title ) ) {
1715
			$form_title .= ' ' . $separator . ' ';
1716
		}
1717
1718
		$form_title .= '<span class="donation-level-text-wrap">';
1719
1720
		if ( 'custom' === $price_id ) {
1721
			$custom_amount_text = give_get_meta( $form_id, '_give_custom_amount_text', true );
1722
			$form_title         .= ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1723
		} else {
1724
			$form_title .= give_get_price_option_name( $form_id, $price_id );
1725
		}
1726
1727
		$form_title .= '</span>';
1728
1729
	}
1730
1731
	return apply_filters( 'give_get_payment_form_title', $form_title, $payment_meta );
1732
1733
}
1734
1735
/**
1736
 * Get Price ID
1737
 *
1738
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1739
 *
1740
 * @param int    $form_id Form ID.
1741
 * @param string $price   Price ID.
1742
 *
1743
 * @return string $price_id
1744
 */
1745
function give_get_price_id( $form_id, $price ) {
1746
	$price_id = null;
1747
1748
	if ( give_has_variable_prices( $form_id ) ) {
1749
1750
		$levels = give_get_meta( $form_id, '_give_donation_levels', true );
1751
1752
		foreach ( $levels as $level ) {
1753
1754
			$level_amount = give_maybe_sanitize_amount( $level['_give_amount'] );
1755
1756
			// Check that this indeed the recurring price.
1757
			if ( $level_amount == $price ) {
1758
1759
				$price_id = $level['_give_id']['level_id'];
1760
				break;
1761
1762
			}
1763
		}
1764
1765
		if ( is_null( $price_id ) && give_is_custom_price_mode( $form_id ) ) {
1766
			$price_id = 'custom';
1767
		}
1768
	}
1769
1770
	// Price ID must be numeric or string.
1771
	$price_id = ! is_numeric( $price_id ) && ! is_string( $price_id ) ? 0 : $price_id;
1772
1773
	return $price_id;
1774
}
1775
1776
/**
1777
 * Get/Print give form dropdown html
1778
 *
1779
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1780
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1781
 *
1782
 * @param array $args Arguments for form dropdown.
1783
 * @param bool  $echo This parameter decides if print form dropdown html output or not.
1784
 *
1785
 * @since 1.6
1786
 *
1787
 * @return string
1788
 */
1789
function give_get_form_dropdown( $args = array(), $echo = false ) {
1790
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1791
1792
	if ( ! $echo ) {
1793
		return $form_dropdown_html;
1794
	}
1795
1796
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1797
}
1798
1799
/**
1800
 * Get/Print give form variable price dropdown html
1801
 *
1802
 * @param array $args Arguments for form dropdown.
1803
 * @param bool  $echo This parameter decide if print form dropdown html output or not.
1804
 *
1805
 * @since 1.6
1806
 *
1807
 * @return string|bool
1808
 */
1809
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1810
1811
	// Check for give form id.
1812
	if ( empty( $args['id'] ) ) {
1813
		return false;
1814
	}
1815
1816
	$form = new Give_Donate_Form( $args['id'] );
1817
1818
	// Check if form has variable prices or not.
1819
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1820
		return false;
1821
	}
1822
1823
	$variable_prices        = $form->get_prices();
1824
	$variable_price_options = array();
1825
1826
	// Check if multi donation form support custom donation or not.
1827
	if ( $form->is_custom_price_mode() ) {
1828
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1829
	}
1830
1831
	// Get variable price and ID from variable price array.
1832
	foreach ( $variable_prices as $variable_price ) {
1833
		$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 ) ) );
1834
	}
1835
1836
	// Update options.
1837
	$args = array_merge( $args, array(
1838
		'options' => $variable_price_options,
1839
	) );
1840
1841
	// Generate select html.
1842
	$form_dropdown_html = Give()->html->select( $args );
1843
1844
	if ( ! $echo ) {
1845
		return $form_dropdown_html;
1846
	}
1847
1848
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1849
}
1850
1851
/**
1852
 * Get the price_id from the payment meta.
1853
 *
1854
 * Some gateways use `give_price_id` and others were using just `price_id`;
1855
 * This checks for the difference and falls back to retrieving it from the form as a last resort.
1856
 *
1857
 * @param array $payment_meta Payment Meta.
1858
 *
1859
 * @since 1.8.6
1860
 *
1861
 * @return string
1862
 */
1863
function give_get_payment_meta_price_id( $payment_meta ) {
1864
1865
	if ( isset( $payment_meta['give_price_id'] ) ) {
1866
		$price_id = $payment_meta['give_price_id'];
1867
	} elseif ( isset( $payment_meta['price_id'] ) ) {
1868
		$price_id = $payment_meta['price_id'];
1869
	} else {
1870
		$price_id = give_get_price_id( $payment_meta['give_form_id'], $payment_meta['price'] );
1871
	}
1872
1873
	return apply_filters( 'give_get_payment_meta_price_id', $price_id );
1874
1875
}
1876