Test Failed
Push — issues/1227 ( 92c1d9 )
by Ravinder
06:04
created

functions.php ➔ give_delete_donation()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 66
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Payment Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Payments
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Get Payments
19
 *
20
 * Retrieve payments from the database.
21
 *
22
 * Since 1.0, this function takes an array of arguments, instead of individual
23
 * parameters. All of the original parameters remain, but can be passed in any
24
 * order via the array.
25
 *
26
 * @since 1.0
27
 *
28
 * @param array $args     {
29
 *                        Optional. Array of arguments passed to payments query.
30
 *
31
 * @type int    $offset   The number of payments to offset before retrieval.
32
 *                            Default is 0.
33
 * @type int    $number   The number of payments to query for. Use -1 to request all
34
 *                            payments. Default is 20.
35
 * @type string $mode     Default is 'live'.
36
 * @type string $order    Designates ascending or descending order of payments.
37
 *                            Accepts 'ASC', 'DESC'. Default is 'DESC'.
38
 * @type string $orderby  Sort retrieved payments by parameter. Default is 'ID'.
39
 * @type string $status   The status of the payments. Default is 'any'.
40
 * @type string $user     User. Default is null.
41
 * @type string $meta_key Custom field key. Default is null.
42
 * }
43
 *
44
 * @return array $payments Payments retrieved from the database
45
 */
46
function give_get_payments( $args = array() ) {
47
48
	// Fallback to post objects to ensure backwards compatibility.
49
	if ( ! isset( $args['output'] ) ) {
50
		$args['output'] = 'posts';
51
	}
52
53
	$args     = apply_filters( 'give_get_payments_args', $args );
54
	$payments = new Give_Payments_Query( $args );
55
56
	return $payments->get_payments();
57
}
58
59
/**
60
 * Retrieve payment by a given field
61
 *
62
 * @since  1.0
63
 *
64
 * @param  string $field The field to retrieve the payment with.
65
 * @param  mixed  $value The value for $field.
66
 *
67
 * @return mixed
68
 */
69
function give_get_payment_by( $field = '', $value = '' ) {
70
71
	if ( empty( $field ) || empty( $value ) ) {
72
		return false;
73
	}
74
75
	switch ( strtolower( $field ) ) {
76
77
		case 'id':
78
			$payment = new Give_Payment( $value );
79
			$id      = $payment->ID;
80
81
			if ( empty( $id ) ) {
82
				return false;
83
			}
84
85
			break;
86
87 View Code Duplication
		case 'key':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
88
			$payment = give_get_payments( array(
89
				'meta_key'       => '_give_payment_purchase_key',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
90
				'meta_value'     => $value,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
91
				'posts_per_page' => 1,
92
				'fields'         => 'ids',
93
			) );
94
95
			if ( $payment ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
96
				$payment = new Give_Payment( $payment[0] );
97
			}
98
99
			break;
100
101 View Code Duplication
		case 'payment_number':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
102
			$payment = give_get_payments( array(
103
				'meta_key'       => '_give_payment_number',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
104
				'meta_value'     => $value,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
105
				'posts_per_page' => 1,
106
				'fields'         => 'ids',
107
			) );
108
109
			if ( $payment ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
110
				$payment = new Give_Payment( $payment[0] );
111
			}
112
113
			break;
114
115
		default:
116
			return false;
117
	}// End switch().
118
119
	if ( $payment ) {
120
		return $payment;
121
	}
122
123
	return false;
124
}
125
126
/**
127
 * Insert Payment
128
 *
129
 * @since  1.0
130
 *
131
 * @param  array $payment_data Arguments passed.
132
 *
133
 * @return int|bool Payment ID if payment is inserted, false otherwise.
134
 */
135
function give_insert_payment( $payment_data = array() ) {
136
137
	if ( empty( $payment_data ) ) {
138
		return false;
139
	}
140
141
	$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;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
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
	// Save payment.
188
	$payment->save();
189
190
	/**
191
	 * Fires while inserting payments.
192
	 *
193
	 * @since 1.0
194
	 *
195
	 * @param int   $payment_id   The payment ID.
196
	 * @param array $payment_data Arguments passed.
197
	 */
198
	do_action( 'give_insert_payment', $payment->ID, $payment_data );
199
200
	// Return payment ID upon success.
201
	if ( ! empty( $payment->ID ) ) {
202
		return $payment->ID;
203
	}
204
205
	// Return false if no payment was inserted.
206
	return false;
207
208
}
209
210
/**
211
 * Create payment.
212
 *
213
 * @param $payment_data
214
 *
215
 * @return bool|int
216
 */
217
function give_create_payment( $payment_data ) {
218
219
	$form_id  = intval( $payment_data['post_data']['give-form-id'] );
220
	$price_id = isset( $payment_data['post_data']['give-price-id'] ) ? $payment_data['post_data']['give-price-id'] : '';
221
222
	// Collect payment data.
223
	$insert_payment_data = array(
224
		'price'           => $payment_data['price'],
225
		'give_form_title' => $payment_data['post_data']['give-form-title'],
226
		'give_form_id'    => $form_id,
227
		'give_price_id'   => $price_id,
228
		'date'            => $payment_data['date'],
229
		'user_email'      => $payment_data['user_email'],
230
		'purchase_key'    => $payment_data['purchase_key'],
231
		'currency'        => give_get_currency(),
232
		'user_info'       => $payment_data['user_info'],
233
		'status'          => 'pending',
234
		'gateway'         => 'paypal',
235
	);
236
237
	/**
238
	 * Filter the payment params.
239
	 *
240
	 * @since 1.8
241
	 *
242
	 * @param array $insert_payment_data
243
	 */
244
	$insert_payment_data = apply_filters( 'give_create_payment', $insert_payment_data );
245
246
	// Record the pending payment.
247
	return give_insert_payment( $insert_payment_data );
248
}
249
250
/**
251
 * Updates a payment status.
252
 *
253
 * @since  1.0
254
 *
255
 * @param  int    $payment_id Payment ID.
256
 * @param  string $new_status New Payment Status. Default is 'publish'.
257
 *
258
 * @return bool
259
 */
260
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
261
262
	$updated = false;
263
	$payment = new Give_Payment( $payment_id );
264
265
	if( $payment && $payment->ID > 0 ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
266
267
		$payment->status = $new_status;
268
		$updated = $payment->save();
269
270
	}
271
272
	return $updated;
273
}
274
275
276
/**
277
 * Deletes a Donation
278
 *
279
 * @since  1.0
280
 *
281
 * @param  int  $payment_id   Payment ID (default: 0).
282
 * @param  bool $update_donor If we should update the donor stats (default:true).
283
 *
284
 * @return void
285
 */
