Completed
Push — hotfix/filter ( cd512d )
by Ravinder
19:07
created

functions.php ➔ give_create_payment()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 1
dl 0
loc 32
rs 8.8571
c 0
b 0
f 0
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 object $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 ) {
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 ) {
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   = isset( $payment_data['give_price_id'] ) ? $payment_data['give_price_id'] : give_get_price_id( $payment_data['give_form_id'], $payment_data['price'] );
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
		'fees'     => isset( $payment_data['fees'] ) ? $payment_data['fees'] : array(),
172
	);
173
174
	$payment->add_donation( $payment->form_id, $args );
175
176
	// Set date if present.
177
	if ( isset( $payment_data['post_date'] ) ) {
178
		$payment->date = $payment_data['post_date'];
179
	}
180
181
	// Handle sequential payments.
182
	if ( give_get_option( 'enable_sequential' ) ) {
183
		$number          = give_get_next_payment_number();
184
		$payment->number = give_format_payment_number( $number );
185
		update_option( 'give_last_payment_number', $number );
186
	}
187
188
	// Clear the user's donation cache.
189
	delete_transient( 'give_user_' . $payment_data['user_info']['id'] . '_purchases' );
190
191
	// Save payment.
192
	$payment->save();
193
194
	/**
195
	 * Fires while inserting payments.
196
	 *
197
	 * @since 1.0
198
	 *
199
	 * @param int   $payment_id   The payment ID.
200
	 * @param array $payment_data Arguments passed.
201
	 */
202
	do_action( 'give_insert_payment', $payment->ID, $payment_data );
203
204
	// Return payment ID upon success.
205
	if ( ! empty( $payment->ID ) ) {
206
		return $payment->ID;
207
	}
208
209
	// Return false if no payment was inserted.
210
	return false;
211
212
}
213
214
/**
215
 * Create payment.
216
 *
217
 * @param $payment_data
218
 *
219
 * @return bool|int
220
 */
221
function give_create_payment( $payment_data ) {
222
223
	$form_id  = intval( $payment_data['post_data']['give-form-id'] );
224
	$price_id = isset( $payment_data['post_data']['give-price-id'] ) ? $payment_data['post_data']['give-price-id'] : '';
225
226
	// Collect payment data.
227
	$insert_payment_data = array(
228
		'price'           => $payment_data['price'],
229
		'give_form_title' => $payment_data['post_data']['give-form-title'],
230
		'give_form_id'    => $form_id,
231
		'give_price_id'   => $price_id,
232
		'date'            => $payment_data['date'],
233
		'user_email'      => $payment_data['user_email'],
234
		'purchase_key'    => $payment_data['purchase_key'],
235
		'currency'        => give_get_currency(),
236
		'user_info'       => $payment_data['user_info'],
237
		'status'          => 'pending',
238
		'gateway'         => 'paypal',
239
	);
240
241
	/**
242
	 * Filter the payment params.
243
	 *
244
	 * @since 1.8
245
	 *
246
	 * @param array $insert_payment_data
247
	 */
248
	$insert_payment_data = apply_filters( 'give_create_filter', $insert_payment_data );
249
250
	// Record the pending payment.
251
	return give_insert_payment( $insert_payment_data );
252
}
253
254
/**
255
 * Updates a payment status.
256
 *
257
 * @since  1.0
258
 *
259
 * @param  int    $payment_id Payment ID.
260
 * @param  string $new_status New Payment Status. Default is 'publish'.
261
 *
262
 * @return bool
263
 */
264
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
265
266
	$payment         = new Give_Payment( $payment_id );
267
	$payment->status = $new_status;
268
	$updated         = $payment->save();
269
270
	return $updated;
271
}
272
273
274
/**
275
 * Deletes a Donation
276
 *
277
 * @since  1.0
278
 * @global      $give_logs
279
 *
280
 * @param  int  $payment_id      Payment ID (default: 0).
281
 * @param  bool $update_customer If we should update the customer stats (default:true).
282
 *
283
 * @return void
284
 */
285
function give_delete_purchase( $payment_id = 0, $update_customer = true ) {
286
	global $give_logs;
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...
287
288
	$payment     = new Give_Payment( $payment_id );
289
	$amount      = give_get_payment_amount( $payment_id );
290
	$status      = $payment->post_status;
291
	$customer_id = give_get_payment_customer_id( $payment_id );
292
	$customer    = new Give_Customer( $customer_id );
293
294
	// Only undo donations that aren't these statuses.
295
	$dont_undo_statuses = apply_filters( 'give_undo_purchase_statuses', array(
296
		'pending',
297
		'cancelled',
298
	) );
299
300
	if ( ! in_array( $status, $dont_undo_statuses ) ) {
301
		give_undo_purchase( false, $payment_id );
302
	}
303
304
	if ( $status == 'publish' ) {
305
306
		// Only decrease earnings if they haven't already been decreased (or were never increased for this payment).
307
		give_decrease_total_earnings( $amount );
308
		// Clear the This Month earnings (this_monththis_month is NOT a typo).
309
		delete_transient( md5( 'give_earnings_this_monththis_month' ) );
310
311
		if ( $customer->id && $update_customer ) {
312
313
			// Decrement the stats for the donor.
314
			$customer->decrease_purchase_count();
315
			$customer->decrease_value( $amount );
316
317
		}
318
	}
319
320
	/**
321
	 * Fires before deleting payment.
322
	 *
323
	 * @since 1.0
324
	 *
325
	 * @param int $payment_id Payment ID.
326
	 */
327
	do_action( 'give_payment_delete', $payment_id );
328
329
	if ( $customer->id && $update_customer ) {
330
331
		// Remove the payment ID from the donor.
332
		$customer->remove_payment( $payment_id );
333
334
	}
335
336
	// Remove the payment.
337
	wp_delete_post( $payment_id, true );
338
339
	// Remove related sale log entries.
340
	$give_logs->delete_logs(
341
		null,
342
		'sale',
343
		array(
344
			array(
345
				'key'   => '_give_log_payment_id',
346
				'value' => $payment_id,
347
			),
348
		)
349
	);
350
351
	/**
352
	 * Fires after payment deleted.
353
	 *
354
	 * @since 1.0
355
	 *
356
	 * @param int $payment_id Payment ID.
357
	 */
358
	do_action( 'give_payment_deleted', $payment_id );
359
}
360
361
/**
362
 * Undo Donation
363
 *
364
 * Undoes a donation, including the decrease of donations and earning stats.
365
 * Used for when refunding or deleting a donation.
366
 *
367
 * @since  1.0
368
 *
369
 * @param  int|bool $form_id    Form ID (default: false).
370
 * @param  int      $payment_id Payment ID.
371
 *
372
 * @return void
373
 */
