Completed
Push — issues/1796 ( b53179...52862a )
by Ravinder
41:58 queued 22:00
created

functions.php ➔ give_delete_donation()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 65
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 23
nc 12
nop 2
dl 0
loc 65
rs 7.1439
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

Loading history...
2
/**
3
 * 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
		case 'key':
88
			$payment = give_get_payments( array(
89
				'meta_key'       => '_give_payment_purchase_key',
90
				'meta_value'     => $value,
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
		case 'payment_number':
102
			$payment = give_get_payments( array(
103
				'meta_key'       => '_give_payment_number',
104
				'meta_value'     => $value,
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
	}
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
	$payment    = new Give_Payment();
142
	$gateway    = ! empty( $payment_data['gateway'] ) ? $payment_data['gateway'] : '';
143
	$gateway    = empty( $gateway ) && isset( $_POST['give-gateway'] ) ? $_POST['give-gateway'] : $gateway;
144
	$form_id    = isset( $payment_data['give_form_id'] ) ? $payment_data['give_form_id'] : 0;
145
	$price_id   = give_get_payment_meta_price_id( $payment_data );
146
	$form_title = isset( $payment_data['give_form_title'] ) ? $payment_data['give_form_title'] : get_the_title( $form_id );
147
148
	// Set properties.
149
	$payment->total          = $payment_data['price'];
150
	$payment->status         = ! empty( $payment_data['status'] ) ? $payment_data['status'] : 'pending';
151
	$payment->currency       = ! empty( $payment_data['currency'] ) ? $payment_data['currency'] : give_get_currency();
152
	$payment->user_info      = $payment_data['user_info'];
153
	$payment->gateway        = $gateway;
154
	$payment->form_title     = $form_title;
155
	$payment->form_id        = $form_id;
156
	$payment->price_id       = $price_id;
157
	$payment->user_id        = $payment_data['user_info']['id'];
158
	$payment->email          = $payment_data['user_email'];
159
	$payment->first_name     = $payment_data['user_info']['first_name'];
160
	$payment->last_name      = $payment_data['user_info']['last_name'];
161
	$payment->email          = $payment_data['user_info']['email'];
162
	$payment->ip             = give_get_ip();
163
	$payment->key            = $payment_data['purchase_key'];
164
	$payment->mode           = give_is_test_mode() ? 'test' : 'live';
165
	$payment->parent_payment = ! empty( $payment_data['parent'] ) ? absint( $payment_data['parent'] ) : '';
166
167
	// Add the donation.
168
	$args = array(
169
		'price'    => $payment->total,
170
		'price_id' => $payment->price_id,
171
	);
172
173
	$payment->add_donation( $payment->form_id, $args );
174
175
	// Set date if present.
176
	if ( isset( $payment_data['post_date'] ) ) {
177
		$payment->date = $payment_data['post_date'];
178
	}
179
180
	// Handle sequential payments.
181
	if ( give_get_option( 'enable_sequential' ) ) {
182
		$number          = give_get_next_payment_number();
183
		$payment->number = give_format_payment_number( $number );
184
		update_option( 'give_last_payment_number', $number );
185
	}
186
187
	// Clear the user's donation cache.
188
	delete_transient( 'give_user_' . $payment_data['user_info']['id'] . '_purchases' );
189
190
	// Save payment.
191
	$payment->save();
192
193
	/**
194
	 * Fires while inserting payments.
195
	 *
196
	 * @since 1.0
197
	 *
198
	 * @param int $payment_id The payment ID.
199
	 * @param array $payment_data Arguments passed.
200
	 */
201
	do_action( 'give_insert_payment', $payment->ID, $payment_data );
202
203
	// Return payment ID upon success.
204
	if ( ! empty( $payment->ID ) ) {
205
		return $payment->ID;
206
	}
207
208
	// Return false if no payment was inserted.
209
	return false;
210
211
}
212
213
/**
214
 * Create payment.
215
 *
216
 * @param $payment_data
217
 *
218
 * @return bool|int
219
 */
220
function give_create_payment( $payment_data ) {
221
222
	$form_id  = intval( $payment_data['post_data']['give-form-id'] );
223
	$price_id = isset( $payment_data['post_data']['give-price-id'] ) ? $payment_data['post_data']['give-price-id'] : '';
224
225
	// Collect payment data.
226
	$insert_payment_data = array(
227
		'price'           => $payment_data['price'],
228
		'give_form_title' => $payment_data['post_data']['give-form-title'],
229
		'give_form_id'    => $form_id,
230
		'give_price_id'   => $price_id,
231
		'date'            => $payment_data['date'],
232
		'user_email'      => $payment_data['user_email'],
233
		'purchase_key'    => $payment_data['purchase_key'],
234
		'currency'        => give_get_currency(),
235
		'user_info'       => $payment_data['user_info'],
236
		'status'          => 'pending',
237
		'gateway'         => 'paypal',
238
	);
239
240
	/**
241
	 * Filter the payment params.
242
	 *
243
	 * @since 1.8
244
	 *
245
	 * @param array $insert_payment_data
246
	 */
247
	$insert_payment_data = apply_filters( 'give_create_payment', $insert_payment_data );
248
249
	// Record the pending payment.
250
	return give_insert_payment( $insert_payment_data );
251
}
252
253
/**
254
 * Updates a payment status.
255
 *
256
 * @since  1.0
257
 *
258
 * @param  int $payment_id Payment ID.
259
 * @param  string $new_status New Payment Status. Default is 'publish'.
260
 *
261
 * @return bool
262
 */
263
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
264
265
	$payment         = new Give_Payment( $payment_id );
266
	$payment->status = $new_status;
267
	$updated         = $payment->save();
268
269
	return $updated;
270
}
271
272
273
/**
274
 * Deletes a Donation
275
 *
276
 * @since  1.0
277
 *
278
 * @param  int $payment_id Payment ID (default: 0).
279
 * @param  bool $update_donor If we should update the donor stats (default:true).
280
 *
281
 * @return void
282
 */
