Completed
Push — issues/2912 ( d8ec76...72f6bd )
by Ravinder
1197:19 queued 1189:23
created

functions.php ➔ give_get_payment_subtotal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
174
	$payment->key            = $payment_data['purchase_key'];
175
	$payment->mode           = ( ! empty( $payment_data['mode'] ) ? (string) $payment_data['mode'] : ( give_is_test_mode() ? 'test' : 'live' ) );
176
	$payment->parent_payment = ! empty( $payment_data['parent'] ) ? absint( $payment_data['parent'] ) : '';
177
178
	// Add the donation.
179
	$args = array(
180
		'price'    => $payment->total,
181
		'price_id' => $payment->price_id,
182
	);
183
184
	$payment->add_donation( $payment->form_id, $args );
185
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
186
187
	// Set date if present.
188
	if ( isset( $payment_data['post_date'] ) ) {
189
		$payment->date = $payment_data['post_date'];
190
	}
191
192
	// Save payment.
193
	$payment->save();
194
195
	/**
196
	 * Fires while inserting payments.
197
	 *
198
	 * @since 1.0
199
	 *
200
	 * @param int   $payment_id   The payment ID.
201
	 * @param array $payment_data Arguments passed.
202
	 */
203
	do_action( 'give_insert_payment', $payment->ID, $payment_data );
204
205
	// Return payment ID upon success.
206
	if ( ! empty( $payment->ID ) ) {
207
		return $payment->ID;
208
	}
209
210
	// Return false if no payment was inserted.
211
	return false;
212
213
}
214
215
/**
216
 * Create payment.
217
 *
218
 * @param $payment_data
219
 *
220
 * @return bool|int
221
 */
222
function give_create_payment( $payment_data ) {
223
224
	$form_id  = intval( $payment_data['post_data']['give-form-id'] );
225
	$price_id = isset( $payment_data['post_data']['give-price-id'] ) ? $payment_data['post_data']['give-price-id'] : '';
226
227
	// Collect payment data.
228
	$insert_payment_data = array(
229
		'price'           => $payment_data['price'],
230
		'give_form_title' => $payment_data['post_data']['give-form-title'],
231
		'give_form_id'    => $form_id,
232
		'give_price_id'   => $price_id,
233
		'date'            => $payment_data['date'],
234
		'user_email'      => $payment_data['user_email'],
235
		'purchase_key'    => $payment_data['purchase_key'],
236
		'currency'        => give_get_currency( $form_id, $payment_data ),
237
		'user_info'       => $payment_data['user_info'],
238
		'status'          => 'pending',
239
		'gateway'         => 'paypal',
240
	);
241
242
	/**
243
	 * Filter the payment params.
244
	 *
245
	 * @since 1.8
246
	 *
247
	 * @param array $insert_payment_data
248
	 */
249
	$insert_payment_data = apply_filters( 'give_create_payment', $insert_payment_data );
250
251
	// Record the pending payment.
252
	return give_insert_payment( $insert_payment_data );
253
}
254
255
/**
256
 * Updates a payment status.
257
 *
258
 * @param  int    $payment_id Payment ID.
259
 * @param  string $new_status New Payment Status. Default is 'publish'.
260
 *
261
 * @since  1.0
262
 *
263
 * @return bool
264
 */
265
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
266
267
	$updated = false;
268
	$payment = new Give_Payment( $payment_id );
269
270
	if ( $payment && $payment->ID > 0 ) {
271
272
		$payment->status = $new_status;
273
		$updated         = $payment->save();
274
275
	}
276
277
	return $updated;
278
}
279
280
281
/**
282
 * Deletes a Donation
283
 *
284
 * @since  1.0
285
 *
286
 * @param  int  $payment_id   Payment ID (default: 0).
287
 * @param  bool $update_donor If we should update the donor stats (default:true).
288
 *
289
 * @return void
290
 */
291
function give_delete_donation( $payment_id = 0, $update_donor = true ) {
292
	$payment = new Give_Payment( $payment_id );
293
294
	// Bailout.
295
	if ( ! $payment->ID ) {
296
		return;
297
	}
298
299
	$amount   = give_donation_amount( $payment_id );
300
	$status   = $payment->post_status;
301
	$donor_id = give_get_payment_donor_id( $payment_id );
302
	$donor    = new Give_Donor( $donor_id );
303
304
	// Only undo donations that aren't these statuses.
305
	$dont_undo_statuses = apply_filters( 'give_undo_donation_statuses', array(
306
		'pending',
307
		'cancelled',
308
	) );
309
310
	if ( ! in_array( $status, $dont_undo_statuses ) ) {
311
		give_undo_donation( $payment_id );
312
	}
313
314
	// Only undo donations that aren't these statuses.
315
	$status_to_decrease_stats = apply_filters( 'give_decrease_donor_statuses', array( 'publish' ) );
316
317
	if ( in_array( $status, $status_to_decrease_stats ) ) {
318
319
		// Only decrease earnings if they haven't already been decreased (or were never increased for this payment).
320
		give_decrease_total_earnings( $amount );
321
322
		// @todo: Refresh only range related stat cache
323
		give_delete_donation_stats();
324
325
		if ( $donor->id && $update_donor ) {
326
327
			// Decrement the stats for the donor.
328
			$donor->decrease_donation_count();
329
			$donor->decrease_value( $amount );
330
331
		}
332
	}
333
334
	/**
335
	 * Fires before deleting payment.
336
	 *
337
	 * @param int $payment_id Payment ID.
338
	 *
339
	 * @since 1.0
340
	 */
341
	do_action( 'give_payment_delete', $payment_id );
342
343
	if ( $donor->id && $update_donor ) {
344
		// Remove the payment ID from the donor.
345
		$donor->remove_payment( $payment_id );
346
	}
347
348
	// Remove the payment.
349
	wp_delete_post( $payment_id, true );
350
351
	// Remove related sale log entries.
352
	Give()->logs->delete_logs( $payment_id );
353
354
	/**
355
	 * Fires after payment deleted.
356
	 *
357
	 * @param int $payment_id Payment ID.
358
	 *
359
	 * @since 1.0
360
	 */
361
	do_action( 'give_payment_deleted', $payment_id );
362
}
363
364
/**
365
 * Undo Donation
366
 *
367
 * Undoes a donation, including the decrease of donations and earning stats.
368
 * Used for when refunding or deleting a donation.
369
 *
370
 * @param  int $payment_id Payment ID.
371
 *
372
 * @since  1.0
373
 *
374
 * @return void
375
 */