374
function give_undo_purchase( $form_id = false, $payment_id ) {
375
376
	if ( ! empty( $form_id ) ) {
377
		$form_id = false;
378
		_give_deprected_argument( 'form_id', 'give_undo_purchase', '1.5' );
379
	}
380
381
	$payment = new Give_Payment( $payment_id );
382
383
	$maybe_decrease_earnings = apply_filters( 'give_decrease_earnings_on_undo', true, $payment, $payment->form_id );
384
	if ( true === $maybe_decrease_earnings ) {
385
		// Decrease earnings.
386
		give_decrease_earnings( $payment->form_id, $payment->total );
387
	}
388
389
	$maybe_decrease_sales = apply_filters( 'give_decrease_sales_on_undo', true, $payment, $payment->form_id );
390
	if ( true === $maybe_decrease_sales ) {
391
		// Decrease donation count.
392
		give_decrease_purchase_count( $payment->form_id );
393
	}
394
395
}
396
397
398
/**
399
 * Count Payments
400
 *
401
 * Returns the total number of payments recorded.
402
 *
403
 * @since  1.0
404
 *
405
 * @param  array $args Arguments passed.
406
 *
407
 * @return array $count Number of payments sorted by payment status.
408
 */
409
function give_count_payments( $args = array() ) {
410
411
	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...
412
413
	$defaults = array(
414
		'user'       => null,
415
		's'          => null,
416
		'start-date' => null,
417
		'end-date'   => null,
418
		'form_id'    => null,
419
	);
420
421
	$args = wp_parse_args( $args, $defaults );
422
423
	$select = 'SELECT p.post_status,count( * ) AS num_posts';
424
	$join   = '';
425
	$where  = "WHERE p.post_type = 'give_payment'";
426
427
	// Count payments for a specific user.
428
	if ( ! empty( $args['user'] ) ) {
429
430
		if ( is_email( $args['user'] ) ) {
431
			$field = 'email';
432
		} elseif ( is_numeric( $args['user'] ) ) {
433
			$field = 'id';
434
		} else {
435
			$field = '';
436
		}
437
438
		$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
439
440
		if ( ! empty( $field ) ) {
441
			$where .= "
442
				AND m.meta_key = '_give_payment_user_{$field}'
443
				AND m.meta_value = '{$args['user']}'";
444
		}
445
446
		// Count payments for a search.
447
	} elseif ( ! empty( $args['s'] ) ) {
448
449
		if ( is_email( $args['s'] ) || strlen( $args['s'] ) == 32 ) {
450
451
			if ( is_email( $args['s'] ) ) {
452
				$field = '_give_payment_user_email';
453
			} else {
454
				$field = '_give_payment_purchase_key';
455
			}
456
457
			$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
458
			$where .= $wpdb->prepare( '
459
                AND m.meta_key = %s
460
                AND m.meta_value = %s',
461
				$field,
462
				$args['s']
463
			);
464
465
		} elseif ( '#' == substr( $args['s'], 0, 1 ) ) {
466
467
			$search = str_replace( '#:', '', $args['s'] );
468
			$search = str_replace( '#', '', $search );
469
470
			$select = 'SELECT p2.post_status,count( * ) AS num_posts ';
471
			$join   = "LEFT JOIN $wpdb->postmeta m ON m.meta_key = '_give_log_payment_id' AND m.post_id = p.ID ";
472
			$join .= "INNER JOIN $wpdb->posts p2 ON m.meta_value = p2.ID ";
473
			$where = "WHERE p.post_type = 'give_log' ";
474
			$where .= $wpdb->prepare( 'AND p.post_parent = %d} ', $search );
475
476
		} elseif ( is_numeric( $args['s'] ) ) {
477
478
			$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
479
			$where .= $wpdb->prepare( "
480
				AND m.meta_key = '_give_payment_user_id'
481
				AND m.meta_value = %d",
482
				$args['s']
483
			);
484
485
		} else {
486
			$search = $wpdb->esc_like( $args['s'] );
487
			$search = '%' . $search . '%';
488
489
			$where .= $wpdb->prepare( 'AND ((p.post_title LIKE %s) OR (p.post_content LIKE %s))', $search, $search );
490
		}
491
	}
492
493
	if ( ! empty( $args['form_id'] ) && is_numeric( $args['form_id'] ) ) {
494
495
		$where .= $wpdb->prepare( ' AND p.post_parent = %d', $args['form_id'] );
496
497
	}
498
	// Limit payments count by date.
499
	if ( ! empty( $args['start-date'] ) && false !== strpos( $args['start-date'], '/' ) ) {
500
501
		$date_parts = explode( '/', $args['start-date'] );
502
		$month      = ! empty( $date_parts[0] ) && is_numeric( $date_parts[0] ) ? $date_parts[0] : 0;
503
		$day        = ! empty( $date_parts[1] ) && is_numeric( $date_parts[1] ) ? $date_parts[1] : 0;
504
		$year       = ! empty( $date_parts[2] ) && is_numeric( $date_parts[2] ) ? $date_parts[2] : 0;
505
506
		$is_date = checkdate( $month, $day, $year );
507
		if ( false !== $is_date ) {
508
509
			$date = new DateTime( $args['start-date'] );
510
			$where .= $wpdb->prepare( " AND p.post_date >= '%s'", $date->format( 'Y-m-d' ) );
511
512
		}
513
514
		// Fixes an issue with the payments list table counts when no end date is specified (partiy with stats class).
515
		if ( empty( $args['end-date'] ) ) {
516
			$args['end-date'] = $args['start-date'];
517
		}
518
	}
519
520
	if ( ! empty( $args['end-date'] ) && false !== strpos( $args['end-date'], '/' ) ) {
521
522
		$date_parts = explode( '/', $args['end-date'] );
523
524
		$month = ! empty( $date_parts[0] ) ? $date_parts[0] : 0;
525
		$day   = ! empty( $date_parts[1] ) ? $date_parts[1] : 0;
526
		$year  = ! empty( $date_parts[2] ) ? $date_parts[2] : 0;
527
528
		$is_date = checkdate( $month, $day, $year );
529
		if ( false !== $is_date ) {
530
531
			$date = new DateTime( $args['end-date'] );
532
			$where .= $wpdb->prepare( " AND p.post_date <= '%s'", $date->format( 'Y-m-d' ) );
533
534
		}
535
	}
536
537
	$where = apply_filters( 'give_count_payments_where', $where );
538
	$join  = apply_filters( 'give_count_payments_join', $join );
539
540
	$query = "$select
541
		FROM $wpdb->posts p
542
		$join
543
		$where
544
		GROUP BY p.post_status
545
	";
546
547
	$cache_key = md5( $query );
548
549
	$count = wp_cache_get( $cache_key, 'counts' );
550
	if ( false !== $count ) {
551
		return $count;
552
	}
553
554
	$count = $wpdb->get_results( $query, ARRAY_A );
555
556
	$stats    = array();
557
	$statuses = get_post_stati();
558
	if ( isset( $statuses['private'] ) && empty( $args['s'] ) ) {
559
		unset( $statuses['private'] );
560
	}
561
562
	foreach ( $statuses as $state ) {
563
		$stats[ $state ] = 0;
564
	}
565
566
	foreach ( (array) $count as $row ) {
567
568
		if ( 'private' == $row['post_status'] && empty( $args['s'] ) ) {
569
			continue;
570
		}
571
572
		$stats[ $row['post_status'] ] = $row['num_posts'];
573
	}
574
575
	$stats = (object) $stats;
576
	wp_cache_set( $cache_key, $stats, 'counts' );
577
578
	return $stats;
579
}
580
581
582
/**
583
 * Check For Existing Payment
584
 *
585
 * @since  1.0
586
 *
587
 * @param  int $payment_id Payment ID
588
 *
589
 * @return bool $exists True if payment exists, false otherwise.
590
 */