283
function give_delete_donation( $payment_id = 0, $update_donor = true ) {
284
	$payment     = new Give_Payment( $payment_id );
285
	$amount      = give_get_payment_amount( $payment_id );
286
	$status      = $payment->post_status;
287
	$donor_id = give_get_payment_donor_id( $payment_id );
288
	$donor    = new Give_Donor( $donor_id );
289
290
	// Only undo donations that aren't these statuses.
291
	$dont_undo_statuses = apply_filters( 'give_undo_donation_statuses', array(
292
		'pending',
293
		'cancelled',
294
	) );
295
296
	if ( ! in_array( $status, $dont_undo_statuses ) ) {
297
		give_undo_donation( $payment_id );
298
	}
299
300
	if ( $status == 'publish' ) {
301
302
		// Only decrease earnings if they haven't already been decreased (or were never increased for this payment).
303
		give_decrease_total_earnings( $amount );
304
305
		// @todo: Refresh only range related stat cache
306
		give_delete_donation_stats();
307
308
		if ( $donor->id && $update_donor ) {
309
310
			// Decrement the stats for the donor.
311
			$donor->decrease_donation_count();
312
			$donor->decrease_value( $amount );
313
314
		}
315
	}
316
317
	/**
318
	 * Fires before deleting payment.
319
	 *
320
	 * @since 1.0
321
	 *
322
	 * @param int $payment_id Payment ID.
323
	 */
324
	do_action( 'give_payment_delete', $payment_id );
325
326
	if ( $donor->id && $update_donor ) {
327
328
		// Remove the payment ID from the donor.
329
		$donor->remove_payment( $payment_id );
330
331
	}
332
333
	// Remove the payment.
334
	wp_delete_post( $payment_id, true );
335
336
	// Remove related sale log entries.
337
	Give()->logs->delete_logs( $payment_id );
338
339
	/**
340
	 * Fires after payment deleted.
341
	 *
342
	 * @since 1.0
343
	 *
344
	 * @param int $payment_id Payment ID.
345
	 */
346
	do_action( 'give_payment_deleted', $payment_id );
347
}
348
349
/**
350
 * Undo Donation
351
 *
352
 * Undoes a donation, including the decrease of donations and earning stats.
353
 * Used for when refunding or deleting a donation.
354
 *
355
 * @since  1.0
356
 *
357
 * @param  int $payment_id Payment ID.
358
 *
359
 * @return void
360
 */
361
function give_undo_donation( $payment_id ) {
362
363
	$payment = new Give_Payment( $payment_id );
364
365
	$maybe_decrease_earnings = apply_filters( 'give_decrease_earnings_on_undo', true, $payment, $payment->form_id );
366
	if ( true === $maybe_decrease_earnings ) {
367
		// Decrease earnings.
368
		give_decrease_earnings( $payment->form_id, $payment->total );
369
	}
370
371
	$maybe_decrease_donations = apply_filters( 'give_decrease_donations_on_undo', true, $payment, $payment->form_id );
372
	if ( true === $maybe_decrease_donations ) {
373
		// Decrease donation count.
374
		give_decrease_donation_count( $payment->form_id );
375
	}
376
377
}
378
379
380
/**
381
 * Count Payments
382
 *
383
 * Returns the total number of payments recorded.
384
 *
385
 * @since  1.0
386
 *
387
 * @param  array $args Arguments passed.
388
 *
389
 * @return object $stats Contains the number of payments per payment status.
390
 */
391
function give_count_payments( $args = array() ) {
392
393
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
394
395
	$defaults = array(
396
		'user'       => null,
397
		's'          => null,
398
		'start-date' => null,
399
		'end-date'   => null,
400
		'form_id'    => null,
401
	);
402
403
	$args = wp_parse_args( $args, $defaults );
404
405
	$select = 'SELECT p.post_status,count( * ) AS num_posts';
406
	$join   = '';
407
	$where  = "WHERE p.post_type = 'give_payment'";
408
409
	// Count payments for a specific user.
410
	if ( ! empty( $args['user'] ) ) {
411
412
		if ( is_email( $args['user'] ) ) {
413
			$field = 'email';
414
		} elseif ( is_numeric( $args['user'] ) ) {
415
			$field = 'id';
416
		} else {
417
			$field = '';
418
		}
419
420
		$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
421
422
		if ( ! empty( $field ) ) {
423
			$where .= "
424
				AND m.meta_key = '_give_payment_user_{$field}'
425
				AND m.meta_value = '{$args['user']}'";
426
		}
427
428
		// Count payments for a search.
429
	} elseif ( ! empty( $args['s'] ) ) {
430
431
		if ( is_email( $args['s'] ) || strlen( $args['s'] ) == 32 ) {
432
433
			if ( is_email( $args['s'] ) ) {
434
				$field = '_give_payment_user_email';
435
			} else {
436
				$field = '_give_payment_purchase_key';
437
			}
438
439
			$join  = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
440
			$where .= $wpdb->prepare( '
441
                AND m.meta_key = %s
442
                AND m.meta_value = %s',
443
				$field,
444
				$args['s']
445
			);
446
447
		} elseif ( '#' == substr( $args['s'], 0, 1 ) ) {
448
449
			$search = str_replace( '#:', '', $args['s'] );
450
			$search = str_replace( '#', '', $search );
451
452
			$select = 'SELECT p2.post_status,count( * ) AS num_posts ';
453
			$join   = "LEFT JOIN $wpdb->postmeta m ON m.meta_key = '_give_log_payment_id' AND m.post_id = p.ID ";
454
			$join   .= "INNER JOIN $wpdb->posts p2 ON m.meta_value = p2.ID ";
455
			$where  = "WHERE p.post_type = 'give_log' ";
456
			$where  .= $wpdb->prepare( 'AND p.post_parent = %d} ', $search );
457
458
		} elseif ( is_numeric( $args['s'] ) ) {
459
460
			$join  = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
461
			$where .= $wpdb->prepare( "
462
				AND m.meta_key = '_give_payment_user_id'
463
				AND m.meta_value = %d",
464
				$args['s']
465
			);
466
467
		} else {
468
			$search = $wpdb->esc_like( $args['s'] );
469
			$search = '%' . $search . '%';
470
471
			$where .= $wpdb->prepare( 'AND ((p.post_title LIKE %s) OR (p.post_content LIKE %s))', $search, $search );
472
		}
473
	}
474
475
	if ( ! empty( $args['form_id'] ) && is_numeric( $args['form_id'] ) ) {
476
477
		$where .= $wpdb->prepare( ' AND p.post_parent = %d', $args['form_id'] );
478
479
	}
480
	// Limit payments count by date.
481
	if ( ! empty( $args['start-date'] ) && false !== strpos( $args['start-date'], '/' ) ) {
482
483
		$date_parts = explode( '/', $args['start-date'] );
484
		$month      = ! empty( $date_parts[0] ) && is_numeric( $date_parts[0] ) ? $date_parts[0] : 0;
485
		$day        = ! empty( $date_parts[1] ) && is_numeric( $date_parts[1] ) ? $date_parts[1] : 0;
486
		$year       = ! empty( $date_parts[2] ) && is_numeric( $date_parts[2] ) ? $date_parts[2] : 0;
487
488
		$is_date = checkdate( $month, $day, $year );
489
		if ( false !== $is_date ) {
490
491
			$date  = new DateTime( $args['start-date'] );
492
			$where .= $wpdb->prepare( " AND p.post_date >= '%s'", $date->format( 'Y-m-d' ) );
493
494
		}
495
496
		// Fixes an issue with the payments list table counts when no end date is specified (partiy with stats class).
497
		if ( empty( $args['end-date'] ) ) {
498
			$args['end-date'] = $args['start-date'];
499
		}
500
	}
501
502
	if ( ! empty( $args['end-date'] ) && false !== strpos( $args['end-date'], '/' ) ) {
503
504
		$date_parts = explode( '/', $args['end-date'] );
505
506
		$month = ! empty( $date_parts[0] ) ? $date_parts[0] : 0;
507
		$day   = ! empty( $date_parts[1] ) ? $date_parts[1] : 0;
508
		$year  = ! empty( $date_parts[2] ) ? $date_parts[2] : 0;
509
510
		$is_date = checkdate( $month, $day, $year );
511
		if ( false !== $is_date ) {
512
513
			$date  = new DateTime( $args['end-date'] );
514
			$where .= $wpdb->prepare( " AND p.post_date <= '%s'", $date->format( 'Y-m-d' ) );
515
516
		}
517
	}
518
519
	$where = apply_filters( 'give_count_payments_where', $where );
520
	$join  = apply_filters( 'give_count_payments_join', $join );
521
522
	$query = "$select
523
		FROM $wpdb->posts p
524
		$join
525
		$where
526
		GROUP BY p.post_status
527
	";
528
529
	$cache_key = md5( $query );
530
531
	$count = wp_cache_get( $cache_key, 'counts' );
532
	if ( false !== $count ) {
533
		return $count;
534
	}
535
536
	$count = $wpdb->get_results( $query, ARRAY_A );
537
538
	$stats    = array();
539
	$statuses = get_post_stati();
540
	if ( isset( $statuses['private'] ) && empty( $args['s'] ) ) {
541
		unset( $statuses['private'] );
542
	}
543
544
	foreach ( $statuses as $state ) {
545
		$stats[ $state ] = 0;
546
	}
547
548
	foreach ( (array) $count as $row ) {
549
550
		if ( 'private' == $row['post_status'] && empty( $args['s'] ) ) {
551
			continue;
552
		}
553
554
		$stats[ $row['post_status'] ] = $row['num_posts'];
555
	}
556
557
	$stats = (object) $stats;
558
	wp_cache_set( $cache_key, $stats, 'counts' );
559
560
	return $stats;
561
}
562
563
564
/**
565
 * Check For Existing Payment
566
 *
567
 * @since  1.0
568
 *
569
 * @param  int $payment_id Payment ID
570
 *
571
 * @return bool $exists True if payment exists, false otherwise.
572
 */