286
function give_delete_donation( $payment_id = 0, $update_donor = true ) {
287
	$payment     = new Give_Payment( $payment_id );
288
	$amount      = give_get_payment_amount( $payment_id );
289
	$status      = $payment->post_status;
290
291
	$donor_id = give_get_payment_donor_id( $payment_id );
292
	$donor    = new Give_Donor( $donor_id );
0 ignored issues
show
Documentation introduced by
$donor_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
293
294
	// Only undo donations that aren't these statuses.
295
	$dont_undo_statuses = apply_filters( 'give_undo_donation_statuses', array(
296
		'pending',
297
		'cancelled',
298
	) );
299
300
	if ( ! in_array( $status, $dont_undo_statuses ) ) {
301
		give_undo_donation( $payment_id );
302
	}
303
304
	if ( $status == 'publish' ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
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
309
		// @todo: Refresh only range related stat cache
310
		give_delete_donation_stats();
311
312
		if ( $donor->id && $update_donor ) {
313
314
			// Decrement the stats for the donor.
315
			$donor->decrease_donation_count();
316
			$donor->decrease_value( $amount );
317
318
		}
319
	}
320
321
	/**
322
	 * Fires before deleting payment.
323
	 *
324
	 * @since 1.0
325
	 *
326
	 * @param int $payment_id Payment ID.
327
	 */
328
	do_action( 'give_payment_delete', $payment_id );
329
330
	if ( $donor->id && $update_donor ) {
331
332
		// Remove the payment ID from the donor.
333
		$donor->remove_payment( $payment_id );
334
335
	}
336
337
	// Remove the payment.
338
	wp_delete_post( $payment_id, true );
339
340
	// Remove related sale log entries.
341
	Give()->logs->delete_logs( $payment_id );
342
343
	/**
344
	 * Fires after payment deleted.
345
	 *
346
	 * @since 1.0
347
	 *
348
	 * @param int $payment_id Payment ID.
349
	 */
350
	do_action( 'give_payment_deleted', $payment_id );
351
}
352
353
/**
354
 * Undo Donation
355
 *
356
 * Undoes a donation, including the decrease of donations and earning stats.
357
 * Used for when refunding or deleting a donation.
358
 *
359
 * @since  1.0
360
 *
361
 * @param  int $payment_id Payment ID.
362
 *
363
 * @return void
364
 */
365
function give_undo_donation( $payment_id ) {
366
367
	$payment = new Give_Payment( $payment_id );
368
369
	$maybe_decrease_earnings = apply_filters( 'give_decrease_earnings_on_undo', true, $payment, $payment->form_id );
370
	if ( true === $maybe_decrease_earnings ) {
371
		// Decrease earnings.
372
		give_decrease_earnings( $payment->form_id, $payment->total );
373
	}
374
375
	$maybe_decrease_donations = apply_filters( 'give_decrease_donations_on_undo', true, $payment, $payment->form_id );
376
	if ( true === $maybe_decrease_donations ) {
377
		// Decrease donation count.
378
		give_decrease_donation_count( $payment->form_id );
379
	}
380
381
}
382
383
384
/**
385
 * Count Payments
386
 *
387
 * Returns the total number of payments recorded.
388
 *
389
 * @since  1.0
390
 *
391
 * @param  array $args Arguments passed.
392
 *
393
 * @return object $stats Contains the number of payments per payment status.
394
 */