591
function give_check_for_existing_payment( $payment_id ) {
592
	$exists  = false;
593
	$payment = new Give_Payment( $payment_id );
594
595
	if ( $payment_id === $payment->ID && 'publish' === $payment->status ) {
596
		$exists = true;
597
	}
598
599
	return $exists;
600
}
601
602
/**
603
 * Get Payment Status
604
 *
605
 * @since 1.0
606
 *
607
 * @param WP_Post|Give_Payment $payment      Payment object.
608
 * @param bool                 $return_label Whether to return the translated status label
609
 *                                           instead of status value. Default false.
610
 *
611
 * @return bool|mixed True if payment status exists, false otherwise.
612
 */
613
function give_get_payment_status( $payment, $return_label = false ) {
614
615
	if ( ! is_object( $payment ) || ! isset( $payment->post_status ) ) {
616
		return false;
617
	}
618
619
	$statuses = give_get_payment_statuses();
620
621
	if ( ! is_array( $statuses ) || empty( $statuses ) ) {
622
		return false;
623
	}
624
625
	// Get payment object if no already given.
626
	$payment = $payment instanceof Give_Payment ? $payment : new Give_Payment( $payment->ID );
627
628
	if ( array_key_exists( $payment->status, $statuses ) ) {
629
		if ( true === $return_label ) {
630
			// Return translated status label.
631
			return $statuses[ $payment->status ];
632
		} else {
633
			// Account that our 'publish' status is labeled 'Complete'
634
			$post_status = 'publish' == $payment->status ? 'Complete' : $payment->post_status;
635
636
			// Make sure we're matching cases, since they matter
637
			return array_search( strtolower( $post_status ), array_map( 'strtolower', $statuses ) );
638
		}
639
	}
640
641
	return false;
642
}
643
644
/**
645
 * Retrieves all available statuses for payments.
646
 *
647
 * @since  1.0
648
 *
649
 * @return array $payment_status All the available payment statuses.
650
 */
651
function give_get_payment_statuses() {
652
	$payment_statuses = array(
653
		'pending'     => __( 'Pending', 'give' ),
654
		'publish'     => __( 'Complete', 'give' ),
655
		'refunded'    => __( 'Refunded', 'give' ),
656
		'failed'      => __( 'Failed', 'give' ),
657
		'cancelled'   => __( 'Cancelled', 'give' ),
658
		'abandoned'   => __( 'Abandoned', 'give' ),
659
		'preapproval' => __( 'Pre-Approved', 'give' ),
660
		'revoked'     => __( 'Revoked', 'give' ),
661
	);
662
663
	return apply_filters( 'give_payment_statuses', $payment_statuses );
664
}
665
666
/**
667
 * Get Payment Status Keys
668
 *
669
 * Retrieves keys for all available statuses for payments
670
 *
671
 * @since  1.0
672
 *
673
 * @return array $payment_status All the available payment statuses.
674
 */
675
function give_get_payment_status_keys() {
676
	$statuses = array_keys( give_get_payment_statuses() );
677
	asort( $statuses );
678
679
	return array_values( $statuses );
680
}
681
682
/**
683
 * Get Earnings By Date
684
 *
685
 * @since  1.0
686
 *
687
 * @param  int $day       Day number. Default is null.
688
 * @param  int $month_num Month number. Default is null.
689
 * @param  int $year      Year number. Default is null.
690
 * @param  int $hour      Hour number. Default is null.
691
 *
692
 * @return int $earnings  Earnings
693
 */
694
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
695
696
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead.
697
	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...
698
699
	$args = array(
700
		'post_type'              => 'give_payment',
701
		'nopaging'               => true,
702
		'year'                   => $year,
703
		'monthnum'               => $month_num,
704
		'post_status'            => array( 'publish' ),
705
		'fields'                 => 'ids',
706
		'update_post_term_cache' => false,
707
	);
708
	if ( ! empty( $day ) ) {
709
		$args['day'] = $day;
710
	}
711
712
	if ( ! empty( $hour ) ) {
713
		$args['hour'] = $hour;
714
	}
715
716
	$args = apply_filters( 'give_get_earnings_by_date_args', $args );
717
	$key  = 'give_stats_' . substr( md5( serialize( $args ) ), 0, 15 );
718
719
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
720
		$earnings = false;
721
	} else {
722
		$earnings = get_transient( $key );
723
	}
724
725
	if ( false === $earnings ) {
726
		$sales    = get_posts( $args );
727
		$earnings = 0;
728
		if ( $sales ) {
729
			$sales = implode( ',', $sales );
730
731
			$earnings = $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN ({$sales})" );
732
733
		}
734
		// Cache the results for one hour.
735
		set_transient( $key, $earnings, HOUR_IN_SECONDS );
736
	}
737
738
	return round( $earnings, 2 );
739
}
740
741
/**
742
 * Get Donations (sales) By Date
743
 *
744
 * @since  1.0
745
 *
746
 * @param  int $day       Day number. Default is null.
747
 * @param  int $month_num Month number. Default is null.
748
 * @param  int $year      Year number. Default is null.
749
 * @param  int $hour      Hour number. Default is null.
750
 *
751
 * @return int $count     Sales
752
 */
753
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
754
755
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead.
756
	$args = array(
757
		'post_type'              => 'give_payment',
758
		'nopaging'               => true,
759
		'year'                   => $year,
760
		'fields'                 => 'ids',
761
		'post_status'            => array( 'publish' ),
762
		'update_post_meta_cache' => false,
763
		'update_post_term_cache' => false,
764
	);
765
766
	$show_free = apply_filters( 'give_sales_by_date_show_free', true, $args );