573
function give_check_for_existing_payment( $payment_id ) {
574
	$exists  = false;
575
	$payment = new Give_Payment( $payment_id );
576
577
	if ( $payment_id === $payment->ID && 'publish' === $payment->status ) {
578
		$exists = true;
579
	}
580
581
	return $exists;
582
}
583
584
/**
585
 * Get Payment Status
586
 *
587
 * @since 1.0
588
 *
589
 * @param WP_Post|Give_Payment $payment Payment object.
590
 * @param bool $return_label Whether to return the translated status label
591
 *                                           instead of status value. Default false.
592
 *
593
 * @return bool|mixed True if payment status exists, false otherwise.
594
 */
595
function give_get_payment_status( $payment, $return_label = false ) {
596
597
	if ( ! is_object( $payment ) || ! isset( $payment->post_status ) ) {
598
		return false;
599
	}
600
601
	$statuses = give_get_payment_statuses();
602
603
	if ( ! is_array( $statuses ) || empty( $statuses ) ) {
604
		return false;
605
	}
606
607
	// Get payment object if no already given.
608
	$payment = $payment instanceof Give_Payment ? $payment : new Give_Payment( $payment->ID );
609
610
	if ( array_key_exists( $payment->status, $statuses ) ) {
611
		if ( true === $return_label ) {
612
			// Return translated status label.
613
			return $statuses[ $payment->status ];
614
		} else {
615
			// Account that our 'publish' status is labeled 'Complete'
616
			$post_status = 'publish' == $payment->status ? 'Complete' : $payment->post_status;
617
618
			// Make sure we're matching cases, since they matter
619
			return array_search( strtolower( $post_status ), array_map( 'strtolower', $statuses ) );
620
		}
621
	}
622
623
	return false;
624
}
625
626
/**
627
 * Retrieves all available statuses for payments.
628
 *
629
 * @since  1.0
630
 *
631
 * @return array $payment_status All the available payment statuses.
632
 */
633
function give_get_payment_statuses() {
634
	$payment_statuses = array(
635
		'pending'     => __( 'Pending', 'give' ),
636
		'publish'     => __( 'Complete', 'give' ),
637
		'refunded'    => __( 'Refunded', 'give' ),
638
		'failed'      => __( 'Failed', 'give' ),
639
		'cancelled'   => __( 'Cancelled', 'give' ),
640
		'abandoned'   => __( 'Abandoned', 'give' ),
641
		'preapproval' => __( 'Pre-Approved', 'give' ),
642
		'processing'  => __( 'Processing', 'give' ),
643
		'revoked'     => __( 'Revoked', 'give' ),
644
	);
645
646
	return apply_filters( 'give_payment_statuses', $payment_statuses );
647
}
648
649
/**
650
 * Get Payment Status Keys
651
 *
652
 * Retrieves keys for all available statuses for payments
653
 *
654
 * @since  1.0
655
 *
656
 * @return array $payment_status All the available payment statuses.
657
 */
658
function give_get_payment_status_keys() {
659
	$statuses = array_keys( give_get_payment_statuses() );
660
	asort( $statuses );
661
662
	return array_values( $statuses );
663
}
664
665
/**
666
 * Get Earnings By Date
667
 *
668
 * @since  1.0
669
 *
670
 * @param  int $day Day number. Default is null.
671
 * @param  int $month_num Month number. Default is null.
672
 * @param  int $year Year number. Default is null.
673
 * @param  int $hour Hour number. Default is null.
674
 *
675
 * @return int $earnings  Earnings
0 ignored issues
show
Documentation introduced by
Should the return type not be double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
676
 */
677
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
678
679
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead.
680
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
681
682
	$args = array(
683
		'post_type'              => 'give_payment',
684
		'nopaging'               => true,
685
		'year'                   => $year,
686
		'monthnum'               => $month_num,
687
		'post_status'            => array( 'publish' ),
688
		'fields'                 => 'ids',
689
		'update_post_term_cache' => false,
690
	);
691
	if ( ! empty( $day ) ) {
692
		$args['day'] = $day;
693
	}
694
695
	if ( ! empty( $hour ) ) {
696
		$args['hour'] = $hour;
697
	}
698
699
	$args = apply_filters( 'give_get_earnings_by_date_args', $args );
700
	$key  = Give_Cache::get_key( 'give_stats', $args );
701
702
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
703
		$earnings = false;
704
	} else {
705
		$earnings = Give_Cache::get( $key );
706
	}
707
708
	if ( false === $earnings ) {
709
		$donations    = get_posts( $args );
710
		$earnings = 0;
711
		if ( $donations ) {
712
			$donations = implode( ',', $donations );
713
714
			$earnings = $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN ({$donations})" );
715
716
		}
717
		// Cache the results for one hour.
718
		Give_Cache::set( $key, $earnings, HOUR_IN_SECONDS );
719
	}
720
721
	return round( $earnings, 2 );