395
function give_count_payments( $args = array() ) {
396
397
	global $wpdb;
398
	$meta_table      = __give_v20_bc_table_details( 'payment' );
399
	$donor_meta_type = Give()->donor_meta->meta_type;
400
401
	$defaults = array(
402
		'user'       => null,
403
		's'          => null,
404
		'start-date' => null,
405
		'end-date'   => null,
406
		'form_id'    => null,
407
	);
408
409
	$args = wp_parse_args( $args, $defaults );
410
411
	$select = 'SELECT p.post_status,count( * ) AS num_posts';
412
	$join   = '';
413
	$where  = "WHERE p.post_type = 'give_payment' AND p.post_status IN ('". implode( "','", give_get_payment_status_keys() ). "')";
414
415
	// Count payments for a specific user.
416
	if ( ! empty( $args['user'] ) ) {
417
418
		if ( is_email( $args['user'] ) ) {
419
			$field = 'email';
420
		} elseif ( is_numeric( $args['user'] ) ) {
421
			$field = 'id';
422
		} else {
423
			$field = '';
424
		}
425
426
		$join = "LEFT JOIN {$meta_table['name']} m ON (p.ID = m.{$meta_table['column']['id']})";
427
428
		if ( ! empty( $field ) ) {
429
			$where .= "
430
				AND m.meta_key = '_give_payment_user_{$field}'
431
				AND m.meta_value = '{$args['user']}'";
432
		}
433
	} elseif ( ! empty( $args['donor'] ) ) {
434
435
		$join  = "LEFT JOIN {$meta_table['name']} m ON (p.ID = m.{$meta_table['column']['id']})";
436
		$where .= "
437
			AND m.meta_key = '_give_payment_{$donor_meta_type}_id'
438
			AND m.meta_value = '{$args['donor']}'";
439
440
		// Count payments for a search.
441
	} elseif ( ! empty( $args['s'] ) ) {
442
443
		if ( is_email( $args['s'] ) || strlen( $args['s'] ) == 32 ) {
444
445
			if ( is_email( $args['s'] ) ) {
446
				$field = '_give_payment_donor_email';
447
			} else {
448
				$field = '_give_payment_purchase_key';
449
			}
450
451
			$join  = "LEFT JOIN {$meta_table['name']} m ON (p.ID = m.{$meta_table['column']['id']})";
452
			$where .= $wpdb->prepare( '
453
                AND m.meta_key = %s
454
                AND m.meta_value = %s', $field, $args['s'] );
455
456
		} elseif ( '#' == substr( $args['s'], 0, 1 ) ) {
457
458
			$search = str_replace( '#:', '', $args['s'] );
459
			$search = str_replace( '#', '', $search );
460
461
			$select = 'SELECT p.post_status,count( * ) AS num_posts ';
462
			$join   = '';
463
			$where  = $wpdb->prepare( 'WHERE p.post_type=%s  AND p.ID = %d ', 'give_payment', $search );
464
465
		} elseif ( is_numeric( $args['s'] ) ) {
466
467
			$join  = "LEFT JOIN {$meta_table['column']} m ON (p.ID = m.{$meta_table['column']})";
468
			$where .= $wpdb->prepare( "
469
				AND m.meta_key = '_give_payment_donor_id'
470
				AND m.meta_value = %d", $args['s'] );
471
472
		} else {
473
			$search = $wpdb->esc_like( $args['s'] );
474
			$search = '%' . $search . '%';
475
476
			$where .= $wpdb->prepare( 'AND ((p.post_title LIKE %s) OR (p.post_content LIKE %s))', $search, $search );
477
		}// End if().
478
	}// End if().
479
480
	if ( ! empty( $args['form_id'] ) && is_numeric( $args['form_id'] ) ) {
481
482
		$join  = "LEFT JOIN {$meta_table['name']} m ON (p.ID = m.{$meta_table['column']['id']})";
483
		$where .= $wpdb->prepare( '
484
                AND m.meta_key = %s
485
                AND m.meta_value = %s', '_give_payment_form_id', $args['form_id'] );
486
	}
487
488
	// Limit payments count by date.
489
	if ( ! empty( $args['start-date'] ) && false !== strpos( $args['start-date'], '/' ) ) {
490
491
		$date_parts = explode( '/', $args['start-date'] );
492
		$month      = ! empty( $date_parts[0] ) && is_numeric( $date_parts[0] ) ? $date_parts[0] : 0;
493
		$day        = ! empty( $date_parts[1] ) && is_numeric( $date_parts[1] ) ? $date_parts[1] : 0;
494
		$year       = ! empty( $date_parts[2] ) && is_numeric( $date_parts[2] ) ? $date_parts[2] : 0;
495
496
		$is_date = checkdate( $month, $day, $year );
497 View Code Duplication
		if ( false !== $is_date ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
498
499
			$date  = new DateTime( $args['start-date'] );
500
			$where .= $wpdb->prepare( " AND p.post_date >= '%s'", $date->format( 'Y-m-d' ) );
501
502
		}
503
504
		// Fixes an issue with the payments list table counts when no end date is specified (with stats class).
505
		if ( empty( $args['end-date'] ) ) {
506
			$args['end-date'] = $args['start-date'];
507
		}
508
	}
509
510
	if ( ! empty( $args['end-date'] ) && false !== strpos( $args['end-date'], '/' ) ) {
511
512
		$date_parts = explode( '/', $args['end-date'] );
513
514
		$month = ! empty( $date_parts[0] ) ? $date_parts[0] : 0;
515
		$day   = ! empty( $date_parts[1] ) ? $date_parts[1] : 0;
516
		$year  = ! empty( $date_parts[2] ) ? $date_parts[2] : 0;
517
518
		$is_date = checkdate( $month, $day, $year );
519 View Code Duplication
		if ( false !== $is_date ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
520
521
			$date  = new DateTime( $args['end-date'] );
522
			$where .= $wpdb->prepare( " AND p.post_date <= '%s'", $date->format( 'Y-m-d' ) );
523
524
		}
525
	}
526
527
	$where = apply_filters( 'give_count_payments_where', $where );
528
	$join  = apply_filters( 'give_count_payments_join', $join );
529
530
	$query = "$select
531
		FROM $wpdb->posts p
532
		$join
533
		$where
534
		GROUP BY p.post_status
535
	";
536
537
	$cache_key = md5( $query );
538
539
	$count = wp_cache_get( $cache_key, 'counts' );
540
	if ( false !== $count ) {
541
		return $count;
542
	}
543
544
	$count = $wpdb->get_results( $query, ARRAY_A );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
545
546
	$stats    = array();
547
	$statuses = get_post_stati();
548
	if ( isset( $statuses['private'] ) && empty( $args['s'] ) ) {
549
		unset( $statuses['private'] );
550
	}
551
552
	foreach ( $statuses as $state ) {
553
		$stats[ $state ] = 0;
554
	}
555
556
	foreach ( (array) $count as $row ) {
557
558
		if ( 'private' == $row['post_status'] && empty( $args['s'] ) ) {
559
			continue;
560
		}
561
562
		$stats[ $row['post_status'] ] = $row['num_posts'];
563
	}
564
565
	$stats = (object) $stats;
566
	wp_cache_set( $cache_key, $stats, 'counts' );
567
568
	return $stats;
569
}
570
571
572
/**
573
 * Check For Existing Payment
574
 *
575
 * @since  1.0
576
 *
577
 * @param  int $payment_id Payment ID
578
 *
579
 * @return bool $exists True if payment exists, false otherwise.
580
 */
581
function give_check_for_existing_payment( $payment_id ) {
582
	$exists  = false;
583
	$payment = new Give_Payment( $payment_id );
584
585
	if ( $payment_id === $payment->ID && 'publish' === $payment->status ) {
586
		$exists = true;
587
	}
588
589
	return $exists;
590
}
591
592
/**
593
 * Get Payment Status
594
 *
595
 * @since 1.0
596
 *
597
 * @param WP_Post|Give_Payment|int $payment      Payment object or payment ID.
598
 * @param bool                 $return_label Whether to return the translated status label
599
 *                                           instead of status value. Default false.
600
 *
601
 * @return bool|mixed True if payment status exists, false otherwise.
602
 */
603
function give_get_payment_status( $payment, $return_label = false ) {
604
605
	if( is_numeric( $payment ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
606
607
		$payment = new Give_Payment( $payment );
608
609
		if( ! $payment->ID > 0 ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
610
			return false;
611
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
612
613
	}
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 not 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
		'processing'  => __( 'Processing', 'give' ),
661
		'revoked'     => __( 'Revoked', 'give' ),
662
	);
663
664
	return apply_filters( 'give_payment_statuses', $payment_statuses );
665
}
666
667
/**
668
 * Get Payment Status Keys
669
 *
670
 * Retrieves keys for all available statuses for payments
671
 *
672
 * @since  1.0
673
 *
674
 * @return array $payment_status All the available payment statuses.
675
 */
676
function give_get_payment_status_keys() {
677
	$statuses = array_keys( give_get_payment_statuses() );
678
	asort( $statuses );
679
680
	return array_values( $statuses );
681
}
682
683
/**
684
 * Get Earnings By Date
685
 *
686
 * @since  1.0
687
 *
688
 * @param  int $day       Day number. Default is null.
689
 * @param  int $month_num Month number. Default is null.
690
 * @param  int $year      Year number. Default is null.
691
 * @param  int $hour      Hour number. Default is null.
692
 *
693
 * @return int $earnings  Earnings
694
 */
695
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
696
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead.
697
698
	global $wpdb;
699
	$meta_table = __give_v20_bc_table_details( 'payment' );
700
701
	$args = array(
702
		'post_type'              => 'give_payment',
703
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
704
		'year'                   => $year,
705
		'monthnum'               => $month_num,
706
		'post_status'            => array( 'publish' ),
707
		'fields'                 => 'ids',
708
		'update_post_term_cache' => false,
709
	);
710
	if ( ! empty( $day ) ) {
711
		$args['day'] = $day;
712
	}
713
714
	if ( ! empty( $hour ) ) {
715
		$args['hour'] = $hour;
716
	}
717
718
	$args = apply_filters( 'give_get_earnings_by_date_args', $args );
719
	$key  = Give_Cache::get_key( 'give_stats', $args );
720
721 View Code Duplication
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
722
		$earnings = false;
723
	} else {
724
		$earnings = Give_Cache::get( $key );
725
	}
726
727
	if ( false === $earnings ) {
728
		$donations = get_posts( $args );
729
		$earnings  = 0;
730 View Code Duplication
		if ( $donations ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
731
			$donations = implode( ',', $donations );
732
733
			$earnings = $wpdb->get_var( "SELECT SUM(meta_value) FROM {$meta_table['name']} WHERE meta_key = '_give_payment_total' AND {$meta_table['column']['id']} IN ({$donations})" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
734
735
		}
736
		// Cache the results for one hour.
737
		Give_Cache::set( $key, $earnings, HOUR_IN_SECONDS );
738
	}
739
740
	return round( $earnings, 2 );
741
}
742
743
/**
744
 * Get Donations (sales) By Date
745
 *
746
 * @since  1.0
747
 *
748
 * @param  int $day       Day number. Default is null.
749
 * @param  int $month_num Month number. Default is null.
750
 * @param  int $year      Year number. Default is null.
751
 * @param  int $hour      Hour number. Default is null.
752
 *
753
 * @return int $count     Sales
754
 */
755
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
756
757
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead.
758
	$args = array(
759
		'post_type'              => 'give_payment',
760
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
761
		'year'                   => $year,
762
		'fields'                 => 'ids',
763
		'post_status'            => array( 'publish' ),
764
		'update_post_meta_cache' => false,
765
		'update_post_term_cache' => false,
766
	);
767
768
	$show_free = apply_filters( 'give_sales_by_date_show_free', true, $args );
769
770
	if ( false === $show_free ) {
771
		$args['meta_query'] = array(
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
772
			array(
773
				'key'     => '_give_payment_total',
774
				'value'   => 0,
775
				'compare' => '>',
776
				'type'    => 'NUMERIC',
777
			),
778
		);
779
	}
780
781
	if ( ! empty( $month_num ) ) {
782
		$args['monthnum'] = $month_num;
783
	}
784
785
	if ( ! empty( $day ) ) {
786
		$args['day'] = $day;
787
	}
788
789
	if ( ! empty( $hour ) ) {
790
		$args['hour'] = $hour;
791
	}
792
793
	$args = apply_filters( 'give_get_sales_by_date_args', $args );
794
795
	$key = Give_Cache::get_key( 'give_stats', $args );
796
797 View Code Duplication
	if ( ! empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'give-refresh-reports' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
798
		$count = false;
799
	} else {
800
		$count = Give_Cache::get( $key );
801
	}
802
803
	if ( false === $count ) {
804
		$donations = new WP_Query( $args );
805
		$count     = (int) $donations->post_count;
806
		// Cache the results for one hour.
807
		Give_Cache::set( $key, $count, HOUR_IN_SECONDS );
808
	}
809
810
	return $count;
811
}
812
813
/**
814
 * Checks whether a payment has been marked as complete.
815
 *
816
 * @since  1.0
817
 *
818
 * @param  int $payment_id Payment ID to check against.
819
 *
820
 * @return bool $ret True if complete, false otherwise.
821
 */
822
function give_is_payment_complete( $payment_id ) {
823
	$payment = new Give_Payment( $payment_id );
824
825
	$ret = false;
826
827
	if ( $payment->ID > 0 ) {
828
829
		if ( (int) $payment_id === (int) $payment->ID && 'publish' == $payment->status ) {
830
			$ret = true;
831
		}
832
	}
833
834
	return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
835
}
836
837
/**
838
 * Get Total Donations.
839
 *
840
 * @since  1.0
841
 *
842
 * @return int $count Total number of donations.
843
 */
844
function give_get_total_donations() {
845
846
	$payments = give_count_payments();
847
848
	return $payments->publish;
849
}
850
851
/**
852
 * Get Total Earnings
853
 *
854
 * @since  1.0
855
 *
856
 * @param bool $recalculate Recalculate earnings forcefully.
857
 *
858
 * @return float $total Total earnings.
859
 */
860
function give_get_total_earnings( $recalculate = false ) {
861
862
	$total = get_option( 'give_earnings_total', 0 );
863
	$meta_table = __give_v20_bc_table_details( 'payment' );
864
865
	// Calculate total earnings.
866
	if ( ! $total || $recalculate ) {
867
		global $wpdb;
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 ) {
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...
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 View Code Duplication
			if ( ! empty( $payments ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
891
				$payments = implode( ',', $payments );
892
				$total    += $wpdb->get_var( "SELECT SUM(meta_value) FROM {$meta_table['name']} WHERE meta_key = '_give_payment_total' AND {$meta_table['column']['id']} IN({$payments})" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
893
			}
894
		}
895
896
		update_option( 'give_earnings_total', $total, 'no' );
897
	}
898
899
	if ( $total < 0 ) {
900
		$total = 0; // Don't ever show negative earnings.
901
	}
902
903
	return apply_filters( 'give_total_earnings', round( $total, give_currency_decimal_filter() ) );
904
}
905
906
/**
907
 * Increase the Total Earnings
908
 *
909
 * @since  1.0
910
 *
911
 * @param  int $amount   The amount you would like to increase the total earnings by.
912
 *                       Default is 0.
913
 *
914
 * @return float $total  Total earnings.
915
 */
916
function give_increase_total_earnings( $amount = 0 ) {
917
	$total = give_get_total_earnings();
918
	$total += $amount;
919
	update_option( 'give_earnings_total', $total );
920
921
	return $total;
922
}
923
924
/**
925
 * Decrease the Total Earnings
926
 *
927
 * @since 1.0
928
 *
929
 * @param int $amount The amount you would like to decrease the total earnings by.
930
 *
931
 * @return float $total Total earnings.
932
 */
933
function give_decrease_total_earnings( $amount = 0 ) {
934
	$total = give_get_total_earnings();
935
	$total -= $amount;
936
	if ( $total < 0 ) {
937
		$total = 0;
938
	}
939
	update_option( 'give_earnings_total', $total );
940
941
	return $total;
942
}
943
944
/**
945
 * Get Payment Meta for a specific Payment
946
 *
947
 * @since 1.0
948
 *
949
 * @param int    $payment_id Payment ID.
950
 * @param string $meta_key   The meta key to pull.
951
 * @param bool   $single     Pull single meta entry or as an object.
952
 *
953
 * @return mixed $meta Payment Meta.
954
 */
955
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
956
	$payment = new Give_Payment( $payment_id );
957
958
	return $payment->get_meta( $meta_key, $single );
959
}
960
961
/**
962
 * Update the meta for a payment
963
 *
964
 * @param  int    $payment_id Payment ID.
965
 * @param  string $meta_key   Meta key to update.
966
 * @param  string $meta_value Value to update to.
967
 * @param  string $prev_value Previous value.
968
 *
969
 * @return mixed Meta ID if successful, false if unsuccessful.
970
 */
971
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
972
	$payment = new Give_Payment( $payment_id );
973
974
	return $payment->update_meta( $meta_key, $meta_value, $prev_value );
975
}
976
977
/**
978
 * Get the user_info Key from Payment Meta
979
 *
980
 * @since 1.0
981
 *
982
 * @param int $payment_id Payment ID.
983
 *
984
 * @return array $user_info User Info Meta Values.
985
 */
986
function give_get_payment_meta_user_info( $payment_id ) {
987
	$payment = new Give_Payment( $payment_id );
988
989
	return $payment->user_info;
990
}
991
992
/**
993
 * Get the donations Key from Payment Meta
994
 *
995
 * Retrieves the form_id from a (Previously titled give_get_payment_meta_donations)
996
 *
997
 * @since 1.0
998
 *
999
 * @param int $payment_id Payment ID.
1000
 *
1001
 * @return int $form_id Form ID.
1002
 */
1003
function give_get_payment_form_id( $payment_id ) {
1004
	$payment = new Give_Payment( $payment_id );
1005
1006
	return $payment->form_id;
1007
}
1008
1009
/**
1010
 * Get the user email associated with a payment
1011
 *
1012
 * @since 1.0
1013
 *
1014
 * @param int $payment_id Payment ID.
1015
 *
1016
 * @return string $email User email.
1017
 */
1018
function give_get_payment_user_email( $payment_id ) {
1019
	$payment = new Give_Payment( $payment_id );
1020
1021
	return $payment->email;
1022
}
1023
1024
/**
1025
 * Is the payment provided associated with a user account
1026
 *
1027
 * @since  1.3
1028
 *
1029
 * @param  int $payment_id The payment ID.
1030
 *
1031
 * @return bool $is_guest_payment If the payment is associated with a user (false) or not (true)
1032
 */
1033
function give_is_guest_payment( $payment_id ) {
1034
	$payment_user_id  = give_get_payment_user_id( $payment_id );
1035
	$is_guest_payment = ! empty( $payment_user_id ) && $payment_user_id > 0 ? false : true;
1036
1037
	return (bool) apply_filters( 'give_is_guest_payment', $is_guest_payment, $payment_id );
1038
}
1039
1040
/**
1041
 * Get the user ID associated with a payment
1042
 *
1043
 * @since 1.3
1044
 *
1045
 * @param int $payment_id Payment ID.
1046
 *
1047
 * @return int $user_id User ID.
1048
 */
1049
function give_get_payment_user_id( $payment_id ) {
1050
	$payment = new Give_Payment( $payment_id );
1051
1052
	return $payment->user_id;
1053
}
1054
1055
/**
1056
 * Get the donor ID associated with a payment.
1057
 *
1058
 * @since 1.0
1059
 *
1060
 * @param int $payment_id Payment ID.
1061
 *
1062
 * @return int $payment->customer_id Donor ID.
1063
 */
1064
function give_get_payment_donor_id( $payment_id ) {
1065
	$payment = new Give_Payment( $payment_id );
1066
1067
	return $payment->customer_id;
1068
}
1069
1070
/**
1071
 * Get the IP address used to make a donation
1072
 *
1073
 * @since 1.0
1074
 *
1075
 * @param int $payment_id Payment ID.
1076
 *
1077
 * @return string $ip User IP.
1078
 */
1079
function give_get_payment_user_ip( $payment_id ) {
1080
	$payment = new Give_Payment( $payment_id );
1081
1082
	return $payment->ip;
1083
}
1084
1085
/**
1086
 * Get the date a payment was completed
1087
 *
1088
 * @since 1.0
1089
 *
1090
 * @param int $payment_id Payment ID.
1091
 *
1092
 * @return string $date The date the payment was completed.
1093
 */
1094
function give_get_payment_completed_date( $payment_id = 0 ) {
1095
	$payment = new Give_Payment( $payment_id );
1096
1097
	return $payment->completed_date;
1098
}
1099
1100
/**
1101
 * Get the gateway associated with a payment
1102
 *
1103
 * @since 1.0
1104
 *
1105
 * @param int $payment_id Payment ID.
1106
 *
1107
 * @return string $gateway Gateway.
1108
 */
1109
function give_get_payment_gateway( $payment_id ) {
1110
	$payment = new Give_Payment( $payment_id );
1111
1112
	return $payment->gateway;
1113
}
1114
1115
/**
1116
 * Get the currency code a payment was made in
1117
 *
1118
 * @since 1.0
1119
 *
1120
 * @param int $payment_id Payment ID.
1121
 *
1122
 * @return string $currency The currency code.
1123
 */
1124
function give_get_payment_currency_code( $payment_id = 0 ) {
1125
	$payment = new Give_Payment( $payment_id );
1126
1127
	return $payment->currency;
1128
}
1129
1130
/**
1131
 * Get the currency name a payment was made in
1132
 *
1133
 * @since 1.0
1134
 *
1135
 * @param int $payment_id Payment ID.
1136
 *
1137
 * @return string $currency The currency name.
1138
 */
1139
function give_get_payment_currency( $payment_id = 0 ) {
1140
	$currency = give_get_payment_currency_code( $payment_id );
1141
1142
	return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
1143
}
1144
1145
/**
1146
 * Get the key for a donation
1147
 *
1148
 * @since 1.0
1149
 *
1150
 * @param int $payment_id Payment ID.
1151
 *
1152
 * @return string $key Donation key.
1153
 */
1154
function give_get_payment_key( $payment_id = 0 ) {
1155
	$payment = new Give_Payment( $payment_id );
1156
1157
	return $payment->key;
1158
}
1159
1160
/**
1161
 * Get the payment order number
1162
 *
1163
 * This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
1164
 *
1165
 * @since 1.0
1166
 *
1167
 * @param int $payment_id Payment ID.
1168
 *
1169
 * @return string $number Payment order number.
1170
 */
1171
function give_get_payment_number( $payment_id = 0 ) {
1172
	$payment = new Give_Payment( $payment_id );
1173
1174
	return $payment->number;
1175
}
1176
1177
/**
1178
 * Formats the payment number with the prefix and postfix
1179
 *
1180
 * @since  1.3
1181
 *
1182
 * @param  int $number The payment number to format.
1183
 *
1184
 * @return string      The formatted payment number.
1185
 */
1186
function give_format_payment_number( $number ) {
1187
1188
	if ( ! give_get_option( 'enable_sequential' ) ) {
1189
		return $number;
1190
	}
1191
1192
	if ( ! is_numeric( $number ) ) {
1193
		return $number;
1194
	}
1195
1196
	$prefix  = give_get_option( 'sequential_prefix' );
1197
	$number  = absint( $number );
1198
	$postfix = give_get_option( 'sequential_postfix' );
1199
1200
	$formatted_number = $prefix . $number . $postfix;
1201
1202
	return apply_filters( 'give_format_payment_number', $formatted_number, $prefix, $number, $postfix );
1203
}
1204
1205
/**
1206
 * Gets the next available order number
1207
 *
1208
 * This is used when inserting a new payment
1209
 *
1210
 * @since 1.0
1211
 * @return string $number The next available payment number.
1212
 */
1213
function give_get_next_payment_number() {
1214
1215
	if ( ! give_get_option( 'enable_sequential' ) ) {
1216
		return false;
1217
	}
1218
1219
	$number           = get_option( 'give_last_payment_number' );
1220
	$start            = give_get_option( 'sequential_start', 1 );
1221
	$increment_number = true;
1222
1223
	if ( false !== $number ) {
1224
1225
		if ( empty( $number ) ) {
1226
1227
			$number           = $start;
1228
			$increment_number = false;
1229
1230
		}
1231
	} else {
1232
1233
		// This case handles the first addition of the new option, as well as if it get's deleted for any reason.
1234
		$payments     = new Give_Payments_Query( array(
1235
			'number'  => 1,
1236
			'order'   => 'DESC',
1237
			'orderby' => 'ID',
1238
			'output'  => 'posts',
1239
			'fields'  => 'ids',
1240
		) );
1241
		$last_payment = $payments->get_payments();
1242
1243
		if ( ! empty( $last_payment ) ) {
1244
1245
			$number = give_get_payment_number( $last_payment[0] );
1246
1247
		}
1248
1249
		if ( ! empty( $number ) && $number !== (int) $last_payment[0] ) {
1250
1251
			$number = give_remove_payment_prefix_postfix( $number );
1252
1253
		} else {
1254
1255
			$number           = $start;
1256
			$increment_number = false;
1257
		}
1258
	}// End if().
1259
1260
	$increment_number = apply_filters( 'give_increment_payment_number', $increment_number, $number );
1261
1262
	if ( $increment_number ) {
1263
		$number ++;
1264
	}
1265
1266
	return apply_filters( 'give_get_next_payment_number', $number );
1267
}
1268
1269
/**
1270
 * Given a given a number, remove the pre/postfix
1271
 *
1272
 * @since  1.3
1273
 *
1274
 * @param  string $number The formatted Current Number to increment.
1275
 *
1276
 * @return string The new Payment number without prefix and postfix.
1277
 */
1278
function give_remove_payment_prefix_postfix( $number ) {
1279
1280
	$prefix  = give_get_option( 'sequential_prefix' );
1281
	$postfix = give_get_option( 'sequential_postfix' );
1282
1283
	// Remove prefix.
1284
	$number = preg_replace( '/' . $prefix . '/', '', $number, 1 );
1285
1286
	// Remove the postfix.
1287
	$length      = strlen( $number );
1288
	$postfix_pos = strrpos( $number, $postfix );
1289
	if ( false !== $postfix_pos ) {
1290
		$number = substr_replace( $number, '', $postfix_pos, $length );
1291
	}
1292
1293
	// Ensure it's a whole number.
1294
	$number = intval( $number );
1295
1296
	return apply_filters( 'give_remove_payment_prefix_postfix', $number, $prefix, $postfix );
1297
1298
}
1299
1300
1301
/**
1302
 * Get Payment Amount
1303
 *
1304
 * Get the fully formatted payment amount. The payment amount is retrieved using give_get_payment_amount() and is then
1305
 * sent through give_currency_filter() and  give_format_amount() to format the amount correctly.
1306
 *
1307
 * @since       1.0
1308
 *
1309
 * @param int $payment_id Payment ID.
1310
 *
1311
 * @return string $amount Fully formatted payment amount.
1312
 */
1313
function give_payment_amount( $payment_id = 0 ) {
1314
	$amount = give_get_payment_amount( $payment_id );
1315
1316
	return give_currency_filter( give_format_amount( $amount, array( 'sanitize' => false ) ), give_get_payment_currency_code( $payment_id ) );
1317
}
1318
1319
/**
1320
 * Get the amount associated with a payment
1321
 *
1322
 * @access public
1323
 * @since  1.0
1324
 *
1325
 * @param int $payment_id Payment ID.
1326
 *
1327
 * @return mixed
1328
 */
1329
function give_get_payment_amount( $payment_id ) {
1330
1331
	$payment = new Give_Payment( $payment_id );
1332
1333
	return apply_filters( 'give_payment_amount', floatval( $payment->total ), $payment_id );
1334
}
1335
1336
/**
1337
 * Payment Subtotal
1338
 *
1339
 * Retrieves subtotal for payment and then returns a full formatted amount. This
1340
 * function essentially calls give_get_payment_subtotal()
1341
 *
1342
 * @since 1.5
1343
 *
1344
 * @param int $payment_id Payment ID.
1345
 *
1346
 * @see   give_get_payment_subtotal()
1347
 *
1348
 * @return array Fully formatted payment subtotal.
1349
 */
1350
function give_payment_subtotal( $payment_id = 0 ) {
1351
	$subtotal = give_get_payment_subtotal( $payment_id );
1352
1353
	return give_currency_filter( give_format_amount( $subtotal , array( 'sanitize' => false ) ), give_get_payment_currency_code( $payment_id ) );
1354
}
1355
1356
/**
1357
 * Get Payment Subtotal
1358
 *
1359
 * Retrieves subtotal for payment and then returns a non formatted amount.
1360
 *
1361
 * @since 1.5
1362
 *
1363
 * @param int $payment_id Payment ID.
1364
 *
1365
 * @return float $subtotal Subtotal for payment (non formatted).
1366
 */
1367
function give_get_payment_subtotal( $payment_id = 0 ) {
1368
	$payment = new Give_Payment( $payment_id );
1369
1370
	return $payment->subtotal;
1371
}
1372
1373
/**
1374
 * Retrieves the donation ID
1375
 *
1376
 * @since  1.0
1377
 *
1378
 * @param int $payment_id Payment ID.
1379
 *
1380
 * @return string The donation ID.
1381
 */
1382
function give_get_payment_transaction_id( $payment_id = 0 ) {
1383
	$payment = new Give_Payment( $payment_id );
1384
1385
	return $payment->transaction_id;
1386
}
1387
1388
/**
1389
 * Sets a Transaction ID in post meta for the given Payment ID.
1390
 *
1391
 * @since  1.0
1392
 *
1393
 * @param int    $payment_id     Payment ID.
1394
 * @param string $transaction_id The transaction ID from the gateway.
1395
 *
1396
 * @return bool|mixed
1397
 */
1398
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1399
1400
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1401
		return false;
1402
	}