767
768
	if ( false === $show_free ) {
769
		$args['meta_query'] = array(
770
			array(
771
				'key'     => '_give_payment_total',
772
				'value'   => 0,
773
				'compare' => '>',
774
				'type'    => 'NUMERIC',
775
			),
776
		);
777
	}
778
779
	if ( ! empty( $month_num ) ) {
780
		$args['monthnum'] = $month_num;
781
	}
782
783
	if ( ! empty( $day ) ) {
784
		$args['day'] = $day;
785
	}
786
787
	if ( ! empty( $hour ) ) {
788
		$args['hour'] = $hour;
789
	}
790
791
	$args = apply_filters( 'give_get_sales_by_date_args', $args );
792
793
	$key = 'give_stats_' . substr( md5( serialize( $args ) ), 0, 15 );
794
795
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
796
		$count = false;
797
	} else {
798
		$count = get_transient( $key );
799
	}
800
801
	if ( false === $count ) {
802
		$sales = new WP_Query( $args );
803
		$count = (int) $sales->post_count;
804
		// Cache the results for one hour.
805
		set_transient( $key, $count, HOUR_IN_SECONDS );
806
	}
807
808
	return $count;
809
}
810
811
/**
812
 * Checks whether a payment has been marked as complete.
813
 *
814
 * @since  1.0
815
 *
816
 * @param  int $payment_id Payment ID to check against.
817
 *
818
 * @return bool $ret True if complete, false otherwise.
819
 */
820
function give_is_payment_complete( $payment_id ) {
821
	$payment = new Give_Payment( $payment_id );
822
823
	$ret = false;
824
825
	if ( $payment->ID > 0 ) {
826
827
		if ( (int) $payment_id === (int) $payment->ID && 'publish' == $payment->status ) {
828
			$ret = true;
829
		}
830
	}
831
832
	return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
833
}
834
835
/**
836
 * Get Total Donations.
837
 *
838
 * @since  1.0
839
 *
840
 * @return int $count Total sales.
841
 */
842
function give_get_total_sales() {
843
844
	$payments = give_count_payments();
845
846
	return $payments->publish;
847
}
848
849
/**
850
 * Get Total Earnings
851
 *
852
 * @since  1.0
853
 *
854
 * @return float $total Total earnings.
855
 */
856
function give_get_total_earnings() {
857
858
	$total = get_option( 'give_earnings_total', false );
859
860
	// If no total stored in DB, use old method of calculating total earnings.
861
	if ( false === $total ) {
862
863
		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...
864
865
		$total = get_transient( 'give_earnings_total' );
866
867
		if ( false === $total ) {
868
869
			$total = (float) 0;
870
871
			$args = apply_filters( 'give_get_total_earnings_args', array(
872
				'offset' => 0,
873
				'number' => - 1,
874
				'status' => array( 'publish' ),
875
				'fields' => 'ids',
876
			) );
877
878
			$payments = give_get_payments( $args );
879
			if ( $payments ) {
880
881
				/**
882
				 * If performing a donation, we need to skip the very last payment in the database,
883
				 * since it calls give_increase_total_earnings() on completion,
884
				 * which results in duplicated earnings for the very first donation.
885
				 */
886
				if ( did_action( 'give_update_payment_status' ) ) {
887
					array_pop( $payments );
888
				}
889
890
				if ( ! empty( $payments ) ) {
891
					$payments = implode( ',', $payments );
892
					$total += $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN({$payments})" );
893
				}
894
			}
895
896
			// Cache results for 1 day. This cache is cleared automatically when a payment is made.
897
			set_transient( 'give_earnings_total', $total, 86400 );
898
899
			// Store the total for the first time.
900
			update_option( 'give_earnings_total', $total );
901
		}
902
	}
903
904
	if ( $total < 0 ) {
905
		$total = 0; // Don't ever show negative earnings.
906
	}
907
908
	return apply_filters( 'give_total_earnings', round( $total, give_currency_decimal_filter() ) );
909
}
910
911
/**
912
 * Increase the Total Earnings
913
 *
914
 * @since  1.0
915
 *
916
 * @param  int $amount   The amount you would like to increase the total earnings by.
917
 *                       Default is 0.
918
 *
919
 * @return float $total  Total earnings.
920
 */
921
function give_increase_total_earnings( $amount = 0 ) {
922
	$total = give_get_total_earnings();
923
	$total += $amount;
924
	update_option( 'give_earnings_total', $total );
925
926
	return $total;
927
}
928
929
/**
930
 * Decrease the Total Earnings
931
 *
932
 * @since 1.0
933
 *
934
 * @param int $amount The amount you would like to decrease the total earnings by.
935
 *
936
 * @return float $total Total earnings.
937
 */
938
function give_decrease_total_earnings( $amount = 0 ) {
939
	$total = give_get_total_earnings();
940
	$total -= $amount;
941
	if ( $total < 0 ) {
942
		$total = 0;
943
	}
944
	update_option( 'give_earnings_total', $total );
945
946
	return $total;
947
}
948
949
/**
950
 * Get Payment Meta for a specific Payment
951
 *
952
 * @since 1.0
953
 *
954
 * @param int    $payment_id Payment ID.
955
 * @param string $meta_key   The meta key to pull.
956
 * @param bool   $single     Pull single meta entry or as an object.
957
 *
958
 * @return mixed $meta Payment Meta.
959
 */
960
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
961
	$payment = new Give_Payment( $payment_id );
962
963
	return $payment->get_meta( $meta_key, $single );
964
}
965
966
/**
967
 * Update the meta for a payment
968
 *
969
 * @param  int    $payment_id Payment ID.
970
 * @param  string $meta_key   Meta key to update.
971
 * @param  string $meta_value Value to update to.
972
 * @param  string $prev_value Previous value.
973
 *
974
 * @return mixed Meta ID if successful, false if unsuccessful.
975
 */
976
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
977
	$payment = new Give_Payment( $payment_id );
978
979
	return $payment->update_meta( $meta_key, $meta_value, $prev_value );
980
}
981
982
/**
983
 * Get the user_info Key from Payment Meta
984
 *
985
 * @since 1.0
986
 *
987
 * @param int $payment_id Payment ID.
988
 *
989
 * @return string $user_info User Info Meta Values.
990
 */
991
function give_get_payment_meta_user_info( $payment_id ) {
992
	$payment = new Give_Payment( $payment_id );
993
994
	return $payment->user_info;
995
}
996
997
/**
998
 * Get the donations Key from Payment Meta
999
 *
1000
 * Retrieves the form_id from a (Previously titled give_get_payment_meta_donations)
1001
 *
1002
 * @since 1.0
1003
 *
1004
 * @param int $payment_id Payment ID.
1005
 *
1006
 * @return int $form_id Form ID.
1007
 */