722
}
723
724
/**
725
 * Get Donations (sales) By Date
726
 *
727
 * @since  1.0
728
 *
729
 * @param  int $day Day number. Default is null.
730
 * @param  int $month_num Month number. Default is null.
731
 * @param  int $year Year number. Default is null.
732
 * @param  int $hour Hour number. Default is null.
733
 *
734
 * @return int $count     Sales
735
 */
736
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
737
738
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead.
739
	$args = array(
740
		'post_type'              => 'give_payment',
741
		'nopaging'               => true,
742
		'year'                   => $year,
743
		'fields'                 => 'ids',
744
		'post_status'            => array( 'publish' ),
745
		'update_post_meta_cache' => false,
746
		'update_post_term_cache' => false,
747
	);
748
749
	$show_free = apply_filters( 'give_sales_by_date_show_free', true, $args );
750
751
	if ( false === $show_free ) {
752
		$args['meta_query'] = array(
753
			array(
754
				'key'     => '_give_payment_total',
755
				'value'   => 0,
756
				'compare' => '>',
757
				'type'    => 'NUMERIC',
758
			),
759
		);
760
	}
761
762
	if ( ! empty( $month_num ) ) {
763
		$args['monthnum'] = $month_num;
764
	}
765
766
	if ( ! empty( $day ) ) {
767
		$args['day'] = $day;
768
	}
769
770
	if ( ! empty( $hour ) ) {
771
		$args['hour'] = $hour;
772
	}
773
774
	$args = apply_filters( 'give_get_sales_by_date_args', $args );
775
776
	$key = Give_Cache::get_key( 'give_stats', $args );
777
778
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
779
		$count = false;
780
	} else {
781
		$count = Give_Cache::get( $key );
782
	}
783
784
	if ( false === $count ) {
785
		$donations = new WP_Query( $args );
786
		$count = (int) $donations->post_count;
787
		// Cache the results for one hour.
788
		Give_Cache::set( $key, $count, HOUR_IN_SECONDS );
789
	}
790
791
	return $count;
792
}
793
794
/**
795
 * Checks whether a payment has been marked as complete.
796
 *
797
 * @since  1.0
798
 *
799
 * @param  int $payment_id Payment ID to check against.
800
 *
801
 * @return bool $ret True if complete, false otherwise.
802
 */
803
function give_is_payment_complete( $payment_id ) {
804
	$payment = new Give_Payment( $payment_id );
805
806
	$ret = false;
807
808
	if ( $payment->ID > 0 ) {
809
810
		if ( (int) $payment_id === (int) $payment->ID && 'publish' == $payment->status ) {
811
			$ret = true;
812
		}
813
	}
814
815
	return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
816
}
817
818
/**
819
 * Get Total Donations.
820
 *
821
 * @since  1.0
822
 *
823
 * @return int $count Total number of donations.
824
 */
825
function give_get_total_donations() {
826
827
	$payments = give_count_payments();
828
829
	return $payments->publish;
830
}
831
832
/**
833
 * Get Total Earnings
834
 *
835
 * @since  1.0
836
 *
837
 * @param bool $recalculate Recalculate earnings forcefully.
838
 *
839
 * @return float $total Total earnings.
840
 */
841
function give_get_total_earnings( $recalculate = false ) {
842
843
	$total = get_option( 'give_earnings_total', 0 );
844
845
	// Calculate total earnings.
846
	if ( ! $total || $recalculate ) {
847
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
848
849
		$total = (float) 0;
850
851
		$args = apply_filters( 'give_get_total_earnings_args', array(
852
			'offset' => 0,
853
			'number' => - 1,
854
			'status' => array( 'publish' ),
855
			'fields' => 'ids',
856
		) );
857
858
		$payments = give_get_payments( $args );
859
		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...
860
861
			/**
862
			 * If performing a donation, we need to skip the very last payment in the database,
863
			 * since it calls give_increase_total_earnings() on completion,
864
			 * which results in duplicated earnings for the very first donation.
865
			 */
866
			if ( did_action( 'give_update_payment_status' ) ) {
867
				array_pop( $payments );
868
			}
869
870
			if ( ! empty( $payments ) ) {
871
				$payments = implode( ',', $payments );
872
				$total    += $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN({$payments})" );
873
			}
874
		}
875
876
		update_option( 'give_earnings_total', $total, 'no' );
877
	}
878
879
	if ( $total < 0 ) {
880
		$total = 0; // Don't ever show negative earnings.
881
	}
882
883
	return apply_filters( 'give_total_earnings', round( $total, give_currency_decimal_filter() ) );
884
}
885
886
/**
887
 * Increase the Total Earnings
888
 *
889
 * @since  1.0
890
 *
891
 * @param  int $amount The amount you would like to increase the total earnings by.
892
 *                       Default is 0.
893
 *
894
 * @return float $total  Total earnings.
895
 */
896
function give_increase_total_earnings( $amount = 0 ) {
897
	$total = give_get_total_earnings();
898
	$total += $amount;
899
	update_option( 'give_earnings_total', $total );
900
901
	return $total;
902
}
903
904
/**
905
 * Decrease the Total Earnings
906
 *
907
 * @since 1.0
908
 *
909
 * @param int $amount The amount you would like to decrease the total earnings by.
910
 *
911
 * @return float $total Total earnings.
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
912
 */
913
function give_decrease_total_earnings( $amount = 0 ) {
914
	$total = give_get_total_earnings();
915
	$total -= $amount;
916
	if ( $total < 0 ) {
917
		$total = 0;
918
	}
919
	update_option( 'give_earnings_total', $total );
920
921
	return $total;
922
}
923
924
/**
925
 * Get Payment Meta for a specific Payment
926
 *
927
 * @since 1.0
928
 *
929
 * @param int $payment_id Payment ID.
930
 * @param string $meta_key The meta key to pull.
931
 * @param bool $single Pull single meta entry or as an object.
932
 *
933
 * @return mixed $meta Payment Meta.
934
 */
935
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
936
	$payment = new Give_Payment( $payment_id );
937
938
	return $payment->get_meta( $meta_key, $single );
939
}
940
941
/**
942
 * Update the meta for a payment
943
 *
944
 * @param  int $payment_id Payment ID.
945
 * @param  string $meta_key Meta key to update.
946
 * @param  string $meta_value Value to update to.
947
 * @param  string $prev_value Previous value.
948
 *
949
 * @return mixed Meta ID if successful, false if unsuccessful.
950
 */
951
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
952
	$payment = new Give_Payment( $payment_id );
953
954
	return $payment->update_meta( $meta_key, $meta_value, $prev_value );
955
}
956
957
/**
958
 * Get the user_info Key from Payment Meta
959
 *
960
 * @since 1.0
961
 *
962
 * @param int $payment_id Payment ID.
963
 *
964
 * @return array $user_info User Info Meta Values.
965
 */