376
function give_undo_donation( $payment_id ) {
377
378
	$payment = new Give_Payment( $payment_id );
379
380
	$maybe_decrease_earnings = apply_filters( 'give_decrease_earnings_on_undo', true, $payment, $payment->form_id );
381
	if ( true === $maybe_decrease_earnings ) {
382
		// Decrease earnings.
383
		give_decrease_form_earnings( $payment->form_id, $payment->total );
384
	}
385
386
	$maybe_decrease_donations = apply_filters( 'give_decrease_donations_on_undo', true, $payment, $payment->form_id );
387
	if ( true === $maybe_decrease_donations ) {
388
		// Decrease donation count.
389
		give_decrease_donation_count( $payment->form_id );
390
	}
391
392
}
393
394
395
/**
396
 * Count Payments
397
 *
398
 * Returns the total number of payments recorded.
399
 *
400
 * @param  array $args Arguments passed.
401
 *
402
 * @since  1.0
403
 *
404
 * @return object $stats Contains the number of payments per payment status.
405
 */
406
function give_count_payments( $args = array() ) {
407
	// Backward compatibility.
408
	if ( ! empty( $args['start-date'] ) ) {
409
		$args['start_date'] = $args['start-date'];
410
		unset( $args['start-date'] );
411
	}
412
413
	if ( ! empty( $args['end-date'] ) ) {
414
		$args['end_date'] = $args['end-date'];
415
		unset( $args['end-date'] );
416
	}
417
418
	if ( ! empty( $args['form_id'] ) ) {
419
		$args['give_forms'] = $args['form_id'];
420
		unset( $args['form_id'] );
421
	}
422
423
	// Extract all donations
424
	$args['number']      = - 1;
425
	$args['group_by']    = 'post_status';
426
	$args['count']       = 'true';
427
428
	$donations_obj   = new Give_Payments_Query( $args );
429
	$donations_count = $donations_obj->get_payment_by_group();
430
431
	/**
432
	 * Filter the payment counts group by status
433
	 *
434
	 * @since 1.0
435
	 */
436
	return (object) apply_filters( 'give_count_payments', $donations_count, $args, $donations_obj );
437
}
438
439
440
/**
441
 * Check For Existing Payment
442
 *
443
 * @param  int $payment_id Payment ID.
444
 *
445
 * @since  1.0
446
 *
447
 * @return bool $exists True if payment exists, false otherwise.
448
 */
449
function give_check_for_existing_payment( $payment_id ) {
450
	$exists  = false;
451
	$payment = new Give_Payment( $payment_id );
452
453
	if ( $payment_id === $payment->ID && 'publish' === $payment->status ) {
454
		$exists = true;
455
	}
456
457
	return $exists;
458
}
459
460
/**
461
 * Get Payment Status
462
 *
463
 * @param WP_Post|Give_Payment|int $payment      Payment object or payment ID.
464
 * @param bool                     $return_label Whether to return the translated status label instead of status value.
465
 *                                               Default false.
466
 *
467
 * @since 1.0
468
 *
469
 * @return bool|mixed True if payment status exists, false otherwise.
470
 */
471
function give_get_payment_status( $payment, $return_label = false ) {
472
473
	if ( is_numeric( $payment ) ) {
474
475
		$payment = new Give_Payment( $payment );
476
477
		if ( ! $payment->ID > 0 ) {
478
			return false;
479
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
480
481
	}
482
483
	if ( ! is_object( $payment ) || ! isset( $payment->post_status ) ) {
484
		return false;
485
	}
486
487
	$statuses = give_get_payment_statuses();
488
489
	if ( ! is_array( $statuses ) || empty( $statuses ) ) {
490
		return false;
491
	}
492
493
	// Get payment object if not already given.
494
	$payment = $payment instanceof Give_Payment ? $payment : new Give_Payment( $payment->ID );
495
496
	if ( array_key_exists( $payment->status, $statuses ) ) {
497
		if ( true === $return_label ) {
498
			// Return translated status label.
499
			return $statuses[ $payment->status ];
500
		} else {
501
			// Account that our 'publish' status is labeled 'Complete'
502
			$post_status = 'publish' === $payment->status ? 'Complete' : $payment->post_status;
503
504
			// Make sure we're matching cases, since they matter
505
			return array_search( strtolower( $post_status ), array_map( 'strtolower', $statuses ) );
506
		}
507
	}
508
509
	return false;
510
}
511
512
/**
513
 * Retrieves all available statuses for payments.
514
 *
515
 * @since  1.0
516
 *
517
 * @return array $payment_status All the available payment statuses.
518
 */
519
function give_get_payment_statuses() {
520
	$payment_statuses = array(
521
		'pending'     => __( 'Pending', 'give' ),
522
		'publish'     => __( 'Complete', 'give' ),
523
		'refunded'    => __( 'Refunded', 'give' ),
524
		'failed'      => __( 'Failed', 'give' ),
525
		'cancelled'   => __( 'Cancelled', 'give' ),
526
		'abandoned'   => __( 'Abandoned', 'give' ),
527
		'preapproval' => __( 'Pre-Approved', 'give' ),
528
		'processing'  => __( 'Processing', 'give' ),
529
		'revoked'     => __( 'Revoked', 'give' ),
530
	);
531
532
	return apply_filters( 'give_payment_statuses', $payment_statuses );
533
}
534
535
/**
536
 * Get Payment Status Keys
537
 *
538
 * Retrieves keys for all available statuses for payments
539
 *
540
 * @since 1.0
541
 *
542
 * @return array $payment_status All the available payment statuses.
543
 */
544
function give_get_payment_status_keys() {
545
	$statuses = array_keys( give_get_payment_statuses() );
546
	asort( $statuses );
547
548
	return array_values( $statuses );
549
}
550
551
/**
552
 * Get Earnings By Date
553
 *
554
 * @param int $day       Day number. Default is null.
555
 * @param int $month_num Month number. Default is null.
556
 * @param int $year      Year number. Default is null.
557
 * @param int $hour      Hour number. Default is null.
558
 *
559
 * @since 1.0
560
 *
561
 * @return int $earnings Earnings
562
 */
563
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
564
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead.
565
566
	global $wpdb;
567
	$meta_table = __give_v20_bc_table_details( 'payment' );
0 ignored issues
show
Unused Code introduced by
$meta_table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
568
569
	$args = array(
570
		'post_type'              => 'give_payment',
571
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
572
		'year'                   => $year,
573
		'monthnum'               => $month_num,
574
		'post_status'            => array( 'publish' ),
575
		'fields'                 => 'ids',
576
		'update_post_term_cache' => false,
577
	);
578
	if ( ! empty( $day ) ) {
579
		$args['day'] = $day;
580
	}
581
582
	if ( isset( $hour ) ) {
583
		$args['hour'] = $hour;
584
	}
585
586
	$args = apply_filters( 'give_get_earnings_by_date_args', $args );
587
	$key  = Give_Cache::get_key( 'give_stats', $args );
588
589 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...
590
		$earnings = false;
591
	} else {
592
		$earnings = Give_Cache::get( $key );
593
	}