1008
function give_get_payment_form_id( $payment_id ) {
1009
	$payment = new Give_Payment( $payment_id );
1010
1011
	return $payment->form_id;
1012
}
1013
1014
/**
1015
 * Get the user email associated with a payment
1016
 *
1017
 * @since 1.0
1018
 *
1019
 * @param int $payment_id Payment ID.
1020
 *
1021
 * @return string $email User email.
1022
 */
1023
function give_get_payment_user_email( $payment_id ) {
1024
	$payment = new Give_Payment( $payment_id );
1025
1026
	return $payment->email;
1027
}
1028
1029
/**
1030
 * Is the payment provided associated with a user account
1031
 *
1032
 * @since  1.3
1033
 *
1034
 * @param  int $payment_id The payment ID.
1035
 *
1036
 * @return bool $is_guest_payment If the payment is associated with a user (false) or not (true)
1037
 */
1038
function give_is_guest_payment( $payment_id ) {
1039
	$payment_user_id  = give_get_payment_user_id( $payment_id );
1040
	$is_guest_payment = ! empty( $payment_user_id ) && $payment_user_id > 0 ? false : true;
1041
1042
	return (bool) apply_filters( 'give_is_guest_payment', $is_guest_payment, $payment_id );
1043
}
1044
1045
/**
1046
 * Get the user ID associated with a payment
1047
 *
1048
 * @since 1.3
1049
 *
1050
 * @param int $payment_id Payment ID.
1051
 *
1052
 * @return int $user_id User ID.
1053
 */
1054
function give_get_payment_user_id( $payment_id ) {
1055
	$payment = new Give_Payment( $payment_id );
1056
1057
	return $payment->user_id;
1058
}
1059
1060
/**
1061
 * Get the donor ID associated with a payment
1062
 *
1063
 * @since 1.0
1064
 *
1065
 * @param int $payment_id Payment ID.
1066
 *
1067
 * @return int $customer_id Customer ID.
1068
 */
1069
function give_get_payment_customer_id( $payment_id ) {
1070
	$payment = new Give_Payment( $payment_id );
1071
1072
	return $payment->customer_id;
1073
}
1074
1075
/**
1076
 * Get the IP address used to make a donation
1077
 *
1078
 * @since 1.0
1079
 *
1080
 * @param int $payment_id Payment ID.
1081
 *
1082
 * @return string $ip User IP.
1083
 */
1084
function give_get_payment_user_ip( $payment_id ) {
1085
	$payment = new Give_Payment( $payment_id );
1086
1087
	return $payment->ip;
1088
}
1089
1090
/**
1091
 * Get the date a payment was completed
1092
 *
1093
 * @since 1.0
1094
 *
1095
 * @param int $payment_id Payment ID.
1096
 *
1097
 * @return string $date The date the payment was completed.
1098
 */
1099
function give_get_payment_completed_date( $payment_id = 0 ) {
1100
	$payment = new Give_Payment( $payment_id );
1101
1102
	return $payment->completed_date;
1103
}
1104
1105
/**
1106
 * Get the gateway associated with a payment
1107
 *
1108
 * @since 1.0
1109
 *
1110
 * @param int $payment_id Payment ID.
1111
 *
1112
 * @return string $gateway Gateway.
1113
 */
1114
function give_get_payment_gateway( $payment_id ) {
1115
	$payment = new Give_Payment( $payment_id );
1116
1117
	return $payment->gateway;
1118
}
1119
1120
/**
1121
 * Get the currency code a payment was made in
1122
 *
1123
 * @since 1.0
1124
 *
1125
 * @param int $payment_id Payment ID.
1126
 *
1127
 * @return string $currency The currency code.
1128
 */
1129
function give_get_payment_currency_code( $payment_id = 0 ) {
1130
	$payment = new Give_Payment( $payment_id );
1131
1132
	return $payment->currency;
1133
}
1134
1135
/**
1136
 * Get the currency name a payment was made in
1137
 *
1138
 * @since 1.0
1139
 *
1140
 * @param int $payment_id Payment ID.
1141
 *
1142
 * @return string $currency The currency name.
1143
 */
1144
function give_get_payment_currency( $payment_id = 0 ) {
1145
	$currency = give_get_payment_currency_code( $payment_id );
1146
1147
	return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
1148
}
1149
1150
/**
1151
 * Get the key for a donation
1152
 *
1153
 * @since 1.0
1154
 *
1155
 * @param int $payment_id Payment ID.
1156
 *
1157
 * @return string $key Donation key.
1158
 */
1159
function give_get_payment_key( $payment_id = 0 ) {
1160
	$payment = new Give_Payment( $payment_id );
1161
1162
	return $payment->key;
1163
}
1164
1165
/**
1166
 * Get the payment order number
1167
 *
1168
 * This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
1169
 *
1170
 * @since 1.0
1171
 *
1172
 * @param int $payment_id Payment ID.
1173
 *
1174
 * @return string $number Payment order number.
1175
 */
1176
function give_get_payment_number( $payment_id = 0 ) {
1177
	$payment = new Give_Payment( $payment_id );
1178
1179
	return $payment->number;
1180
}
1181
1182
/**
1183
 * Formats the payment number with the prefix and postfix
1184
 *
1185
 * @since  1.3
1186
 *
1187
 * @param  int $number The payment number to format.
1188
 *
1189
 * @return string      The formatted payment number.
1190
 */
1191
function give_format_payment_number( $number ) {
1192
1193
	if ( ! give_get_option( 'enable_sequential' ) ) {
1194
		return $number;
1195
	}
1196
1197
	if ( ! is_numeric( $number ) ) {
1198
		return $number;
1199
	}
1200
1201
	$prefix  = give_get_option( 'sequential_prefix' );
1202
	$number  = absint( $number );
1203
	$postfix = give_get_option( 'sequential_postfix' );
1204
1205
	$formatted_number = $prefix . $number . $postfix;
1206
1207
	return apply_filters( 'give_format_payment_number', $formatted_number, $prefix, $number, $postfix );
1208
}
1209
1210
/**
1211
 * Gets the next available order number
1212
 *
1213
 * This is used when inserting a new payment
1214
 *
1215
 * @since 1.0
1216
 * @return string $number The next available payment number.
1217
 */