966
function give_get_payment_meta_user_info( $payment_id ) {
967
	$payment = new Give_Payment( $payment_id );
968
969
	return $payment->user_info;
970
}
971
972
/**
973
 * Get the donations Key from Payment Meta
974
 *
975
 * Retrieves the form_id from a (Previously titled give_get_payment_meta_donations)
976
 *
977
 * @since 1.0
978
 *
979
 * @param int $payment_id Payment ID.
980
 *
981
 * @return int $form_id Form ID.
0 ignored issues
show
Documentation introduced by
Should the return type not be string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
982
 */
983
function give_get_payment_form_id( $payment_id ) {
984
	$payment = new Give_Payment( $payment_id );
985
986
	return $payment->form_id;
987
}
988
989
/**
990
 * Get the user email associated with a payment
991
 *
992
 * @since 1.0
993
 *
994
 * @param int $payment_id Payment ID.
995
 *
996
 * @return string $email User email.
997
 */
998
function give_get_payment_user_email( $payment_id ) {
999
	$payment = new Give_Payment( $payment_id );
1000
1001
	return $payment->email;
1002
}
1003
1004
/**
1005
 * Is the payment provided associated with a user account
1006
 *
1007
 * @since  1.3
1008
 *
1009
 * @param  int $payment_id The payment ID.
1010
 *
1011
 * @return bool $is_guest_payment If the payment is associated with a user (false) or not (true)
1012
 */
1013
function give_is_guest_payment( $payment_id ) {
1014
	$payment_user_id  = give_get_payment_user_id( $payment_id );
1015
	$is_guest_payment = ! empty( $payment_user_id ) && $payment_user_id > 0 ? false : true;
1016
1017
	return (bool) apply_filters( 'give_is_guest_payment', $is_guest_payment, $payment_id );
1018
}
1019
1020
/**
1021
 * Get the user ID associated with a payment
1022
 *
1023
 * @since 1.3
1024
 *
1025
 * @param int $payment_id Payment ID.
1026
 *
1027
 * @return int $user_id User ID.
1028
 */
1029
function give_get_payment_user_id( $payment_id ) {
1030
	$payment = new Give_Payment( $payment_id );
1031
1032
	return $payment->user_id;
1033
}
1034
1035
/**
1036
 * Get the donor ID associated with a payment.
1037
 *
1038
 * @since 1.0
1039
 *
1040
 * @param int $payment_id Payment ID.
1041
 *
1042
 * @return int $payment->customer_id Donor ID.
1043
 */
1044
function give_get_payment_donor_id( $payment_id ) {
1045
	$payment = new Give_Payment( $payment_id );
1046
1047
	return $payment->customer_id;
1048
}
1049
1050
/**
1051
 * Get the IP address used to make a donation
1052
 *
1053
 * @since 1.0
1054
 *
1055
 * @param int $payment_id Payment ID.
1056
 *
1057
 * @return string $ip User IP.
1058
 */
1059
function give_get_payment_user_ip( $payment_id ) {
1060
	$payment = new Give_Payment( $payment_id );
1061
1062
	return $payment->ip;
1063
}
1064
1065
/**
1066
 * Get the date a payment was completed
1067
 *
1068
 * @since 1.0
1069
 *
1070
 * @param int $payment_id Payment ID.
1071
 *
1072
 * @return string $date The date the payment was completed.
1073
 */
1074
function give_get_payment_completed_date( $payment_id = 0 ) {
1075
	$payment = new Give_Payment( $payment_id );
1076
1077
	return $payment->completed_date;
1078
}
1079
1080
/**
1081
 * Get the gateway associated with a payment
1082
 *
1083
 * @since 1.0
1084
 *
1085
 * @param int $payment_id Payment ID.
1086
 *
1087
 * @return string $gateway Gateway.
1088
 */
1089
function give_get_payment_gateway( $payment_id ) {
1090
	$payment = new Give_Payment( $payment_id );
1091
1092
	return $payment->gateway;
1093
}
1094
1095
/**
1096
 * Get the currency code a payment was made in
1097
 *
1098
 * @since 1.0
1099
 *
1100
 * @param int $payment_id Payment ID.
1101
 *
1102
 * @return string $currency The currency code.
1103
 */
1104
function give_get_payment_currency_code( $payment_id = 0 ) {
1105
	$payment = new Give_Payment( $payment_id );
1106
1107
	return $payment->currency;
1108
}
1109
1110
/**
1111
 * Get the currency name a payment was made in
1112
 *
1113
 * @since 1.0
1114
 *
1115
 * @param int $payment_id Payment ID.
1116
 *
1117
 * @return string $currency The currency name.
1118
 */
1119
function give_get_payment_currency( $payment_id = 0 ) {
1120
	$currency = give_get_payment_currency_code( $payment_id );
1121
1122
	return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
1123
}
1124
1125
/**
1126
 * Get the key for a donation
1127
 *
1128
 * @since 1.0
1129
 *
1130
 * @param int $payment_id Payment ID.
1131
 *
1132
 * @return string $key Donation key.
1133
 */
1134
function give_get_payment_key( $payment_id = 0 ) {
1135
	$payment = new Give_Payment( $payment_id );
1136
1137
	return $payment->key;
1138
}
1139
1140
/**
1141
 * Get the payment order number
1142
 *
1143
 * This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
1144
 *
1145
 * @since 1.0
1146
 *
1147
 * @param int $payment_id Payment ID.
1148
 *
1149
 * @return string $number Payment order number.
1150
 */
1151
function give_get_payment_number( $payment_id = 0 ) {
1152
	$payment = new Give_Payment( $payment_id );
1153
1154
	return $payment->number;
1155
}
1156
1157
/**
1158
 * Formats the payment number with the prefix and postfix
1159
 *
1160
 * @since  1.3
1161
 *
1162
 * @param  int $number The payment number to format.
1163
 *
1164
 * @return string      The formatted payment number.
1165
 */
1166
function give_format_payment_number( $number ) {
1167
1168
	if ( ! give_get_option( 'enable_sequential' ) ) {
1169
		return $number;
1170
	}
1171
1172
	if ( ! is_numeric( $number ) ) {
1173
		return $number;
1174
	}
1175
1176
	$prefix  = give_get_option( 'sequential_prefix' );
1177
	$number  = absint( $number );
1178
	$postfix = give_get_option( 'sequential_postfix' );
1179
1180
	$formatted_number = $prefix . $number . $postfix;
1181
1182
	return apply_filters( 'give_format_payment_number', $formatted_number, $prefix, $number, $postfix );
1183
}
1184
1185
/**
1186
 * Gets the next available order number
1187
 *
1188
 * This is used when inserting a new payment
1189
 *
1190
 * @since 1.0
1191
 * @return string $number The next available payment number.
1192
 */