1403
1404
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1405
1406
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1407
}
1408
1409
/**
1410
 * Retrieve the donation ID based on the key
1411
 *
1412
 * @since 1.0
1413
 * @global object $wpdb Used to query the database using the WordPress Database API.
1414
 *
1415
 * @param string $key  the key to search for.
1416
 *
1417
 * @return int $purchase Donation ID.
1418
 */
1419 View Code Duplication
function give_get_purchase_id_by_key( $key ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

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

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

Loading history...
1420
	global $wpdb;
1421
	$meta_table = __give_v20_bc_table_details( 'payment' );
1422
1423
	$purchase = $wpdb->get_var( $wpdb->prepare( "SELECT {$meta_table['column']['id']} FROM {$meta_table['name']} WHERE meta_key = '_give_payment_purchase_key' AND meta_value = %s LIMIT 1", $key ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
1424
1425
	if ( $purchase != null ) {
1426
		return $purchase;
1427
	}
1428
1429
	return 0;
1430
}
1431
1432
1433
/**
1434
 * Retrieve the donation ID based on the transaction ID
1435
 *
1436
 * @since 1.3
1437
 * @global object $wpdb Used to query the database using the WordPress Database API.
1438
 *
1439
 * @param string $key  The transaction ID to search for.
1440
 *
1441
 * @return int $purchase Donation ID.
1442
 */
1443 View Code Duplication
function give_get_purchase_id_by_transaction_id( $key ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

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

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

Loading history...
1444
	global $wpdb;
1445
	$meta_table = __give_v20_bc_table_details('payment');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
1446
1447
	$purchase = $wpdb->get_var( $wpdb->prepare( "SELECT {$meta_table['column']['id']} FROM {$meta_table['name']} WHERE meta_key = '_give_payment_transaction_id' AND meta_value = %s LIMIT 1", $key ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
1448
1449
	if ( $purchase != null ) {
1450
		return $purchase;
1451
	}
1452
1453
	return 0;
1454
}
1455
1456
/**
1457
 * Retrieve all notes attached to a donation
1458
 *
1459
 * @since 1.0
1460
 *
1461
 * @param int    $payment_id The donation ID to retrieve notes for.
1462
 * @param string $search     Search for notes that contain a search term.
1463
 *
1464
 * @return array $notes Donation Notes
1465
 */
1466
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1467
1468
	if ( empty( $payment_id ) && empty( $search ) ) {
1469
		return false;
1470
	}
1471
1472
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1473
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1474
1475
	$notes = get_comments( array(
1476
		'post_id' => $payment_id,
1477
		'order' => 'ASC',
1478
		'search' => $search,
1479
	) );
1480
1481
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1482
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1483
1484
	return $notes;
1485
}
1486
1487
1488
/**
1489
 * Add a note to a payment
1490
 *
1491
 * @since 1.0
1492
 *
1493
 * @param int    $payment_id The payment ID to store a note for.
1494
 * @param string $note       The note to store.
1495
 *
1496
 * @return int The new note ID
1497
 */
1498
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1499
	if ( empty( $payment_id ) ) {
1500
		return false;
1501
	}
1502
1503
	/**
1504
	 * Fires before inserting payment note.
1505
	 *
1506
	 * @since 1.0
1507
	 *
1508
	 * @param int    $payment_id Payment ID.
1509
	 * @param string $note       The note.
1510
	 */
1511
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1512
1513
	$note_id = wp_insert_comment( wp_filter_comment( array(
1514
		'comment_post_ID'      => $payment_id,
1515
		'comment_content'      => $note,
1516
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1517
		'comment_date'         => current_time( 'mysql' ),
1518
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1519
		'comment_approved'     => 1,
1520
		'comment_parent'       => 0,
1521
		'comment_author'       => '',
1522
		'comment_author_IP'    => '',
1523
		'comment_author_url'   => '',
1524
		'comment_author_email' => '',
1525
		'comment_type'         => 'give_payment_note',
1526
1527
	) ) );
1528
1529
	/**
1530
	 * Fires after payment note inserted.
1531
	 *
1532
	 * @since 1.0
1533
	 *
1534
	 * @param int    $note_id    Note ID.
1535
	 * @param int    $payment_id Payment ID.
1536
	 * @param string $note       The note.
1537
	 */
1538
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1539
1540
	return $note_id;
1541
}
1542
1543
/**
1544
 * Deletes a payment note
1545
 *
1546
 * @since 1.0
1547
 *
1548
 * @param int $comment_id The comment ID to delete.
1549
 * @param int $payment_id The payment ID the note is connected to.
1550
 *
1551
 * @return bool True on success, false otherwise.
1552
 */
1553
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1554
	if ( empty( $comment_id ) ) {
1555
		return false;
1556
	}
1557
1558
	/**
1559
	 * Fires before deleting donation note.
1560
	 *
1561
	 * @since 1.0
1562
	 *
1563
	 * @param int $comment_id Note ID.
1564
	 * @param int $payment_id Payment ID.
1565
	 */
1566
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1567
1568
	$ret = wp_delete_comment( $comment_id, true );
1569
1570
	/**
1571
	 * Fires after donation note deleted.
1572
	 *
1573
	 * @since 1.0
1574
	 *
1575
	 * @param int $comment_id Note ID.
1576
	 * @param int $payment_id Payment ID.
1577
	 */
1578
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1579
1580
	return $ret;
1581
}
1582
1583
/**
1584
 * Gets the payment note HTML
1585
 *
1586
 * @since 1.0
1587
 *
1588
 * @param object|int $note       The comment object or ID.
1589
 * @param int        $payment_id The payment ID the note is connected to.
1590
 *
1591
 * @return string
1592
 */
1593
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1594
1595
	if ( is_numeric( $note ) ) {
1596
		$note = get_comment( $note );
1597
	}
1598
1599
	if ( ! empty( $note->user_id ) ) {
1600
		$user = get_userdata( $note->user_id );
1601
		$user = $user->display_name;
1602
	} else {
1603
		$user = esc_html__( 'System', 'give' );
1604
	}
1605
1606
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1607
1608
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1609
		'give-action' => 'delete_payment_note',
1610
		'note_id'     => $note->comment_ID,
1611
		'payment_id'  => $payment_id,
1612
	) ), 'give_delete_payment_note_' . $note->comment_ID );