1218
function give_get_next_payment_number() {
1219
1220
	if ( ! give_get_option( 'enable_sequential' ) ) {
1221
		return false;
1222
	}
1223
1224
	$number           = get_option( 'give_last_payment_number' );
1225
	$start            = give_get_option( 'sequential_start', 1 );
1226
	$increment_number = true;
1227
1228
	if ( false !== $number ) {
1229
1230
		if ( empty( $number ) ) {
1231
1232
			$number           = $start;
1233
			$increment_number = false;
1234
1235
		}
1236
	} else {
1237
1238
		// This case handles the first addition of the new option, as well as if it get's deleted for any reason.
1239
		$payments     = new Give_Payments_Query( array(
1240
			'number'  => 1,
1241
			'order'   => 'DESC',
1242
			'orderby' => 'ID',
1243
			'output'  => 'posts',
1244
			'fields'  => 'ids',
1245
		) );
1246
		$last_payment = $payments->get_payments();
1247
1248
		if ( ! empty( $last_payment ) ) {
1249
1250
			$number = give_get_payment_number( $last_payment[0] );
1251
1252
		}
1253
1254
		if ( ! empty( $number ) && $number !== (int) $last_payment[0] ) {
1255
1256
			$number = give_remove_payment_prefix_postfix( $number );
1257
1258
		} else {
1259
1260
			$number           = $start;
1261
			$increment_number = false;
1262
		}
1263
	}
1264
1265
	$increment_number = apply_filters( 'give_increment_payment_number', $increment_number, $number );
1266
1267
	if ( $increment_number ) {
1268
		$number ++;
1269
	}
1270
1271
	return apply_filters( 'give_get_next_payment_number', $number );
1272
}
1273
1274
/**
1275
 * Given a given a number, remove the pre/postfix
1276
 *
1277
 * @since  1.3
1278
 *
1279
 * @param  string $number The formatted Current Number to increment.
1280
 *
1281
 * @return string The new Payment number without prefix and postfix.
1282
 */
1283
function give_remove_payment_prefix_postfix( $number ) {
1284
1285
	$prefix  = give_get_option( 'sequential_prefix' );
1286
	$postfix = give_get_option( 'sequential_postfix' );
1287
1288
	// Remove prefix.
1289
	$number = preg_replace( '/' . $prefix . '/', '', $number, 1 );
1290
1291
	// Remove the postfix.
1292
	$length      = strlen( $number );
1293
	$postfix_pos = strrpos( $number, $postfix );
1294
	if ( false !== $postfix_pos ) {
1295
		$number = substr_replace( $number, '', $postfix_pos, $length );
1296
	}
1297
1298
	// Ensure it's a whole number.
1299
	$number = intval( $number );
1300
1301
	return apply_filters( 'give_remove_payment_prefix_postfix', $number, $prefix, $postfix );
1302
1303
}
1304
1305
1306
/**
1307
 * Get Payment Amount
1308
 *
1309
 * Get the fully formatted payment amount. The payment amount is retrieved using give_get_payment_amount() and is then sent through give_currency_filter() and  give_format_amount() to format the amount correctly.
1310
 *
1311
 * @since       1.0
1312
 *
1313
 * @param int $payment_id Payment ID.
1314
 *
1315
 * @return string $amount Fully formatted payment amount.
1316
 */
1317
function give_payment_amount( $payment_id = 0 ) {
1318
	$amount = give_get_payment_amount( $payment_id );
1319
1320
	return give_currency_filter( give_format_amount( $amount ), give_get_payment_currency_code( $payment_id ) );
1321
}
1322
1323
/**
1324
 * Get the amount associated with a payment
1325
 *
1326
 * @access public
1327
 * @since  1.0
1328
 *
1329
 * @param int $payment_id Payment ID.
1330
 *
1331
 * @return mixed|void
1332
 */
1333
function give_get_payment_amount( $payment_id ) {
1334
1335
	$payment = new Give_Payment( $payment_id );
1336
1337
	return apply_filters( 'give_payment_amount', floatval( $payment->total ), $payment_id );
1338
}
1339
1340
/**
1341
 * Payment Subtotal
1342
 *
1343
 * Retrieves subtotal for payment (this is the amount before fees) and then returns a full formatted amount. This function essentially calls give_get_payment_subtotal()
1344
 *
1345
 * @since 1.5
1346
 *
1347
 * @param int $payment_id Payment ID.
1348
 *
1349
 * @see   give_get_payment_subtotal()
1350
 *
1351
 * @return array Fully formatted payment subtotal.
1352
 */
1353
function give_payment_subtotal( $payment_id = 0 ) {
1354
	$subtotal = give_get_payment_subtotal( $payment_id );
1355
1356
	return give_currency_filter( give_format_amount( $subtotal ), give_get_payment_currency_code( $payment_id ) );
1357
}
1358
1359
/**
1360
 * Get Payment Subtotal
1361
 *
1362
 * Retrieves subtotal for payment (this is the amount before fees) and then returns a non formatted amount.
1363
 *
1364
 * @since 1.5
1365
 *
1366
 * @param int $payment_id Payment ID.
1367
 *
1368
 * @return float $subtotal Subtotal for payment (non formatted).
1369
 */
1370
function give_get_payment_subtotal( $payment_id = 0 ) {
1371
	$payment = new G_Payment( $payment_id );
1372
1373
	return $payment->subtotal;
1374
}
1375
1376
/**
1377
 * Retrieves arbitrary fees for the payment
1378
 *
1379
 * @since 1.5
1380
 *
1381
 * @param int    $payment_id Payment ID.
1382
 * @param string $type       Fee type.
1383
 *
1384
 * @return mixed array if payment fees found, false otherwise.
1385
 */
1386
function give_get_payment_fees( $payment_id = 0, $type = 'all' ) {
1387
	$payment = new Give_Payment( $payment_id );
1388
1389
	return $payment->get_fees( $type );
1390
}
1391
1392
/**
1393
 * Retrieves the donation ID
1394
 *
1395
 * @since  1.0
1396
 *
1397
 * @param int $payment_id Payment ID.
1398
 *
1399
 * @return string The donation ID.
1400
 */
1401
function give_get_payment_transaction_id( $payment_id = 0 ) {
1402
	$payment = new Give_Payment( $payment_id );
1403
1404
	return $payment->transaction_id;
1405
}
1406
1407
/**
1408
 * Sets a Transaction ID in post meta for the given Payment ID.
1409
 *
1410
 * @since  1.0
1411
 *
1412
 * @param int    $payment_id     Payment ID.
1413
 * @param string $transaction_id The transaction ID from the gateway.
1414
 *
1415
 * @return bool|mixed
1416
 */
1417
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1418
1419
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1420
		return false;
1421
	}
1422
1423
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1424
1425
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1426
}
1427
1428
/**
1429
 * Retrieve the donation ID based on the key
1430
 *
1431
 * @since 1.0
1432
 * @global object $wpdb Used to query the database using the WordPress Database API.
1433
 *
1434
 * @param string  $key  the key to search for.
1435
 *
1436
 * @return int $purchase Donation ID.
1437
 */
1438
function give_get_purchase_id_by_key( $key ) {
1439
	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...
1440
1441
	$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 ) );
1442
1443
	if ( $purchase != null ) {
1444
		return $purchase;
1445
	}
1446
1447
	return 0;