1193
function give_get_next_payment_number() {
1194
1195
	if ( ! give_get_option( 'enable_sequential' ) ) {
1196
		return false;
1197
	}
1198
1199
	$number           = get_option( 'give_last_payment_number' );
1200
	$start            = give_get_option( 'sequential_start', 1 );
1201
	$increment_number = true;
1202
1203
	if ( false !== $number ) {
1204
1205
		if ( empty( $number ) ) {
1206
1207
			$number           = $start;
1208
			$increment_number = false;
1209
1210
		}
1211
	} else {
1212
1213
		// This case handles the first addition of the new option, as well as if it get's deleted for any reason.
1214
		$payments     = new Give_Payments_Query( array(
1215
			'number'  => 1,
1216
			'order'   => 'DESC',
1217
			'orderby' => 'ID',
1218
			'output'  => 'posts',
1219
			'fields'  => 'ids',
1220
		) );
1221
		$last_payment = $payments->get_payments();
1222
1223
		if ( ! empty( $last_payment ) ) {
1224
1225
			$number = give_get_payment_number( $last_payment[0] );
1226
1227
		}
1228
1229
		if ( ! empty( $number ) && $number !== (int) $last_payment[0] ) {
1230
1231
			$number = give_remove_payment_prefix_postfix( $number );
1232
1233
		} else {
1234
1235
			$number           = $start;
1236
			$increment_number = false;
1237
		}
1238
	}
1239
1240
	$increment_number = apply_filters( 'give_increment_payment_number', $increment_number, $number );
1241
1242
	if ( $increment_number ) {
1243
		$number ++;
1244
	}
1245
1246
	return apply_filters( 'give_get_next_payment_number', $number );
1247
}
1248
1249
/**
1250
 * Given a given a number, remove the pre/postfix
1251
 *
1252
 * @since  1.3
1253
 *
1254
 * @param  string $number The formatted Current Number to increment.
1255
 *
1256
 * @return string The new Payment number without prefix and postfix.
1257
 */
1258
function give_remove_payment_prefix_postfix( $number ) {
1259
1260
	$prefix  = give_get_option( 'sequential_prefix' );
1261
	$postfix = give_get_option( 'sequential_postfix' );
1262
1263
	// Remove prefix.
1264
	$number = preg_replace( '/' . $prefix . '/', '', $number, 1 );
1265
1266
	// Remove the postfix.
1267
	$length      = strlen( $number );
1268
	$postfix_pos = strrpos( $number, $postfix );
1269
	if ( false !== $postfix_pos ) {
1270
		$number = substr_replace( $number, '', $postfix_pos, $length );
1271
	}
1272
1273
	// Ensure it's a whole number.
1274
	$number = intval( $number );
1275
1276
	return apply_filters( 'give_remove_payment_prefix_postfix', $number, $prefix, $postfix );
1277
1278
}
1279
1280
1281
/**
1282
 * Get Payment Amount
1283
 *
1284
 * Get the fully formatted payment amount. The payment amount is retrieved using give_get_payment_amount() and is then
1285
 * sent through give_currency_filter() and  give_format_amount() to format the amount correctly.
1286
 *
1287
 * @since       1.0
1288
 *
1289
 * @param int $payment_id Payment ID.
1290
 *
1291
 * @return string $amount Fully formatted payment amount.
1292
 */
1293
function give_payment_amount( $payment_id = 0 ) {
1294
	$amount = give_get_payment_amount( $payment_id );
1295
1296
	return give_currency_filter( give_format_amount( $amount ), give_get_payment_currency_code( $payment_id ) );
1297
}
1298
1299
/**
1300
 * Get the amount associated with a payment
1301
 *
1302
 * @access public
1303
 * @since  1.0
1304
 *
1305
 * @param int $payment_id Payment ID.
1306
 *
1307
 * @return mixed
1308
 */
1309
function give_get_payment_amount( $payment_id ) {
1310
1311
	$payment = new Give_Payment( $payment_id );
1312
1313
	return apply_filters( 'give_payment_amount', floatval( $payment->total ), $payment_id );
1314
}
1315
1316
/**
1317
 * Payment Subtotal
1318
 *
1319
 * Retrieves subtotal for payment and then returns a full formatted amount. This
1320
 * function essentially calls give_get_payment_subtotal()
1321
 *
1322
 * @since 1.5
1323
 *
1324
 * @param int $payment_id Payment ID.
1325
 *
1326
 * @see   give_get_payment_subtotal()
1327
 *
1328
 * @return array Fully formatted payment subtotal.
1329
 */
1330
function give_payment_subtotal( $payment_id = 0 ) {
1331
	$subtotal = give_get_payment_subtotal( $payment_id );
1332
1333
	return give_currency_filter( give_format_amount( $subtotal ), give_get_payment_currency_code( $payment_id ) );
1334
}
1335
1336
/**
1337
 * Get Payment Subtotal
1338
 *
1339
 * Retrieves subtotal for payment and then returns a non formatted amount.
1340
 *
1341
 * @since 1.5
1342
 *
1343
 * @param int $payment_id Payment ID.
1344
 *
1345
 * @return float $subtotal Subtotal for payment (non formatted).
1346
 */
1347
function give_get_payment_subtotal( $payment_id = 0 ) {
1348
	$payment = new Give_Payment( $payment_id );
1349
1350
	return $payment->subtotal;
1351
}
1352
1353
/**
1354
 * Retrieves the donation ID
1355
 *
1356
 * @since  1.0
1357
 *
1358
 * @param int $payment_id Payment ID.
1359
 *
1360
 * @return string The donation ID.
1361
 */
1362
function give_get_payment_transaction_id( $payment_id = 0 ) {
1363
	$payment = new Give_Payment( $payment_id );
1364
1365
	return $payment->transaction_id;
1366
}
1367
1368
/**
1369
 * Sets a Transaction ID in post meta for the given Payment ID.
1370
 *
1371
 * @since  1.0
1372
 *
1373
 * @param int $payment_id Payment ID.
1374
 * @param string $transaction_id The transaction ID from the gateway.
1375
 *
1376
 * @return bool|mixed
1377
 */
1378
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1379
1380
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1381
		return false;
1382
	}
1383
1384
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1385
1386
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1387
}
1388
1389
/**
1390
 * Retrieve the donation ID based on the key
1391
 *
1392
 * @since 1.0
1393
 * @global object $wpdb Used to query the database using the WordPress Database API.
1394
 *
1395
 * @param string $key the key to search for.
1396
 *
1397
 * @return int $purchase Donation ID.
1398
 */
1399
function give_get_purchase_id_by_key( $key ) {
1400
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1401
1402
	$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 ) );
1403
1404
	if ( $purchase != null ) {
1405
		return $purchase;
1406
	}
1407
1408
	return 0;
1409
}
1410
1411
1412
/**
1413
 * Retrieve the donation ID based on the transaction ID
1414
 *
1415
 * @since 1.3
1416
 * @global object $wpdb Used to query the database using the WordPress Database API.
1417
 *
1418
 * @param string $key The transaction ID to search for.
1419
 *
1420
 * @return int $purchase Donation ID.
1421
 */
1422
function give_get_purchase_id_by_transaction_id( $key ) {
1423
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1424
1425
	$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 ) );
1426
1427
	if ( $purchase != null ) {
1428
		return $purchase;
1429
	}
1430
1431
	return 0;