1613
1614
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1615
	$note_html .= '<p>';
1616
	$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/>';
1617
	$note_html .= $note->comment_content;
1618
	$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>';
1619
	$note_html .= '</p>';
1620
	$note_html .= '</div>';
1621
1622
	return $note_html;
1623
1624
}
1625
1626
/**
1627
 * Exclude notes (comments) on give_payment post type from showing in Recent
1628
 * Comments widgets
1629
 *
1630
 * @since 1.0
1631
 *
1632
 * @param object $query WordPress Comment Query Object.
1633
 *
1634
 * @return void
1635
 */
1636
function give_hide_payment_notes( $query ) {
1637
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1638
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1639
		if ( ! is_array( $types ) ) {
1640
			$types = array( $types );
1641
		}
1642
		$types[]                           = 'give_payment_note';
1643
		$query->query_vars['type__not_in'] = $types;
1644
	}
1645
}
1646
1647
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1648
1649
/**
1650
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1651
 *
1652
 * @since 1.0
1653
 *
1654
 * @param array  $clauses          Comment clauses for comment query.
1655
 * @param object $wp_comment_query WordPress Comment Query Object.
1656
 *
1657
 * @return array $clauses Updated comment clauses.
1658
 */
1659
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...
1660
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1661
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1662
	}