1448
}
1449
1450
1451
/**
1452
 * Retrieve the donation ID based on the transaction ID
1453
 *
1454
 * @since 1.3
1455
 * @global object $wpdb Used to query the database using the WordPress Database API.
1456
 *
1457
 * @param string  $key  The transaction ID to search for.
1458
 *
1459
 * @return int $purchase Donation ID.
1460
 */
1461
function give_get_purchase_id_by_transaction_id( $key ) {
1462
	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...
1463
1464
	$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 ) );
1465
1466
	if ( $purchase != null ) {
1467
		return $purchase;
1468
	}
1469
1470
	return 0;
1471
}
1472
1473
/**
1474
 * Retrieve all notes attached to a donation
1475
 *
1476
 * @since 1.0
1477
 *
1478
 * @param int    $payment_id The donation ID to retrieve notes for.
1479
 * @param string $search     Search for notes that contain a search term.
1480
 *
1481
 * @return array $notes Donation Notes
1482
 */
1483
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1484
1485
	if ( empty( $payment_id ) && empty( $search ) ) {
1486
		return false;
1487
	}
1488
1489
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1490
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1491
1492
	$notes = get_comments( array( 'post_id' => $payment_id, 'order' => 'ASC', 'search' => $search ) );
1493
1494
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1495
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1496
1497
	return $notes;
1498
}
1499
1500
1501
/**
1502
 * Add a note to a payment
1503
 *
1504
 * @since 1.0
1505
 *
1506
 * @param int    $payment_id The payment ID to store a note for.
1507
 * @param string $note       The note to store.
1508
 *
1509
 * @return int The new note ID
1510
 */
1511
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1512
	if ( empty( $payment_id ) ) {
1513
		return false;
1514
	}
1515
1516
	/**
1517
	 * Fires before inserting payment note.
1518
	 *
1519
	 * @since 1.0
1520
	 *
1521
	 * @param int    $payment_id Payment ID.
1522
	 * @param string $note       The note.
1523
	 */
1524
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1525
1526
	$note_id = wp_insert_comment( wp_filter_comment( array(
1527
		'comment_post_ID'      => $payment_id,
1528
		'comment_content'      => $note,
1529
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1530
		'comment_date'         => current_time( 'mysql' ),
1531
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1532
		'comment_approved'     => 1,
1533
		'comment_parent'       => 0,
1534
		'comment_author'       => '',
1535
		'comment_author_IP'    => '',
1536
		'comment_author_url'   => '',
1537
		'comment_author_email' => '',
1538
		'comment_type'         => 'give_payment_note',
1539
1540
	) ) );
1541
1542
	/**
1543
	 * Fires after payment note inserted.
1544
	 *
1545
	 * @since 1.0
1546
	 *
1547
	 * @param int    $note_id    Note ID.
1548
	 * @param int    $payment_id Payment ID.
1549
	 * @param string $note       The note.
1550
	 */
1551
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1552
1553
	return $note_id;
1554
}
1555
1556
/**
1557
 * Deletes a payment note
1558
 *
1559
 * @since 1.0
1560
 *
1561
 * @param int $comment_id The comment ID to delete.
1562
 * @param int $payment_id The payment ID the note is connected to.
1563
 *
1564
 * @return bool True on success, false otherwise.
1565
 */
1566
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1567
	if ( empty( $comment_id ) ) {
1568
		return false;
1569
	}
1570
1571
	/**
1572
	 * Fires before deleting donation note.
1573
	 *
1574
	 * @since 1.0
1575
	 *
1576
	 * @param int $comment_id Note ID.
1577
	 * @param int $payment_id Payment ID.
1578
	 */
1579
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1580
1581
	$ret = wp_delete_comment( $comment_id, true );
1582
1583
	/**
1584
	 * Fires after donation note deleted.
1585
	 *
1586
	 * @since 1.0
1587
	 *
1588
	 * @param int $comment_id Note ID.
1589
	 * @param int $payment_id Payment ID.
1590
	 */
1591
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1592
1593
	return $ret;
1594
}
1595
1596
/**
1597
 * Gets the payment note HTML
1598
 *
1599
 * @since 1.0
1600
 *
1601
 * @param object|int $note       The comment object or ID.
1602
 * @param int        $payment_id The payment ID the note is connected to.
1603
 *
1604
 * @return string
1605
 */
1606
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1607
1608
	if ( is_numeric( $note ) ) {
1609
		$note = get_comment( $note );
1610
	}
1611
1612
	if ( ! empty( $note->user_id ) ) {
1613
		$user = get_userdata( $note->user_id );
1614
		$user = $user->display_name;
1615
	} else {
1616
		$user = esc_html__( 'System', 'give' );
1617
	}
1618
1619
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1620
1621
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1622
		'give-action' => 'delete_payment_note',
1623
		'note_id'     => $note->comment_ID,
1624
		'payment_id'  => $payment_id,
1625
	) ),
1626
		'give_delete_payment_note_' . $note->comment_ID
1627
	);
1628
1629
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1630
	$note_html .= '<p>';
1631
	$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/>';
1632
	$note_html .= $note->comment_content;
1633
	$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>';
1634
	$note_html .= '</p>';
1635
	$note_html .= '</div>';
1636
1637
	return $note_html;
1638
1639
}
1640
1641
/**
1642
 * Exclude notes (comments) on give_payment post type from showing in Recent
1643
 * Comments widgets
1644
 *
1645
 * @since 1.0
1646
 *
1647
 * @param object $query WordPress Comment Query Object.
1648
 *
1649
 * @return void
1650
 */
1651
function give_hide_payment_notes( $query ) {
1652
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1653
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1654
		if ( ! is_array( $types ) ) {
1655
			$types = array( $types );
1656
		}
1657
		$types[]                           = 'give_payment_note';
1658
		$query->query_vars['type__not_in'] = $types;
1659
	}
1660
}
1661
1662
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1663
1664
/**
1665
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1666
 *
1667
 * @since 1.0
1668
 *
1669
 * @param array  $clauses          Comment clauses for comment query.
1670
 * @param object $wp_comment_query WordPress Comment Query Object.
1671
 *
1672
 * @return array $clauses Updated comment clauses.
1673
 */
1674
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...
1675
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1676
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1677
	}
1678
1679
	return $clauses;
1680
}
1681
1682
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1683
1684
1685
/**
1686
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1687
 *
1688
 * @since 1.0
1689
 *
1690
 * @param string $where
1691
 * @param object $wp_comment_query WordPress Comment Query Object.
1692
 *
1693
 * @return string $where
1694
 */
1695
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...
1696
	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...
1697
1698
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1699
1700
	return $where;
1701
}
1702
1703
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1704
1705
1706
/**
1707
 * Remove Give Comments from the wp_count_comments function
1708
 *
1709
 * @access public
1710
 * @since  1.0
1711
 *
1712
 * @param array $stats   (empty from core filter).
1713
 * @param int   $post_id Post ID.
1714
 *
1715
 * @return array Array of comment counts.
1716
 */