594
595
	if ( false === $earnings ) {
596
		$donations = get_posts( $args );
597
		$earnings  = 0;
598
		if ( $donations ) {
599
			$donations      = implode( ',', $donations );
600
			$earning_totals = $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN ({$donations})" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
601
602
			/**
603
			 * Filter The earnings by dates.
604
			 *
605
			 * @since 1.8.17
606
			 *
607
			 * @param float $earning_totals Total earnings between the dates.
608
			 * @param array $donations      Donations lists.
609
			 * @param array $args           Donation query args.
610
			 */
611
			$earnings = apply_filters( 'give_get_earnings_by_date', $earning_totals, $donations, $args );
612
		}
613
		// Cache the results for one hour.
614
		Give_Cache::set( $key, $earnings, HOUR_IN_SECONDS );
615
	}
616
617
	return round( $earnings, 2 );
618
}
619
620
/**
621
 * Get Donations (sales) By Date
622
 *
623
 * @param int $day       Day number. Default is null.
624
 * @param int $month_num Month number. Default is null.
625
 * @param int $year      Year number. Default is null.
626
 * @param int $hour      Hour number. Default is null.
627
 *
628
 * @since 1.0
629
 *
630
 * @return int $count Sales
631
 */
632
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
633
634
	// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead.
635
	$args = array(
636
		'post_type'              => 'give_payment',
637
		'nopaging'               => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
638
		'year'                   => $year,
639
		'fields'                 => 'ids',
640
		'post_status'            => array( 'publish' ),
641
		'update_post_meta_cache' => false,
642
		'update_post_term_cache' => false,
643
	);
644
645
	$show_free = apply_filters( 'give_sales_by_date_show_free', true, $args );
646
647
	if ( false === $show_free ) {
648
		$args['meta_query'] = array(
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
649
			array(
650
				'key'     => '_give_payment_total',
651
				'value'   => 0,
652
				'compare' => '>',
653
				'type'    => 'NUMERIC',
654
			),
655
		);
656
	}
657
658
	if ( ! empty( $month_num ) ) {
659
		$args['monthnum'] = $month_num;
660
	}
661
662
	if ( ! empty( $day ) ) {
663
		$args['day'] = $day;
664
	}
665
666
	if ( isset( $hour ) ) {
667
		$args['hour'] = $hour;
668
	}
669
670
	$args = apply_filters( 'give_get_sales_by_date_args', $args );
671
672
	$key = Give_Cache::get_key( 'give_stats', $args );
673
674 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...
675
		$count = false;
676
	} else {
677
		$count = Give_Cache::get( $key );
678
	}
679
680
	if ( false === $count ) {
681
		$donations = new WP_Query( $args );
682
		$count     = (int) $donations->post_count;
683
		// Cache the results for one hour.
684
		Give_Cache::set( $key, $count, HOUR_IN_SECONDS );
685
	}
686
687
	return $count;
688
}
689
690
/**
691
 * Checks whether a payment has been marked as complete.
692
 *
693
 * @param int $payment_id Payment ID to check against.
694
 *
695
 * @since 1.0
696
 *
697
 * @return bool $ret True if complete, false otherwise.
698
 */
699
function give_is_payment_complete( $payment_id ) {
700
	$payment = new Give_Payment( $payment_id );
701
702
	$ret = false;
703
704
	if ( $payment->ID > 0 ) {
705
706
		if ( (int) $payment_id === (int) $payment->ID && 'publish' == $payment->status ) {
707
			$ret = true;
708
		}
709
	}
710
711
	return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
712
}
713
714
/**
715
 * Get Total Donations.
716
 *
717
 * @since 1.0
718
 *
719
 * @return int $count Total number of donations.
720
 */
721
function give_get_total_donations() {
722
723
	$payments = give_count_payments();
724
725
	return $payments->publish;
726
}
727
728
/**
729
 * Get Total Earnings
730
 *
731
 * @param bool $recalculate Recalculate earnings forcefully.
732
 *
733
 * @since 1.0
734
 *
735
 * @return float $total Total earnings.
736
 */
737
function give_get_total_earnings( $recalculate = false ) {
738
739
	$total      = get_option( 'give_earnings_total', 0 );
740
	$meta_table = __give_v20_bc_table_details( 'payment' );
741
742
	// Calculate total earnings.
743
	if ( ! $total || $recalculate ) {
744
		global $wpdb;
745
746
		$total = (float) 0;
747
748
		$args = apply_filters( 'give_get_total_earnings_args', array(
749
			'offset' => 0,
750
			'number' => - 1,
751
			'status' => array( 'publish' ),
752
			'fields' => 'ids',
753
		) );
754
755
		$payments = give_get_payments( $args );
756
		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...
757
758
			/**
759
			 * If performing a donation, we need to skip the very last payment in the database,
760
			 * since it calls give_increase_total_earnings() on completion,
761
			 * which results in duplicated earnings for the very first donation.
762
			 */
763
			if ( did_action( 'give_update_payment_status' ) ) {
764
				array_pop( $payments );
765
			}
766
767
			if ( ! empty( $payments ) ) {
768
				$payments = implode( ',', $payments );
769
				$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...
770
			}
771
		}
772
773
		update_option( 'give_earnings_total', $total, 'no' );
774
	}
775
776
	if ( $total < 0 ) {
777
		$total = 0; // Don't ever show negative earnings.
778
	}
779
780
	return apply_filters( 'give_total_earnings', round( $total, give_get_price_decimals() ), $total );
781
}
782
783
/**
784
 * Increase the Total Earnings
785
 *
786
 * @param int $amount The amount you would like to increase the total earnings by. Default is 0.
787
 *
788
 * @since 1.0
789
 *
790
 * @return float $total Total earnings.
791
 */
792
function give_increase_total_earnings( $amount = 0 ) {
793
	$total = give_get_total_earnings();
794
	$total += $amount;
795
	update_option( 'give_earnings_total', $total );
796
797
	return $total;
798
}
799
800
/**
801
 * Decrease the Total Earnings
802
 *
803
 * @param int $amount The amount you would like to decrease the total earnings by.
804
 *
805
 * @since 1.0
806
 *
807
 * @return float $total Total earnings.
808
 */