1432
}
1433
1434
/**
1435
 * Retrieve all notes attached to a donation
1436
 *
1437
 * @since 1.0
1438
 *
1439
 * @param int $payment_id The donation ID to retrieve notes for.
1440
 * @param string $search Search for notes that contain a search term.
1441
 *
1442
 * @return array $notes Donation Notes
1443
 */
1444
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1445
1446
	if ( empty( $payment_id ) && empty( $search ) ) {
1447
		return false;
1448
	}
1449
1450
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1451
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1452
1453
	$notes = get_comments( array( 'post_id' => $payment_id, 'order' => 'ASC', 'search' => $search ) );
1454
1455
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1456
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1457
1458
	return $notes;
1459
}
1460
1461
1462
/**
1463
 * Add a note to a payment
1464
 *
1465
 * @since 1.0
1466
 *
1467
 * @param int $payment_id The payment ID to store a note for.
1468
 * @param string $note The note to store.
1469
 *
1470
 * @return int The new note ID
1471
 */
1472
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1473
	if ( empty( $payment_id ) ) {
1474
		return false;
1475
	}
1476
1477
	/**
1478
	 * Fires before inserting payment note.
1479
	 *
1480
	 * @since 1.0
1481
	 *
1482
	 * @param int $payment_id Payment ID.
1483
	 * @param string $note The note.
1484
	 */
1485
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1486
1487
	$note_id = wp_insert_comment( wp_filter_comment( array(
1488
		'comment_post_ID'      => $payment_id,
1489
		'comment_content'      => $note,
1490
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1491
		'comment_date'         => current_time( 'mysql' ),
1492
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1493
		'comment_approved'     => 1,
1494
		'comment_parent'       => 0,
1495
		'comment_author'       => '',
1496
		'comment_author_IP'    => '',
1497
		'comment_author_url'   => '',
1498
		'comment_author_email' => '',
1499
		'comment_type'         => 'give_payment_note',
1500
1501
	) ) );
1502
1503
	/**
1504
	 * Fires after payment note inserted.
1505
	 *
1506
	 * @since 1.0
1507
	 *
1508
	 * @param int $note_id Note ID.
1509
	 * @param int $payment_id Payment ID.
1510
	 * @param string $note The note.
1511
	 */
1512
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1513
1514
	return $note_id;
1515
}
1516
1517
/**
1518
 * Deletes a payment note
1519
 *
1520
 * @since 1.0
1521
 *
1522
 * @param int $comment_id The comment ID to delete.
1523
 * @param int $payment_id The payment ID the note is connected to.
1524
 *
1525
 * @return bool True on success, false otherwise.
1526
 */
1527
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1528
	if ( empty( $comment_id ) ) {
1529
		return false;
1530
	}
1531
1532
	/**
1533
	 * Fires before deleting donation note.
1534
	 *
1535
	 * @since 1.0
1536
	 *
1537
	 * @param int $comment_id Note ID.
1538
	 * @param int $payment_id Payment ID.
1539
	 */
1540
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1541
1542
	$ret = wp_delete_comment( $comment_id, true );
1543
1544
	/**
1545
	 * Fires after donation note deleted.
1546
	 *
1547
	 * @since 1.0
1548
	 *
1549
	 * @param int $comment_id Note ID.
1550
	 * @param int $payment_id Payment ID.
1551
	 */
1552
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1553
1554
	return $ret;
1555
}
1556
1557
/**
1558
 * Gets the payment note HTML
1559
 *
1560
 * @since 1.0
1561
 *
1562
 * @param object|int $note The comment object or ID.
1563
 * @param int $payment_id The payment ID the note is connected to.
1564
 *
1565
 * @return string
1566
 */
1567
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1568
1569
	if ( is_numeric( $note ) ) {
1570
		$note = get_comment( $note );
1571
	}
1572
1573
	if ( ! empty( $note->user_id ) ) {
1574
		$user = get_userdata( $note->user_id );
1575
		$user = $user->display_name;
1576
	} else {
1577
		$user = esc_html__( 'System', 'give' );
1578
	}
1579
1580
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1581
1582
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1583
		'give-action' => 'delete_payment_note',
1584
		'note_id'     => $note->comment_ID,
1585
		'payment_id'  => $payment_id,
1586
	) ),
1587
		'give_delete_payment_note_' . $note->comment_ID
1588
	);
1589
1590
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1591
	$note_html .= '<p>';
1592
	$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/>';
1593
	$note_html .= $note->comment_content;
1594
	$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="' . esc_attr__( 'Delete this donation note.', 'give' ) . '">' . esc_html__( 'Delete', 'give' ) . '</a>';
1595
	$note_html .= '</p>';
1596
	$note_html .= '</div>';
1597
1598
	return $note_html;
1599
1600
}
1601
1602
/**
1603
 * Exclude notes (comments) on give_payment post type from showing in Recent
1604
 * Comments widgets
1605
 *
1606
 * @since 1.0
1607
 *
1608
 * @param object $query WordPress Comment Query Object.
1609
 *
1610
 * @return void
1611
 */
1612
function give_hide_payment_notes( $query ) {
1613
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1614
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1615
		if ( ! is_array( $types ) ) {
1616
			$types = array( $types );
1617
		}
1618
		$types[]                           = 'give_payment_note';
1619
		$query->query_vars['type__not_in'] = $types;
1620
	}
1621
}
1622
1623
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1624
1625
/**
1626
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1627
 *
1628
 * @since 1.0
1629
 *
1630
 * @param array $clauses Comment clauses for comment query.
1631
 * @param object $wp_comment_query WordPress Comment Query Object.
1632
 *
1633
 * @return array $clauses Updated comment clauses.
1634
 */
1635
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...
1636
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1637
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1638
	}
1639
1640
	return $clauses;
1641
}
1642
1643
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1644
1645
1646
/**
1647
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1648
 *
1649
 * @since 1.0
1650
 *
1651
 * @param string $where
1652
 * @param object $wp_comment_query WordPress Comment Query Object.
1653
 *
1654
 * @return string $where
1655
 */
1656
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...
1657
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1658
1659
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1660
1661
	return $where;
1662
}
1663
1664
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1665
1666
1667
/**
1668
 * Remove Give Comments from the wp_count_comments function
1669
 *
1670
 * @access public
1671
 * @since  1.0
1672
 *
1673
 * @param array $stats (empty from core filter).
1674
 * @param int $post_id Post ID.
1675
 *
1676
 * @return array Array of comment counts.
1677
 */
1678
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1679
	global $wpdb, $pagenow;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1680
1681
	if ( 'index.php' != $pagenow ) {
1682
		return $stats;
1683
	}
1684
1685
	$post_id = (int) $post_id;
1686
1687
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1688
		return $stats;
1689
	}
1690
1691
	$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
1692
1693
	if ( false !== $stats ) {
1694
		return $stats;
1695
	}
1696
1697
	$where = 'WHERE comment_type != "give_payment_note"';
1698
1699
	if ( $post_id > 0 ) {
1700
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1701
	}
1702
1703
	$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
1704
1705
	$total    = 0;