1717
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1718
	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...
1719
1720
	if ( 'index.php' != $pagenow ) {
1721
		return $stats;
1722
	}
1723
1724
	$post_id = (int) $post_id;
1725
1726
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1727
		return $stats;
1728
	}
1729
1730
	$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
1731
1732
	if ( false !== $stats ) {
1733
		return $stats;
1734
	}
1735
1736
	$where = 'WHERE comment_type != "give_payment_note"';
1737
1738
	if ( $post_id > 0 ) {
1739
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1740
	}
1741
1742
	$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
1743
1744
	$total    = 0;
1745
	$approved = array(
1746
		'0'            => 'moderated',
1747
		'1'            => 'approved',
1748
		'spam'         => 'spam',
1749
		'trash'        => 'trash',
1750
		'post-trashed' => 'post-trashed',
1751
	);
1752
	foreach ( (array) $count as $row ) {
1753
		// Don't count post-trashed toward totals.
1754
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1755
			$total += $row['num_comments'];
1756
		}
1757
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1758
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1759
		}
1760
	}
1761
1762
	$stats['total_comments'] = $total;
1763
	foreach ( $approved as $key ) {
1764
		if ( empty( $stats[ $key ] ) ) {
1765
			$stats[ $key ] = 0;
1766
		}
1767
	}
1768
1769
	$stats = (object) $stats;
1770
	wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
1771
1772
	return $stats;
1773
}
1774
1775
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1776
1777
1778
/**
1779
 * Filter where older than one week
1780
 *
1781
 * @access public
1782
 * @since  1.0
1783
 *
1784
 * @param string $where Where clause.
1785
 *
1786
 * @return string $where Modified where clause.
1787
 */
1788
function give_filter_where_older_than_week( $where = '' ) {
1789
	// Payments older than one week.
1790
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1791
	$where .= " AND post_date <= '{$start}'";
1792
1793
	return $where;
1794
}
1795
1796
1797
/**
1798
 * Get Payment Form ID.
1799
 *
1800
 * Retrieves the form title and appends the level name if present.
1801
 *
1802
 * @since 1.5
1803
 *
1804
 * @param array  $payment_meta       Payment meta data.
1805
 * @param bool   $only_level         If set to true will only return the level name if multi-level enabled.
1806
 * @param string $separator          The separator between the .
1807
 *
1808
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1809
 */
1810
function give_get_payment_form_title( $payment_meta, $only_level = false, $separator = '' ) {
1811
1812
	$form_id    = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
1813
	$price_id   = isset( $payment_meta['price_id'] ) ? $payment_meta['price_id'] : null;
1814
	$form_title = isset( $payment_meta['form_title'] ) ? $payment_meta['form_title'] : '';
1815
1816
	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...
1817
		$form_title = '';
1818
	}
1819
1820
	//If multi-level, append to the form title.
1821
	if ( give_has_variable_prices( $form_id ) ) {
1822
1823
		//Only add separator if there is a form title.
1824
		if ( ! empty( $form_title ) ) {
1825
			$form_title .= ' ' . $separator . ' ';
1826
		}
1827
1828
		$form_title .= '<span class="donation-level-text-wrap">';
1829
1830
		if ( $price_id == 'custom' ) {
1831
			$custom_amount_text = get_post_meta( $form_id, '_give_custom_amount_text', true );
1832
			$form_title .= ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1833
		} else {
1834
			$form_title .= give_get_price_option_name( $form_id, $price_id );
1835
		}
1836
1837
		$form_title .= '</span>';
1838
1839
	}
1840
1841
	return apply_filters( 'give_get_payment_form_title', $form_title, $payment_meta );
1842
1843
}
1844
1845
/**
1846
 * Get Price ID
1847
 *
1848
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1849
 *
1850
 * @param int    $form_id Form ID.
1851
 * @param string $price   Price ID.
1852
 *
1853
 * @return string $price_id
1854
 */
1855
function give_get_price_id( $form_id, $price ) {
1856
1857
	$price_id = 0;
1858
1859
	if ( give_has_variable_prices( $form_id ) ) {
1860
1861
		$levels = maybe_unserialize( get_post_meta( $form_id, '_give_donation_levels', true ) );
1862
1863
		foreach ( $levels as $level ) {
1864
1865
			$level_amount = (float) give_sanitize_amount( $level['_give_amount'] );
1866
1867
			// Check that this indeed the recurring price.
1868
			if ( $level_amount == $price ) {
1869
1870
				$price_id = $level['_give_id']['level_id'];
1871
1872
			}
1873
		}
1874
	}
1875
1876
	return $price_id;
1877
1878
}
1879
1880
/**
1881
 * Get/Print give form dropdown html
1882
 *
1883
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1884
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1885
 *
1886
 * @since 1.6
1887
 *
1888
 * @param array $args Arguments for form dropdown.
1889
 * @param bool  $echo This parameter decides if print form dropdown html output or not.
1890
 *
1891
 * @return string|void
1892
 */
1893
function give_get_form_dropdown( $args = array(), $echo = false ) {
1894
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1895
1896
	if ( ! $echo ) {
1897
		return $form_dropdown_html;
1898
	}
1899
1900
	echo $form_dropdown_html;
1901
}
1902
1903
/**
1904
 * Get/Print give form variable price dropdown html
1905
 *
1906
 * @since 1.6
1907
 *
1908
 * @param array $args Arguments for form dropdown.
1909
 * @param bool  $echo This parameter decide if print form dropdown html output or not.
1910
 *
1911
 * @return string|bool
1912
 */
1913
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1914
1915
	// Check for give form id.
1916
	if ( empty( $args['id'] ) ) {
1917
		return false;
1918
	}
1919
1920
	$form = new Give_Donate_Form( $args['id'] );
1921
1922
	// Check if form has variable prices or not.
1923
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1924
		return false;
1925
	}
1926
1927
	$variable_prices        = $form->get_prices();
1928
	$variable_price_options = array();
1929
1930
	// Check if multi donation form support custom donation or not.
1931
	if ( $form->is_custom_price_mode() ) {
1932
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1933
	}
1934
1935
	// Get variable price and ID from variable price array.
1936
	foreach ( $variable_prices as $variable_price ) {
1937
		$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'] ) );
1938
	}
1939
1940
	// Update options.
1941
	$args = array_merge( $args, array( 'options' => $variable_price_options ) );
1942
1943
	// Generate select html.
1944
	$form_dropdown_html = Give()->html->select( $args );
1945
1946
	if ( ! $echo ) {
1947
		return $form_dropdown_html;
1948
	}
1949
1950
	echo $form_dropdown_html;
1951
}