809
function give_decrease_total_earnings( $amount = 0 ) {
810
	$total = give_get_total_earnings();
811
	$total -= $amount;
812
	if ( $total < 0 ) {
813
		$total = 0;
814
	}
815
	update_option( 'give_earnings_total', $total );
816
817
	return $total;
818
}
819
820
/**
821
 * Get Payment Meta for a specific Payment
822
 *
823
 * @param int    $payment_id Payment ID.
824
 * @param string $meta_key   The meta key to pull.
825
 * @param bool   $single     Pull single meta entry or as an object.
826
 *
827
 * @since 1.0
828
 *
829
 * @return mixed $meta Payment Meta.
830
 */
831
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
832
	$payment = new Give_Payment( $payment_id );
833
834
	return $payment->get_meta( $meta_key, $single );
835
}
836
837
/**
838
 * Update the meta for a payment
839
 *
840
 * @param  int    $payment_id Payment ID.
841
 * @param  string $meta_key   Meta key to update.
842
 * @param  string $meta_value Value to update to.
843
 * @param  string $prev_value Previous value.
844
 *
845
 * @return mixed Meta ID if successful, false if unsuccessful.
846
 */
847
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
848
	$payment = new Give_Payment( $payment_id );
849
850
	return $payment->update_meta( $meta_key, $meta_value, $prev_value );
851
}
852
853
/**
854
 * Get the user_info Key from Payment Meta
855
 *
856
 * @param int $payment_id Payment ID.
857
 *
858
 * @since 1.0
859
 *
860
 * @return array $user_info User Info Meta Values.
861
 */
862
function give_get_payment_meta_user_info( $payment_id ) {
863
	$payment = new Give_Payment( $payment_id );
864
865
	return $payment->user_info;
866
}
867
868
/**
869
 * Get the donations Key from Payment Meta
870
 *
871
 * Retrieves the form_id from a (Previously titled give_get_payment_meta_donations)
872
 *
873
 * @param int $payment_id Payment ID.
874
 *
875
 * @since 1.0
876
 *
877
 * @return int $form_id Form ID.
878
 */
879
function give_get_payment_form_id( $payment_id ) {
880
	$payment = new Give_Payment( $payment_id );
881
882
	return $payment->form_id;
883
}
884
885
/**
886
 * Get the user email associated with a payment
887
 *
888
 * @param int $payment_id Payment ID.
889
 *
890
 * @since 1.0
891
 *
892
 * @return string $email User email.
893
 */
894
function give_get_payment_user_email( $payment_id ) {
895
	$payment = new Give_Payment( $payment_id );
896
897
	return $payment->email;
898
}
899
900
/**
901
 * Is the payment provided associated with a user account
902
 *
903
 * @param int $payment_id The payment ID.
904
 *
905
 * @since 1.3
906
 *
907
 * @return bool $is_guest_payment If the payment is associated with a user (false) or not (true)
908
 */
909
function give_is_guest_payment( $payment_id ) {
910
	$payment_user_id  = give_get_payment_user_id( $payment_id );
911
	$is_guest_payment = ! empty( $payment_user_id ) && $payment_user_id > 0 ? false : true;
912
913
	return (bool) apply_filters( 'give_is_guest_payment', $is_guest_payment, $payment_id );
914
}
915
916
/**
917
 * Get the user ID associated with a payment
918
 *
919
 * @param int $payment_id Payment ID.
920
 *
921
 * @since 1.3
922
 *
923
 * @return int $user_id User ID.
924
 */
925
function give_get_payment_user_id( $payment_id ) {
926
	$payment = new Give_Payment( $payment_id );
927
928
	return $payment->user_id;
929
}
930
931
/**
932
 * Get the donor ID associated with a payment.
933
 *
934
 * @param int $payment_id Payment ID.
935
 *
936
 * @since 1.0
937
 *
938
 * @return int $payment->customer_id Donor ID.
939
 */
940
function give_get_payment_donor_id( $payment_id ) {
941
	$payment = new Give_Payment( $payment_id );
942
943
	return $payment->customer_id;
944
}
945
946
/**
947
 * Get the IP address used to make a donation
948
 *
949
 * @param int $payment_id Payment ID.
950
 *
951
 * @since 1.0
952
 *
953
 * @return string $ip User IP.
954
 */
955
function give_get_payment_user_ip( $payment_id ) {
956
	$payment = new Give_Payment( $payment_id );
957
958
	return $payment->ip;
959
}
960
961
/**
962
 * Get the date a payment was completed
963
 *
964
 * @param int $payment_id Payment ID.
965
 *
966
 * @since 1.0
967
 *
968
 * @return string $date The date the payment was completed.
969
 */
970
function give_get_payment_completed_date( $payment_id = 0 ) {
971
	$payment = new Give_Payment( $payment_id );
972
973
	return $payment->completed_date;
974
}
975
976
/**
977
 * Get the gateway associated with a payment
978
 *
979
 * @param int $payment_id Payment ID.
980
 *
981
 * @since 1.0
982
 *
983
 * @return string $gateway Gateway.
984
 */
985
function give_get_payment_gateway( $payment_id ) {
986
	$payment = new Give_Payment( $payment_id );
987
988
	return $payment->gateway;
989
}
990
991
/**
992
 * Get the currency code a payment was made in
993
 *
994
 * @param int $payment_id Payment ID.
995
 *
996
 * @since 1.0
997
 *
998
 * @return string $currency The currency code.
999
 */
1000
function give_get_payment_currency_code( $payment_id = 0 ) {
1001
	$payment = new Give_Payment( $payment_id );
1002
1003
	return $payment->currency;
1004
}
1005
1006
/**
1007
 * Get the currency name a payment was made in
1008
 *
1009
 * @param int $payment_id Payment ID.
1010
 *
1011
 * @since 1.0
1012
 *
1013
 * @return string $currency The currency name.
1014
 */
1015
function give_get_payment_currency( $payment_id = 0 ) {
1016
	$currency = give_get_payment_currency_code( $payment_id );
1017
1018
	return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
1019
}
1020
1021
/**
1022
 * Get the key for a donation
1023
 *
1024
 * @param int $payment_id Payment ID.
1025
 *
1026
 * @since 1.0
1027
 *
1028
 * @return string $key Donation key.
1029
 */