1706
	$approved = array(
1707
		'0'            => 'moderated',
1708
		'1'            => 'approved',
1709
		'spam'         => 'spam',
1710
		'trash'        => 'trash',
1711
		'post-trashed' => 'post-trashed',
1712
	);
1713
	foreach ( (array) $count as $row ) {
1714
		// Don't count post-trashed toward totals.
1715
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1716
			$total += $row['num_comments'];
1717
		}
1718
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1719
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1720
		}
1721
	}
1722
1723
	$stats['total_comments'] = $total;
1724
	foreach ( $approved as $key ) {
1725
		if ( empty( $stats[ $key ] ) ) {
1726
			$stats[ $key ] = 0;
1727
		}
1728
	}
1729
1730
	$stats = (object) $stats;
1731
	wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
1732
1733
	return $stats;
1734
}
1735
1736
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1737
1738
1739
/**
1740
 * Filter where older than one week
1741
 *
1742
 * @access public
1743
 * @since  1.0
1744
 *
1745
 * @param string $where Where clause.
1746
 *
1747
 * @return string $where Modified where clause.
1748
 */
1749
function give_filter_where_older_than_week( $where = '' ) {
1750
	// Payments older than one week.
1751
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1752
	$where .= " AND post_date <= '{$start}'";
1753
1754
	return $where;
1755
}
1756
1757
1758
/**
1759
 * Get Payment Form ID.
1760
 *
1761
 * Retrieves the form title and appends the level name if present.
1762
 *
1763
 * @since 1.5
1764
 *
1765
 * @param array $payment_meta Payment meta data.
1766
 * @param bool $only_level If set to true will only return the level name if multi-level enabled.
1767
 * @param string $separator The separator between the .
1768
 *
1769
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1770
 */
1771
function give_get_payment_form_title( $payment_meta, $only_level = false, $separator = '' ) {
1772
1773
	$form_id    = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
1774
	$price_id   = isset( $payment_meta['price_id'] ) ? $payment_meta['price_id'] : null;
1775
	$form_title = isset( $payment_meta['form_title'] ) ? $payment_meta['form_title'] : '';
1776
1777
	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...
1778
		$form_title = '';
1779
	}
1780
1781
	//If multi-level, append to the form title.
1782
	if ( give_has_variable_prices( $form_id ) ) {
1783
1784
		//Only add separator if there is a form title.
1785
		if ( ! empty( $form_title ) ) {
1786
			$form_title .= ' ' . $separator . ' ';
1787
		}
1788
1789
		$form_title .= '<span class="donation-level-text-wrap">';
1790
1791
		if ( $price_id == 'custom' ) {
1792
			$custom_amount_text = give_get_meta( $form_id, '_give_custom_amount_text', true );
1793
			$form_title         .= ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1794
		} else {
1795
			$form_title .= give_get_price_option_name( $form_id, $price_id );
1796
		}
1797
1798
		$form_title .= '</span>';
1799
1800
	}
1801
1802
	return apply_filters( 'give_get_payment_form_title', $form_title, $payment_meta );
1803
1804
}
1805
1806
/**
1807
 * Get Price ID
1808
 *
1809
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1810
 *
1811
 * @param int $form_id Form ID.
1812
 * @param string $price Price ID.
1813
 *
1814
 * @return string $price_id
1815
 */
1816
function give_get_price_id( $form_id, $price ) {
1817
1818
	$price_id = 0;
1819
1820
	if ( give_has_variable_prices( $form_id ) ) {
1821
1822
		$levels = maybe_unserialize( give_get_meta( $form_id, '_give_donation_levels', true ) );
1823
1824
		foreach ( $levels as $level ) {
1825
1826
			$level_amount = (float) give_sanitize_amount( $level['_give_amount'] );
1827
1828
			// Check that this indeed the recurring price.
1829
			if ( $level_amount == $price ) {
1830
1831
				$price_id = $level['_give_id']['level_id'];
1832
1833
			}
1834
		}
1835
	}
1836
1837
	return $price_id;
1838
1839
}
1840
1841
/**
1842
 * Get/Print give form dropdown html
1843
 *
1844
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1845
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1846
 *
1847
 * @since 1.6
1848
 *
1849
 * @param array $args Arguments for form dropdown.
1850
 * @param bool $echo This parameter decides if print form dropdown html output or not.
1851
 *
1852
 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1853
 */
1854
function give_get_form_dropdown( $args = array(), $echo = false ) {
1855
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1856
1857
	if ( ! $echo ) {
1858
		return $form_dropdown_html;
1859
	}
1860
1861
	echo $form_dropdown_html;
1862
}
1863
1864
/**
1865
 * Get/Print give form variable price dropdown html
1866
 *
1867
 * @since 1.6
1868
 *
1869
 * @param array $args Arguments for form dropdown.
1870
 * @param bool $echo This parameter decide if print form dropdown html output or not.
1871
 *
1872
 * @return string|bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1873
 */
1874
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1875
1876
	// Check for give form id.
1877
	if ( empty( $args['id'] ) ) {
1878
		return false;
1879
	}
1880
1881
	$form = new Give_Donate_Form( $args['id'] );
1882
1883
	// Check if form has variable prices or not.
1884
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1885
		return false;
1886
	}
1887
1888
	$variable_prices        = $form->get_prices();
1889
	$variable_price_options = array();
1890
1891
	// Check if multi donation form support custom donation or not.
1892
	if ( $form->is_custom_price_mode() ) {
1893
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1894
	}
1895
1896
	// Get variable price and ID from variable price array.
1897
	foreach ( $variable_prices as $variable_price ) {
1898
		$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'] ) );
1899
	}
1900
1901
	// Update options.
1902
	$args = array_merge( $args, array( 'options' => $variable_price_options ) );
1903
1904
	// Generate select html.
1905
	$form_dropdown_html = Give()->html->select( $args );
1906
1907
	if ( ! $echo ) {
1908
		return $form_dropdown_html;
1909
	}
1910
1911
	echo $form_dropdown_html;
1912
}
1913
1914
/**
1915
 * Get the price_id from the payment meta.
1916
 *
1917
 * Some gateways use `give_price_id` and others were using just `price_id`;
1918
 * This checks for the difference and falls back to retrieving it from the form as a last resort.
1919
 *
1920
 * @since 1.8.6
1921
 *
1922
 * @param $payment_meta
1923
 *
1924
 * @return string
1925
 */
1926
function give_get_payment_meta_price_id( $payment_meta ) {
1927
1928
	if ( isset( $payment_meta['give_price_id'] ) ) {
1929
		$price_id = $payment_meta['give_price_id'];
1930
	} elseif ( isset( $payment_meta['price_id'] ) ) {
1931
		$price_id = $payment_meta['price_id'];
1932
	} else {
1933
		$price_id = give_get_price_id( $payment_meta['give_form_id'], $payment_meta['price'] );
1934
	}
1935
1936
	return apply_filters( 'give_get_payment_meta_price_id', $price_id );
1937
1938
}