1663
1664
	return $clauses;
1665
}
1666
1667
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1668
1669
1670
/**
1671
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1672
 *
1673
 * @since 1.0
1674
 *
1675
 * @param string $where
1676
 * @param object $wp_comment_query WordPress Comment Query Object.
1677
 *
1678
 * @return string $where
1679
 */
1680
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...
1681
	global $wpdb;
1682
1683
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1684
1685
	return $where;
1686
}
1687
1688
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1689
1690
1691
/**
1692
 * Remove Give Comments from the wp_count_comments function
1693
 *
1694
 * @access public
1695
 * @since  1.0
1696
 *
1697
 * @param array $stats   (empty from core filter).
1698
 * @param int   $post_id Post ID.
1699
 *
1700
 * @return array Array of comment counts.
1701
 */
1702
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1703
	global $wpdb, $pagenow;
1704
1705
	if ( 'index.php' != $pagenow ) {
1706
		return $stats;
1707
	}
1708
1709
	$post_id = (int) $post_id;
1710
1711
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1712
		return $stats;
1713
	}
1714
1715
	$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
1716
1717
	if ( false !== $stats ) {
1718
		return $stats;
1719
	}
1720
1721
	$where = 'WHERE comment_type != "give_payment_note"';
1722
1723
	if ( $post_id > 0 ) {
1724
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1725
	}