1030
function give_get_payment_key( $payment_id = 0 ) {
1031
	$payment = new Give_Payment( $payment_id );
1032
1033
	return $payment->key;
1034
}
1035
1036
/**
1037
 * Get the payment order number
1038
 *
1039
 * This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
1040
 *
1041
 * @param int $payment_id Payment ID.
1042
 *
1043
 * @since 1.0
1044
 *
1045
 * @return string $number Payment order number.
1046
 */
1047
function give_get_payment_number( $payment_id = 0 ) {
1048
	$payment = new Give_Payment( $payment_id );
1049
1050
	return $payment->number;
1051
}
1052
1053
1054
/**
1055
 * Get Donation Amount
1056
 *
1057
 * Get the fully formatted or unformatted donation amount which is sent through give_currency_filter()
1058
 * and give_format_amount() to format the amount correctly in case of formatted amount.
1059
 *
1060
 * @param int|Give_Payment $donation    Donation ID or Donation Object.
1061
 * @param bool|array       $format_args Currency Formatting Arguments.
1062
 *
1063
 * @since 1.0
1064
 * @since 1.8.17 Added filter and internally use functions.
1065
 *
1066
 * @return string $amount Fully formatted donation amount.
1067
 */
1068
function give_donation_amount( $donation, $format_args = array() ) {
1069
	/* @var Give_Payment $donation */
1070
	if ( ! ( $donation instanceof Give_Payment ) ) {
1071
		$donation = new Give_Payment( absint( $donation ) );
1072
	}
1073
1074
	$amount           = $donation->total;
1075
	$formatted_amount = $amount;
1076
1077
	if ( is_bool( $format_args ) ) {
1078
		$format_args = array(
1079
			'currency' => (bool) $format_args,
1080
			'amount'   => (bool) $format_args,
1081
		);
1082
	}
1083
1084
	$format_args = wp_parse_args(
1085
		$format_args,
1086
		array(
1087
			'currency' => false,
1088
			'amount'   => false,
1089
1090
			// Define context of donation amount, by default keep $type as blank.
1091
			// Pass as 'stats' to calculate donation report on basis of base amount for the Currency-Switcher Add-on.
1092
			// For Eg. In Currency-Switcher add on when donation has been made through
1093
			// different currency other than base currency, in that case for correct
1094
			//report calculation based on base currency we will need to return donation
1095
			// base amount and not the converted amount .
1096
			'type'     => '',
1097
		)
1098
	);
1099
1100
	if ( $format_args['amount'] || $format_args['currency'] ) {
1101
1102
		if ( $format_args['amount'] ) {
1103
1104
			$formatted_amount = give_format_amount(
1105
				$amount,
1106
				! is_array( $format_args['amount'] ) ?
1107
					array(
1108
						'sanitize' => false,
1109
						'currency' => $donation->currency,
1110
					) :
1111
					$format_args['amount']
1112
			);
1113
		}
1114
1115
		if ( $format_args['currency'] ) {
1116
			$formatted_amount = give_currency_filter(
1117
				$formatted_amount,
1118
				! is_array( $format_args['currency'] ) ?
1119
					array( 'currency_code' => $donation->currency ) :
1120
					$format_args['currency']
1121
			);
1122
		}
1123
	}
1124
1125
	/**
1126
	 * Filter Donation amount.
1127
	 *
1128
	 * @since 1.8.17
1129
	 *
1130
	 * @param string $formatted_amount Formatted/Un-formatted amount.
1131
	 * @param float  $amount           Donation amount.
1132
	 * @param int    $donation_id      Donation ID.
1133
	 * @param string $type             Donation amount type.
1134
	 */
1135
	return apply_filters( 'give_donation_amount', (string) $formatted_amount, $amount, $donation, $format_args );
1136
}
1137
1138
/**
1139
 * Payment Subtotal
1140
 *
1141
 * Retrieves subtotal for payment and then returns a full formatted amount. This
1142
 * function essentially calls give_get_payment_subtotal()
1143
 *
1144
 * @param int $payment_id Payment ID.
1145
 *
1146
 * @since 1.5
1147
 *
1148
 * @see   give_get_payment_subtotal()
1149
 *
1150
 * @return array Fully formatted payment subtotal.
1151
 */
1152
function give_payment_subtotal( $payment_id = 0 ) {
1153
	$subtotal = give_get_payment_subtotal( $payment_id );
1154
1155
	return give_currency_filter( give_format_amount( $subtotal, array( 'sanitize' => false ) ), array( 'currency_code' => give_get_payment_currency_code( $payment_id ) ) );
1156
}
1157
1158
/**
1159
 * Get Payment Subtotal
1160
 *
1161
 * Retrieves subtotal for payment and then returns a non formatted amount.
1162
 *
1163
 * @param int $payment_id Payment ID.
1164
 *
1165
 * @since 1.5
1166
 *
1167
 * @return float $subtotal Subtotal for payment (non formatted).
1168
 */
1169
function give_get_payment_subtotal( $payment_id = 0 ) {
1170
	$payment = new Give_Payment( $payment_id );
1171
1172
	return $payment->subtotal;
1173
}
1174
1175
/**
1176
 * Retrieves the donation ID
1177
 *
1178
 * @param int $payment_id Payment ID.
1179
 *
1180
 * @since  1.0
1181
 *
1182
 * @return string The donation ID.
1183
 */
1184
function give_get_payment_transaction_id( $payment_id = 0 ) {
1185
	$payment = new Give_Payment( $payment_id );
1186
1187
	return $payment->transaction_id;
1188
}
1189
1190
/**
1191
 * Sets a Transaction ID in post meta for the given Payment ID.
1192
 *
1193
 * @param int    $payment_id     Payment ID.
1194
 * @param string $transaction_id The transaction ID from the gateway.
1195
 *
1196
 * @since  1.0
1197
 *
1198
 * @return bool|mixed
1199
 */
1200
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
1201
1202
	if ( empty( $payment_id ) || empty( $transaction_id ) ) {
1203
		return false;
1204
	}
1205
1206
	$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
1207
1208
	return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
1209
}
1210
1211
/**
1212
 * Retrieve the donation ID based on the key
1213
 *
1214
 * @param string  $key  the key to search for.
1215
 *
1216
 * @since 1.0
1217
 * @global object $wpdb Used to query the database using the WordPress Database API.
1218
 *
1219
 * @return int $purchase Donation ID.
1220
 */
1221 View Code Duplication
function give_get_donation_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...
1222
	global $wpdb;
1223
1224
	$meta_table = __give_v20_bc_table_details( 'payment' );
1225
1226
	$purchase = $wpdb->get_var(
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...
1227
		$wpdb->prepare(
1228
			"
1229
				SELECT {$meta_table['column']['id']}
1230
				FROM {$meta_table['name']}
1231
				WHERE meta_key = '_give_payment_purchase_key'
1232
				AND meta_value = %s
1233
				ORDER BY {$meta_table['column']['id']} DESC
1234
				LIMIT 1
1235
				",
1236
			$key
1237
		)
1238
	);
1239
1240
	if ( $purchase != null ) {
1241
		return $purchase;
1242
	}
1243
1244
	return 0;
1245
}
1246
1247
1248
/**
1249
 * Retrieve the donation ID based on the transaction ID
1250
 *
1251
 * @param string  $key  The transaction ID to search for.
1252
 *
1253
 * @since 1.3
1254
 * @global object $wpdb Used to query the database using the WordPress Database API.
1255
 *
1256
 * @return int $purchase Donation ID.
1257
 */
1258 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...
1259
	global $wpdb;
1260
	$meta_table = __give_v20_bc_table_details( 'payment' );
1261
1262
	$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...
1263
1264
	if ( $purchase != null ) {
1265
		return $purchase;
1266
	}
1267
1268
	return 0;
1269
}
1270
1271
/**
1272
 * Retrieve all notes attached to a donation
1273
 *
1274
 * @param int    $payment_id The donation ID to retrieve notes for.
1275
 * @param string $search     Search for notes that contain a search term.
1276
 *
1277
 * @since 1.0
1278
 *
1279
 * @return array $notes Donation Notes
1280
 */
1281
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
1282
1283
	if ( empty( $payment_id ) && empty( $search ) ) {
1284
		return false;
1285
	}
1286
1287
	remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1288
	remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10 );
1289
1290
	$notes = get_comments( array(
1291
		'post_id' => $payment_id,
1292
		'order'   => 'ASC',
1293
		'search'  => $search,
1294
	) );
1295
1296
	add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1297
	add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1298
1299
	return $notes;
1300
}
1301
1302
1303
/**
1304
 * Add a note to a payment
1305
 *
1306
 * @param int    $payment_id The payment ID to store a note for.
1307
 * @param string $note       The note to store.
1308
 *
1309
 * @since 1.0
1310
 *
1311
 * @return int The new note ID
1312
 */
1313
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
1314
	if ( empty( $payment_id ) ) {
1315
		return false;
1316
	}
1317
1318
	/**
1319
	 * Fires before inserting payment note.
1320
	 *
1321
	 * @param int    $payment_id Payment ID.
1322
	 * @param string $note       The note.
1323
	 *
1324
	 * @since 1.0
1325
	 */
1326
	do_action( 'give_pre_insert_payment_note', $payment_id, $note );
1327
1328
	$note_id = wp_insert_comment( wp_filter_comment( array(
1329
		'comment_post_ID'      => $payment_id,
1330
		'comment_content'      => $note,
1331
		'user_id'              => is_admin() ? get_current_user_id() : 0,
1332
		'comment_date'         => current_time( 'mysql' ),
1333
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
1334
		'comment_approved'     => 1,
1335
		'comment_parent'       => 0,
1336
		'comment_author'       => '',
1337
		'comment_author_IP'    => '',
1338
		'comment_author_url'   => '',
1339
		'comment_author_email' => '',
1340
		'comment_type'         => 'give_payment_note',
1341
1342
	) ) );
1343
1344
	/**
1345
	 * Fires after payment note inserted.
1346
	 *
1347
	 * @param int    $note_id    Note ID.
1348
	 * @param int    $payment_id Payment ID.
1349
	 * @param string $note       The note.
1350
	 *
1351
	 * @since 1.0
1352
	 */
1353
	do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
1354
1355
	return $note_id;
1356
}
1357
1358
/**
1359
 * Deletes a payment note
1360
 *
1361
 * @param int $comment_id The comment ID to delete.
1362
 * @param int $payment_id The payment ID the note is connected to.
1363
 *
1364
 * @since 1.0
1365
 *
1366
 * @return bool True on success, false otherwise.
1367
 */
1368
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
1369
	if ( empty( $comment_id ) ) {
1370
		return false;
1371
	}
1372
1373
	/**
1374
	 * Fires before deleting donation note.
1375
	 *
1376
	 * @param int $comment_id Note ID.
1377
	 * @param int $payment_id Payment ID.
1378
	 *
1379
	 * @since 1.0
1380
	 */
1381
	do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
1382
1383
	$ret = wp_delete_comment( $comment_id, true );
1384
1385
	/**
1386
	 * Fires after donation note deleted.
1387
	 *
1388
	 * @param int $comment_id Note ID.
1389
	 * @param int $payment_id Payment ID.
1390
	 *
1391
	 * @since 1.0
1392
	 */
1393
	do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
1394
1395
	return $ret;
1396
}
1397
1398
/**
1399
 * Gets the payment note HTML
1400
 *
1401
 * @param object|int $note       The comment object or ID.
1402
 * @param int        $payment_id The payment ID the note is connected to.
1403
 *
1404
 * @since 1.0
1405
 *
1406
 * @return string
1407
 */
1408
function give_get_payment_note_html( $note, $payment_id = 0 ) {
1409
1410
	if ( is_numeric( $note ) ) {
1411
		$note = get_comment( $note );
1412
	}
1413
1414
	if ( ! empty( $note->user_id ) ) {
1415
		$user = get_userdata( $note->user_id );
1416
		$user = $user->display_name;
1417
	} else {
1418
		$user = __( 'System', 'give' );
1419
	}
1420
1421
	$date_format = give_date_format() . ', ' . get_option( 'time_format' );
1422
1423
	$delete_note_url = wp_nonce_url( add_query_arg( array(
1424
		'give-action' => 'delete_payment_note',
1425
		'note_id'     => $note->comment_ID,
1426
		'payment_id'  => $payment_id,
1427
	) ), 'give_delete_payment_note_' . $note->comment_ID );
1428
1429
	$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
1430
	$note_html .= '<p>';
1431
	$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/>';
1432
	$note_html .= $note->comment_content;
1433
	$note_html .= '&nbsp;&ndash;&nbsp;<a href="' . esc_url( $delete_note_url ) . '" class="give-delete-payment-note" data-note-id="' . absint( $note->comment_ID ) . '" data-payment-id="' . absint( $payment_id ) . '" aria-label="' . __( 'Delete this donation note.', 'give' ) . '">' . __( 'Delete', 'give' ) . '</a>';
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw '__'
Loading history...
1434
	$note_html .= '</p>';
1435
	$note_html .= '</div>';
1436
1437
	return $note_html;
1438
1439
}
1440
1441
/**
1442
 * Exclude notes (comments) on give_payment post type from showing in Recent
1443
 * Comments widgets
1444
 *
1445
 * @param object $query WordPress Comment Query Object.
1446
 *
1447
 * @since 1.0
1448
 *
1449
 * @return void
1450
 */