1726
1727
	$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1728
1729
	$total    = 0;
1730
	$approved = array(
1731
		'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
1732
		'1'            => 'approved',
1733
		'spam'         => 'spam',
1734
		'trash'        => 'trash',
1735
		'post-trashed' => 'post-trashed',
1736
	);
1737
	foreach ( (array) $count as $row ) {
1738
		// Don't count post-trashed toward totals.
1739
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1740
			$total += $row['num_comments'];
1741
		}
1742
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1743
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1744
		}
1745
	}
1746
1747
	$stats['total_comments'] = $total;
1748
	foreach ( $approved as $key ) {
1749
		if ( empty( $stats[ $key ] ) ) {
1750
			$stats[ $key ] = 0;
1751
		}
1752
	}
1753
1754
	$stats = (object) $stats;
1755
	wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
1756
1757
	return $stats;
1758
}
1759
1760
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1761
1762
1763
/**
1764
 * Filter where older than one week
1765
 *
1766
 * @access public
1767
 * @since  1.0
1768
 *
1769
 * @param string $where Where clause.
1770
 *
1771
 * @return string $where Modified where clause.
1772
 */
1773
function give_filter_where_older_than_week( $where = '' ) {
1774
	// Payments older than one week.
1775
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1776
	$where .= " AND post_date <= '{$start}'";
1777
1778
	return $where;
1779
}
1780
1781
1782
/**
1783
 * Get Payment Form ID.
1784
 *
1785
 * Retrieves the form title and appends the level name if present.
1786
 *
1787
 * @since 1.5
1788
 *
1789
 * @param array  $payment_meta Payment meta data.
1790
 * @param bool   $only_level   If set to true will only return the level name if multi-level enabled.
1791
 * @param string $separator    The separator between the .
1792
 *
1793
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1794
 */