1451
function give_hide_payment_notes( $query ) {
1452
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
1453
		$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
1454
		if ( ! is_array( $types ) ) {
1455
			$types = array( $types );
1456
		}
1457
		$types[]                           = 'give_payment_note';
1458
		$query->query_vars['type__not_in'] = $types;
1459
	}
1460
}
1461
1462
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
1463
1464
/**
1465
 * Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
1466
 *
1467
 * @param array  $clauses          Comment clauses for comment query.
1468
 * @param object $wp_comment_query WordPress Comment Query Object.
1469
 *
1470
 * @since 1.0
1471
 *
1472
 * @return array $clauses Updated comment clauses.
1473
 */
1474
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...
1475
	if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
1476
		$clauses['where'] .= ' AND comment_type != "give_payment_note"';
1477
	}
1478
1479
	return $clauses;
1480
}
1481
1482
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
1483
1484
1485
/**
1486
 * Exclude notes (comments) on give_payment post type from showing in comment feeds
1487
 *
1488
 * @param string $where
1489
 * @param object $wp_comment_query WordPress Comment Query Object.
1490
 *
1491
 * @since 1.0
1492
 *
1493
 * @return string $where
1494
 */
1495
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...
1496
	global $wpdb;
1497
1498
	$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
1499
1500
	return $where;
1501
}
1502
1503
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
1504
1505
1506
/**
1507
 * Remove Give Comments from the wp_count_comments function
1508
 *
1509
 * @param array $stats   (empty from core filter).
1510
 * @param int   $post_id Post ID.
1511
 *
1512
 * @access public
1513
 * @since  1.0
1514
 *
1515
 * @return array|object Array of comment counts.
1516
 */
1517
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
1518
	global $wpdb, $pagenow;
1519
1520
	if ( 'index.php' != $pagenow ) {
1521
		return $stats;
1522
	}
1523
1524
	$post_id = (int) $post_id;
1525
1526
	if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
1527
		return $stats;
1528
	}
1529
1530
	$stats = Give_Cache::get_group( "comments-{$post_id}", 'counts' );
1531
1532
	if ( ! is_null( $stats ) ) {
1533
		return $stats;
1534
	}
1535
1536
	$where = 'WHERE comment_type != "give_payment_note"';
1537
1538
	if ( $post_id > 0 ) {
1539
		$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
1540
	}
1541
1542
	$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...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
1543
1544
	$total    = 0;
1545
	$approved = array(
1546
		'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
1547
		'1'            => 'approved',
1548
		'spam'         => 'spam',
1549
		'trash'        => 'trash',
1550
		'post-trashed' => 'post-trashed',
1551
	);
1552
	foreach ( (array) $count as $row ) {
1553
		// Don't count post-trashed toward totals.
1554
		if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
1555
			$total += $row['num_comments'];
1556
		}
1557
		if ( isset( $approved[ $row['comment_approved'] ] ) ) {
1558
			$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
1559
		}
1560
	}
1561
1562
	$stats['total_comments'] = $total;
1563
	foreach ( $approved as $key ) {
1564
		if ( empty( $stats[ $key ] ) ) {
1565
			$stats[ $key ] = 0;
1566
		}
1567
	}
1568
1569
	$stats = (object) $stats;
1570
	Give_Cache::set_group( "comments-{$post_id}", $stats, 'counts' );
1571
1572
	return $stats;
1573
}
1574
1575
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
1576
1577
1578
/**
1579
 * Filter where older than one week
1580
 *
1581
 * @param string $where Where clause.
1582
 *
1583
 * @access public
1584
 * @since  1.0
1585
 *
1586
 * @return string $where Modified where clause.
1587
 */
1588
function give_filter_where_older_than_week( $where = '' ) {
1589
	// Payments older than one week.
1590
	$start = date( 'Y-m-d', strtotime( '-7 days' ) );
1591
	$where .= " AND post_date <= '{$start}'";
1592
1593
	return $where;
1594
}
1595
1596
1597
/**
1598
 * Get Payment Form ID.
1599
 *
1600
 * Retrieves the form title and appends the level name if present.
1601
 *
1602
 * @param int|Give_Payment $donation Donation Data Object.
1603
 * @param array            $args     a. only_level = If set to true will only return the level name if multi-level enabled.
1604
 *                                   b. separator  = The separator between the Form Title and the Donation Level.
1605
 *
1606
 * @since 1.5
1607
 *
1608
 * @return string $form_title Returns the full title if $only_level is false, otherwise returns the levels title.
1609
 */
1610
function give_get_donation_form_title( $donation, $args = array() ) {
1611
1612
	if ( ! $donation instanceof Give_Payment ) {
1613
		$donation = new Give_Payment( $donation );
1614
	}
1615
1616
	if( ! $donation->ID ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1617
		return '';
1618
	}
1619
1620
	$defaults = array(
1621
		'only_level' => false,
1622
		'separator'  => '',
1623
	);
1624
1625
	$args = wp_parse_args( $args, $defaults );
1626
1627
	$form_id     = $donation->form_id;
1628
	$price_id    = $donation->price_id;
1629
	$form_title  = $donation->form_title;
1630
	$only_level  = $args['only_level'];
1631
	$separator   = $args['separator'];
1632
	$level_label = '';
1633
1634
	$cache_key = Give_Cache::get_key(
1635
		'give_forms',
1636
		array(
1637
			$form_id,
1638
			$price_id,
1639
			$form_title,
1640
			$only_level,
1641
			$separator
1642
		)
1643
		, false
1644
	);
1645
1646
	$form_title_html = Give_Cache::get_db_query( $cache_key );
1647
1648
	if ( is_null( $form_title_html ) ) {
1649
		if ( true === $only_level ) {
1650
			$form_title = '';
1651
		}
1652
1653
		$form_title_html = $form_title;
1654
1655
		if ( 'custom' === $price_id ) {
1656
1657
			$custom_amount_text = give_get_meta( $form_id, '_give_custom_amount_text', true );
1658
			$level_label        = ! empty( $custom_amount_text ) ? $custom_amount_text : __( 'Custom Amount', 'give' );
1659
1660
			// Show custom amount level only in backend otherwise hide it.
1661
			if( 'set' === give_get_meta( $form_id, '_give_price_option', true ) && ! is_admin()  ) {
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...
1662
				$level_label = '';
1663
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1664
1665
		} elseif ( give_has_variable_prices( $form_id ) ) {
1666
			$level_label = give_get_price_option_name( $form_id, $price_id, $donation->ID, false );
1667
		}
1668
1669
		// Only add separator if there is a form title.
1670
		if (
1671
			! empty( $form_title_html ) &&
1672
			! empty( $level_label )
1673
		) {
1674
			$form_title_html .= " {$separator} ";
1675
		}
1676
1677
		$form_title_html .= "<span class=\"donation-level-text-wrap\">{$level_label}</span>";
1678
		Give_Cache::set_db_query( $cache_key, $form_title_html );
1679
	}
1680
1681
	/**
1682
	 * Filter form title with level html
1683
	 *
1684
	 * @since 1.0
1685
	 */
1686
	return apply_filters( 'give_get_donation_form_title', $form_title_html, $donation->payment_meta, $donation );
1687
}
1688
1689
/**
1690
 * Get Price ID
1691
 *
1692
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
1693
 *
1694
 * @param int    $form_id Form ID.
1695
 * @param string $price   Donation Amount.
1696
 *
1697
 * @return string $price_id
1698
 */
1699
function give_get_price_id( $form_id, $price ) {
1700
	$price_id = null;
1701
1702
	if ( give_has_variable_prices( $form_id ) ) {
1703
1704
		$levels = give_get_meta( $form_id, '_give_donation_levels', true );
1705
1706
		foreach ( $levels as $level ) {
1707
1708
			$level_amount = give_maybe_sanitize_amount( $level['_give_amount'] );
1709
1710
			// Check that this indeed the recurring price.
1711
			if ( $level_amount == $price ) {
1712
1713
				$price_id = $level['_give_id']['level_id'];
1714
				break;
1715
1716
			}
1717
		}
1718
1719
		if ( is_null( $price_id ) && give_is_custom_price_mode( $form_id ) ) {
1720
			$price_id = 'custom';
1721
		}
1722
	}
1723
1724
	// Price ID must be numeric or string.
1725
	$price_id = ! is_numeric( $price_id ) && ! is_string( $price_id ) ? 0 : $price_id;
1726
1727
	/**
1728
	 * Filter the price id
1729
	 *
1730
	 * @since 2.0
1731
	 *
1732
	 * @param string $price_id
1733
	 * @param int    $form_id
1734
	 */
1735
	return apply_filters( 'give_get_price_id', $price_id, $form_id );
1736
}
1737
1738
/**
1739
 * Get/Print give form dropdown html
1740
 *
1741
 * This function is wrapper to public method forms_dropdown of Give_HTML_Elements class to get/print form dropdown html.
1742
 * Give_HTML_Elements is defined in includes/class-give-html-elements.php.
1743
 *
1744
 * @param array $args Arguments for form dropdown.
1745
 * @param bool  $echo This parameter decides if print form dropdown html output or not.
1746
 *
1747
 * @since 1.6
1748
 *
1749
 * @return string
1750
 */
1751
function give_get_form_dropdown( $args = array(), $echo = false ) {
1752
	$form_dropdown_html = Give()->html->forms_dropdown( $args );
1753
1754
	if ( ! $echo ) {
1755
		return $form_dropdown_html;
1756
	}
1757
1758
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1759
}
1760
1761
/**
1762
 * Get/Print give form variable price dropdown html
1763
 *
1764
 * @param array $args Arguments for form dropdown.
1765
 * @param bool  $echo This parameter decide if print form dropdown html output or not.
1766
 *
1767
 * @since 1.6
1768
 *
1769
 * @return string|bool
1770
 */
1771
function give_get_form_variable_price_dropdown( $args = array(), $echo = false ) {
1772
1773
	// Check for give form id.
1774
	if ( empty( $args['id'] ) ) {
1775
		return false;
1776
	}
1777
1778
	$form = new Give_Donate_Form( $args['id'] );
1779
1780
	// Check if form has variable prices or not.
1781
	if ( ! $form->ID || ! $form->has_variable_prices() ) {
1782
		return false;
1783
	}
1784
1785
	$variable_prices        = $form->get_prices();
1786
	$variable_price_options = array();
1787
1788
	// Check if multi donation form support custom donation or not.
1789
	if ( $form->is_custom_price_mode() ) {
1790
		$variable_price_options['custom'] = _x( 'Custom', 'custom donation dropdown item', 'give' );
1791
	}
1792
1793
	// Get variable price and ID from variable price array.
1794
	foreach ( $variable_prices as $variable_price ) {
1795
		$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 ) ) );
1796
	}
1797
1798
	// Update options.
1799
	$args = array_merge( $args, array(
1800
		'options' => $variable_price_options,
1801
	) );
1802
1803
	// Generate select html.
1804
	$form_dropdown_html = Give()->html->select( $args );
1805
1806
	if ( ! $echo ) {
1807
		return $form_dropdown_html;
1808
	}
1809
1810
	echo $form_dropdown_html;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$form_dropdown_html'
Loading history...
1811
}
1812
1813
/**
1814
 * Get the price_id from the payment meta.
1815
 *
1816
 * Some gateways use `give_price_id` and others were using just `price_id`;
1817
 * This checks for the difference and falls back to retrieving it from the form as a last resort.
1818
 *
1819
 * @param array $payment_meta Payment Meta.
1820
 *
1821
 * @since 1.8.6
1822
 *
1823
 * @return string
1824
 */
1825
function give_get_payment_meta_price_id( $payment_meta ) {
1826
1827
	if ( isset( $payment_meta['give_price_id'] ) ) {
1828
		$price_id = $payment_meta['give_price_id'];
1829
	} elseif ( isset( $payment_meta['price_id'] ) ) {
1830
		$price_id = $payment_meta['price_id'];
1831
	} else {
1832
		$price_id = give_get_price_id( $payment_meta['give_form_id'], $payment_meta['price'] );
1833
	}
1834
1835
	/**
1836
	 * Filter the price id
1837
	 *
1838
	 * @since 1.8.6
1839
	 *
1840
	 * @param string $price_id
1841
	 * @param array  $payment_meta
1842
	 */
1843
	return apply_filters( 'give_get_payment_meta_price_id', $price_id, $payment_meta );
1844
1845
}
1846