1795
function give_get_payment_form_title( $payment_meta, $only_level = false, $separator = '' ) {
1796
1797
	$form_id    = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
1798
	$price_id   = isset( $payment_meta['price_id'] ) ? $payment_meta['price_id'] : null;
1799
	$form_title = isset( $payment_meta['form_title'] ) ? $payment_meta['form_title'] : '';
1800
1801
	if ( $only_level == true ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
introduced by
Found "== true". Use Yoda Condition checks, you must
Loading history...
1802
		$form_title = '';
1803
	}
1804
1805
	// If multi-level, append to the form title.
1806
	if ( give_has_variable_prices( $form_id ) ) {
1807
1808
		// Only add separator if there is a form title.
1809
		if ( ! empty( $form_title ) ) {
1810
			$form_title .= ' ' . $separator . ' ';
1811
		}
1812
1813
		$form_title .= '<span class="donation-level-text-wrap">';
1814
1815
		if ( $price_id == 'custom' ) {
0 ignored issues
show
introduced by
Found "== '". Use Yoda Condition checks, you must
Loading history...
1816
			$custom_amount_text = give_get_meta( $form_id, '_give_custom_amount_text', true );
1817
			$form_title         .= ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1818
		} else {
1819
			$form_title .= give_get_price_option_name( $form_id, $price_id );
1820
		}
1821
1822
		$form_title .= '</span>';
1823
1824
	}
1825
1826
	return apply_filters( 'give_get_payment_form_title', $form_title, $payment_meta );
1827
1828
}
1829
1830
/**
1831
 * Get Price ID
1832
 *
1833
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1834
 *
1835
 * @param int    $form_id Form ID.
1836
 * @param string $price   Price ID.
1837
 *
1838
 * @return string $price_id
1839
 */
1840
function give_get_price_id( $form_id, $price ) {
1841
1842
	$price_id = 0;
1843
1844
	if ( give_has_variable_prices( $form_id ) ) {
1845
1846
		$levels = maybe_unserialize( give_get_meta( $form_id, '_give_donation_levels', true ) );
1847
1848
		foreach ( $levels as $level ) {
1849
1850
			$level_amount = (float) give_maybe_sanitize_amount( $level['_give_amount'] );
1851
1852
			// Check that this indeed the recurring price.
1853
			if ( $level_amount == $price ) {
1854
1855
				$price_id = $level['_give_id']['level_id'];
1856
1857
			}
1858
		}
1859
	}
1860
1861
	return $price_id;
1862
1863
}
1864
1865
/**
1866
 * Get/Print give form dropdown html
1867
 *
1868
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1869
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1870
 *
1871
 * @since 1.6
1872
 *
1873
 * @param array $args Arguments for form dropdown.
1874
 * @param bool  $echo This parameter decides if print form dropdown html output or not.
1875
 *
1876
 * @return string
1877
 */
1878
function give_get_form_dropdown( $args = array(), $echo = false ) {
1879
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1880
1881
	if ( ! $echo ) {
1882
		return $form_dropdown_html;
1883
	}
1884
1885
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1886
}
1887
1888
/**
1889
 * Get/Print give form variable price dropdown html
1890
 *
1891
 * @since 1.6
1892
 *
1893
 * @param array $args Arguments for form dropdown.
1894
 * @param bool  $echo This parameter decide if print form dropdown html output or not.
1895
 *
1896
 * @return string|bool
1897
 */
1898
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1899
1900
	// Check for give form id.
1901
	if ( empty( $args['id'] ) ) {
1902
		return false;
1903
	}
1904
1905
	$form = new Give_Donate_Form( $args['id'] );
1906
1907
	// Check if form has variable prices or not.
1908
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1909
		return false;
1910
	}
1911
1912
	$variable_prices        = $form->get_prices();
1913
	$variable_price_options = array();
1914
1915
	// Check if multi donation form support custom donation or not.
1916
	if ( $form->is_custom_price_mode() ) {
1917
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1918
	}
1919
1920
	// Get variable price and ID from variable price array.
1921
	foreach ( $variable_prices as $variable_price ) {
1922
		$variable_price_options[ $variable_price['_give_id']['level_id'] ] = ! empty( $variable_price['_give_text'] ) ? $variable_price['_give_text'] : give_currency_filter( give_format_amount( $variable_price['_give_amount'], array( 'sanitize' => false ) ) );
1923
	}
1924
1925
	// Update options.
1926
	$args = array_merge( $args, array(
1927
		'options' => $variable_price_options,
1928
	) );
1929
1930
	// Generate select html.
1931
	$form_dropdown_html = Give()->html->select( $args );
1932
1933
	if ( ! $echo ) {
1934
		return $form_dropdown_html;
1935
	}
1936
1937
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1938
}
1939
1940
/**
1941
 * Get the price_id from the payment meta.
1942
 *
1943
 * Some gateways use `give_price_id` and others were using just `price_id`;
1944
 * This checks for the difference and falls back to retrieving it from the form as a last resort.
1945
 *
1946
 * @since 1.8.6
1947
 *
1948
 * @param $payment_meta
1949
 *
1950
 * @return string
1951
 */
1952
function give_get_payment_meta_price_id( $payment_meta ) {
1953
1954
	if ( isset( $payment_meta['give_price_id'] ) ) {
1955
		$price_id = $payment_meta['give_price_id'];
1956
	} elseif ( isset( $payment_meta['price_id'] ) ) {
1957
		$price_id = $payment_meta['price_id'];
1958
	} else {
1959
		$price_id = give_get_price_id( $payment_meta['give_form_id'], $payment_meta['price'] );
1960
	}
1961
1962
	return apply_filters( 'give_get_payment_meta_price_id', $price_id );
1963
1964
}
1965