Completed
Push — master ( 45b05a...b92b5a )
by Devin
53s
created

functions.php ➔ give_get_price_option_name()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 5
eloc 9
nc 6
nop 3
dl 0
loc 20
ccs 0
cts 2
cp 0
crap 30
rs 8.8571
c 1
b 1
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 22 and the first side effect is on line 14.

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

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

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

Loading history...
2
/**
3
 * Give Form Functions
4
 *
5
 * @package     WordImpress
6
 * @subpackage  Includes/Forms
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
9
 * @since       1.1
10
 */
11
12
// Exit if accessed directly
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Filter: Do not show the Give shortcut button on Give Forms or Campaign posts
19
 *
20
 * @return bool
21
 */
22
function give_shortcode_button_condition() {
23
24
	global $typenow;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
25
26
	if ( $typenow != 'give_forms' && $typenow != 'give_campaigns' ) {
27
		return true;
28
	}
29
30
	return false;
31
}
32
33
add_filter( 'give_shortcode_button_condition', 'give_shortcode_button_condition' );
34
35
36
/**
37
 * Get the form ID from the form $args
38
 *
39
 * @param $args
40
 *
41
 * @return int|false
42
 */
43
function get_form_id_from_args( $args ) {
44
45
	if ( isset( $args['form_id'] ) && $args['form_id'] != 0 ) {
46
47
		return intval( $args['form_id'] );
48
	}
49
50
	return false;
51
}
52
53
/**
54
 * Checks whether floating labels is enabled for the form ID in $args
55
 *
56
 * @since 1.1
57
 *
58
 * @param array $args
59
 *
60
 * @return bool
61
 */
62
function give_is_float_labels_enabled( $args ) {
63
64 1
	$float_labels = '';
65
66 1
	if ( ! empty( $args['float_labels'] ) ) {
67
		$float_labels = $args['float_labels'];
68
	}
69
70 1
	if ( empty( $float_labels ) ) {
71 1
		$float_labels = get_post_meta( $args['form_id'], '_give_form_floating_labels', true );
72 1
	}
73
74 1
	if ( empty( $float_labels ) ) {
75 1
		$float_labels = give_get_option( 'enable_floatlabels' ) ? 'enabled' : 'disabled';
76 1
	}
77
78 1
	return ( $float_labels == 'enabled' ) ? true : false;
79
}
80
81
/**
82
 * Determines if a user can checkout or not
83
 *
84
 * @description: Allows themes and plugins to set donation checkout conditions
85
 * @since 1.0
86
 * @global $give_options Array of all the Give Options
87
 * @return bool Can user checkout?
88
 */
89
function give_can_checkout() {
90
91 1
	$can_checkout = true;
92
93 1
	return (bool) apply_filters( 'give_can_checkout', $can_checkout );
94
}
95
96
/**
97
 * Retrieve the Success page URI
98
 *
99
 * @access      public
100
 * @since       1.0
101
 * @return      string
102
 */
103
function give_get_success_page_uri() {
104
	global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
105
106
	$success_page = isset( $give_options['success_page'] ) ? get_permalink( absint( $give_options['success_page'] ) ) : get_bloginfo( 'url' );
107
108
	return apply_filters( 'give_get_success_page_uri', $success_page );
109
}
110
111
/**
112
 * Determines if we're currently on the Success page.
113
 *
114
 * @since 1.0
115
 * @return bool True if on the Success page, false otherwise.
116
 */
117
function give_is_success_page() {
118
	global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
119
	$is_success_page = isset( $give_options['success_page'] ) ? is_page( $give_options['success_page'] ) : false;
120
121
	return apply_filters( 'give_is_success_page', $is_success_page );
122
}
123
124
/**
125
 * Send To Success Page
126
 *
127
 * Sends the user to the success page.
128
 *
129
 * @param string $query_string
130
 *
131
 * @access      public
132
 * @since       1.0
133
 * @return      void
134
 */
135
function give_send_to_success_page( $query_string = null ) {
136
137
	$redirect = give_get_success_page_uri();
138
139
	if ( $query_string ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query_string of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
		$redirect .= $query_string;
141
	}
142
143
	$gateway = isset( $_REQUEST['give-gateway'] ) ? $_REQUEST['give-gateway'] : '';
144
145
	wp_redirect( apply_filters( 'give_success_page_redirect', $redirect, $gateway, $query_string ) );
146
	give_die();
147
}
148
149
150
/**
151
 * Send back to checkout.
152
 *
153
 * Used to redirect a user back to the purchase
154
 * page if there are errors present.
155
 *
156
 * @param array $args
157
 *
158
 * @access public
159
 * @since  1.0
160
 * @return Void
161
 */
162
function give_send_back_to_checkout( $args = array() ) {
163
164
	$redirect = ( isset( $_POST['give-current-url'] ) ) ? $_POST['give-current-url'] : '';
165
	$form_id  = isset( $_POST['give-form-id'] ) ? $_POST['give-form-id'] : 0;
166
167
	$defaults = array(
168
		'form-id' => (int) $form_id
169
	);
170
171
	// Check for backward compatibility
172
	if ( is_string( $args ) ) {
173
		$args = str_replace( '?', '', $args );
174
	}
175
176
	$args = wp_parse_args( $args, $defaults );
177
178
	$redirect = add_query_arg( $args, $redirect ) . '#give-form-' . $form_id . '-wrap';
179
180
	wp_redirect( apply_filters( 'give_send_back_to_checkout', $redirect, $args ) );
181
	give_die();
182
}
183
184
/**
185
 * Get Success Page URL
186
 *
187
 * @description Gets the success page URL.
188
 *
189
 * @param string $query_string
190
 *
191
 * @access      public
192
 * @since       1.0
193
 * @return      string
194
 */
195
function give_get_success_page_url( $query_string = null ) {
196
197
	$success_page = give_get_option( 'success_page', 0 );
198
	$success_page = get_permalink( $success_page );
199
200
	if ( $query_string ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query_string of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
201
		$success_page .= $query_string;
202
	}
203
204
	return apply_filters( 'give_success_page_url', $success_page );
205
206
}
207
208
/**
209
 * Get the URL of the Transaction Failed page
210
 *
211
 * @since 1.0
212
 * @global     $give_options Array of all the Give Options
213
 *
214
 * @param bool $extras Extras to append to the URL
215
 *
216
 * @return mixed|void Full URL to the Transaction Failed page, if present, home page if it doesn't exist
217
 */
218
function give_get_failed_transaction_uri( $extras = false ) {
219
	global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
220
221
	$uri = ! empty( $give_options['failure_page'] ) ? trailingslashit( get_permalink( $give_options['failure_page'] ) ) : home_url();
222
	if ( $extras ) {
223
		$uri .= $extras;
224
	}
225
226
	return apply_filters( 'give_get_failed_transaction_uri', $uri );
227
}
228
229
/**
230
 * Determines if we're currently on the Failed Transaction page.
231
 *
232
 * @since 1.0
233
 * @return bool True if on the Failed Transaction page, false otherwise.
234
 */
235
function give_is_failed_transaction_page() {
236
	global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
237
	$ret = isset( $give_options['failure_page'] ) ? is_page( $give_options['failure_page'] ) : false;
238
239
	return apply_filters( 'give_is_failure_page', $ret );
240
}
241
242
/**
243
 * Mark payments as Failed when returning to the Failed Transaction page
244
 *
245
 * @access      public
246
 * @since       1.0
247
 * @return      void
248
 */
249
function give_listen_for_failed_payments() {
250
251
	$failed_page = give_get_option( 'failure_page', 0 );
252
253
	if ( ! empty( $failed_page ) && is_page( $failed_page ) && ! empty( $_GET['payment-id'] ) ) {
254
255
		$payment_id = absint( $_GET['payment-id'] );
256
		give_update_payment_status( $payment_id, 'failed' );
257
258
	}
259
260
}
261
262
add_action( 'template_redirect', 'give_listen_for_failed_payments' );
263
264
265
/**
266
 * Check if a field is required
267
 *
268
 * @param string $field
269
 * @param int $form_id
270
 *
271
 * @access      public
272
 * @since       1.0
273
 * @return      bool
274
 */
275
function give_field_is_required( $field = '', $form_id ) {
276
277
	$required_fields = give_purchase_form_required_fields( $form_id );
278
279
	return array_key_exists( $field, $required_fields );
280
}
281
282
/**
283
 * Record Sale In Log
284
 *
285
 * Stores log information for a form sale.
286
 *
287
 * @since 1.0
288
 * @global            $give_logs
289
 *
290
 * @param int $give_form_id Give Form ID
291
 * @param int $payment_id Payment ID
292
 * @param bool|int $price_id Price ID, if any
293
 * @param string|null $sale_date The date of the sale
294
 *
295
 * @return void
296
 */
297
function give_record_sale_in_log( $give_form_id = 0, $payment_id, $price_id = false, $sale_date = null ) {
298
	global $give_logs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
299
300
	$log_data = array(
301
		'post_parent'   => $give_form_id,
302
		'log_type'      => 'sale',
303
		'post_date'     => isset( $sale_date ) ? $sale_date : null,
304
		'post_date_gmt' => isset( $sale_date ) ? $sale_date : null
305
	);
306
307
	$log_meta = array(
308
		'payment_id' => $payment_id,
309
		'price_id'   => (int) $price_id
310
	);
311
312
	$give_logs->insert_log( $log_data, $log_meta );
313
}
314
315
316
/**
317
 * Increases the donation total count of a donation form.
318
 *
319
 * @since 1.0
320
 *
321
 * @param int $form_id Give Form ID
322
 * @param int $quantity Quantity to increase purchase count by
323
 *
324
 * @return bool|int
325
 */
326
function give_increase_purchase_count( $form_id = 0, $quantity = 1 ) {
327
	$quantity = (int) $quantity;
328
	$form     = new Give_Donate_Form( $form_id );
329
330
	return $form->increase_sales( $quantity );
331
}
332
333
/**
334
 * Decreases the sale count of a form. Primarily for when a donation is refunded.
335
 *
336
 * @since 1.0
337
 *
338
 * @param int $form_id Give Form ID
339
 * @param int $quantity Quantity to increase purchase count by
340
 *
341
 * @return bool|int
342
 */
343
function give_decrease_purchase_count( $form_id = 0, $quantity = 1 ) {
344
	$quantity = (int) $quantity;
345
	$form     = new Give_Donate_Form( $form_id );
346
347
	return $form->decrease_sales( $quantity );
348
}
349
350
/**
351
 * Increases the total earnings of a form.
352
 *
353
 * @since 1.0
354
 *
355
 * @param int $give_form_id Give Form ID
356
 * @param int $amount Earnings
357
 *
358
 * @return bool|int
359
 */
360
function give_increase_earnings( $give_form_id = 0, $amount ) {
361
	$form = new Give_Donate_Form( $give_form_id );
362
363
	return $form->increase_earnings( $amount );
364
}
365
366
/**
367
 * Decreases the total earnings of a form. Primarily for when a purchase is refunded.
368
 *
369
 * @since 1.0
370
 *
371
 * @param int $form_id Give Form ID
372
 * @param int $amount Earnings
373
 *
374
 * @return bool|int
375
 */
376
function give_decrease_earnings( $form_id = 0, $amount ) {
377
	$form = new Give_Donate_Form( $form_id );
378
379
	return $form->decrease_earnings( $amount );
380
}
381
382
383
/**
384
 * Returns the total earnings for a form.
385
 *
386
 * @since 1.0
387
 *
388
 * @param int $form_id Give Form ID
389
 *
390
 * @return int $earnings Earnings for a certain form
391
 */
392
function give_get_form_earnings_stats( $form_id = 0 ) {
393
	$give_form = new Give_Donate_Form( $form_id );
394
395
	return $give_form->earnings;
0 ignored issues
show
Documentation introduced by
The property $earnings is declared private in Give_Donate_Form. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
396
}
397
398
399
/**
400
 * Return the sales number for a form.
401
 *
402
 * @since 1.0
403
 *
404
 * @param int $give_form_id Give Form ID
405
 *
406
 * @return int $sales Amount of sales for a certain form
407
 */
408
function give_get_form_sales_stats( $give_form_id = 0 ) {
409
	$give_form = new Give_Donate_Form( $give_form_id );
410
411
	return $give_form->sales;
0 ignored issues
show
Documentation introduced by
The property $sales is declared private in Give_Donate_Form. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
412
}
413
414
415
/**
416
 * Retrieves the average monthly sales for a specific donation form
417
 *
418
 * @since 1.0
419
 *
420
 * @param int $form_id Form ID
421
 *
422
 * @return float $sales Average monthly sales
423
 */
424
function give_get_average_monthly_form_sales( $form_id = 0 ) {
425
	$sales        = give_get_form_sales_stats( $form_id );
426
	$release_date = get_post_field( 'post_date', $form_id );
427
428
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
429
430
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
431
432
	if ( $months > 0 ) {
433
		$sales = ( $sales / $months );
434
	}
435
436
	return $sales;
437
}
438
439
440
/**
441
 * Retrieves the average monthly earnings for a specific form
442
 *
443
 * @since 1.0
444
 *
445
 * @param int $form_id Form ID
446
 *
447
 * @return float $earnings Average monthly earnings
448
 */
449
function give_get_average_monthly_form_earnings( $form_id = 0 ) {
450
	$earnings     = give_get_form_earnings_stats( $form_id );
451
	$release_date = get_post_field( 'post_date', $form_id );
452
453
	$diff = abs( current_time( 'timestamp' ) - strtotime( $release_date ) );
454
455
	$months = floor( $diff / ( 30 * 60 * 60 * 24 ) ); // Number of months since publication
456
457
	if ( $months > 0 ) {
458
		$earnings = ( $earnings / $months );
459
	}
460
461
	return $earnings < 0 ? 0 : $earnings;
462
}
463
464
465
/**
466
 * Get Price Option Name (Text)
467
 *
468
 * @description Retrieves the name of a variable price option
469
 *
470
 * @since       1.0
471
 *
472
 * @param int $form_id ID of the download
473
 * @param int $price_id ID of the price option
474
 * @param int $payment_id optional payment ID for use in filters
475
 *
476
 * @return string $price_name Name of the price option
477
 */
478
function give_get_price_option_name( $form_id = 0, $price_id = 0, $payment_id = 0 ) {
479
480
	$prices     = give_get_variable_prices( $form_id );
481
	$price_name = '';
482
483
	foreach ( $prices as $price ) {
484
485
		if ( intval( $price['_give_id']['level_id'] ) == intval( $price_id ) ) {
486
487
			$price_text     = isset( $price['_give_text'] ) ? $price['_give_text'] : '';
488
			$price_fallback = give_currency_filter( give_format_amount( $price['_give_amount'] ) );
489
			$price_name     = ! empty( $price_text ) ? $price_text : $price_fallback;
490
491
		}
492
493
	}
494
495
496
	return apply_filters( 'give_get_price_option_name', $price_name, $form_id, $payment_id, $price_id );
497
}
498
499
500
/**
501
 * Retrieves a price from from low to high of a variable priced form
502
 *
503
 * @since 1.0
504
 *
505
 * @param int $form_id ID of the form
506
 *
507
 * @return string $range A fully formatted price range
508
 */
509
function give_price_range( $form_id = 0 ) {
510
	$low   = give_get_lowest_price_option( $form_id );
511
	$high  = give_get_highest_price_option( $form_id );
512
	$range = '<span class="give_price_range_low">' . give_currency_filter( give_format_amount( $low ) ) . '</span>';
513
	$range .= '<span class="give_price_range_sep">&nbsp;&ndash;&nbsp;</span>';
514
	$range .= '<span class="give_price_range_high">' . give_currency_filter( give_format_amount( $high ) ) . '</span>';
515
516
	return apply_filters( 'give_price_range', $range, $form_id, $low, $high );
517
}
518
519
520
/**
521
 * Get Lowest Price ID
522
 *
523
 * @description: Retrieves the ID for the cheapest price option of a variable donation form
524
 *
525
 * @since 1.5
526
 *
527
 * @param int $form_id ID of the donation
528
 *
529
 * @return int ID of the lowest price
530
 */
531
function give_get_lowest_price_id( $form_id = 0 ) {
532
533 10
	if ( empty( $form_id ) ) {
534
		$form_id = get_the_ID();
535 10
	}
536
537
	if ( ! give_has_variable_prices( $form_id ) ) {
538
		return give_get_form_price( $form_id );
539
	}
540
541
	$prices = give_get_variable_prices( $form_id );
542
543
	$low    = 0.00;
544
	$min_id = 1;
545
546
	if ( ! empty( $prices ) ) {
547
548
		foreach ( $prices as $key => $price ) {
549 10
550
			if ( empty( $price['_give_amount'] ) ) {
551 10
				continue;
552
			}
553
554
			if ( ! isset( $min ) ) {
555
				$min = $price['_give_amount'];
556
			} else {
557
				$min = min( $min, $price['_give_amount'] );
558
			}
559
560
			if ( $price['_give_amount'] == $min ) {
561
				$min_id = $price['_give_id']['level_id'];
562
			}
563
		}
564
	}
565 10
566 10
	return (int) $min_id;
567
}
568 10
569
/**
570 10
 * Retrieves cheapest price option of a variable priced form
571
 *
572 10
 * @since 1.0
573
 *
574
 * @param int $form_id ID of the form
575
 *
576 10
 * @return float Amount of the lowest price
577
 */
578
function give_get_lowest_price_option( $form_id = 0 ) {
579
	if ( empty( $form_id ) ) {
580
		$form_id = get_the_ID();
581
	}
582
583
	if ( ! give_has_variable_prices( $form_id ) ) {
584
		return give_get_form_price( $form_id );
585
	}
586
587
	$prices = give_get_variable_prices( $form_id );
588
589
	$low = 0.00;
590 10
591 10
	if ( ! empty( $prices ) ) {
592
593 10
		foreach ( $prices as $key => $price ) {
594
595 10
			if ( empty( $price['_give_amount'] ) ) {
596
				continue;
597 10
			}
598
599
			if ( ! isset( $min ) ) {
600
				$min = $price['_give_amount'];
601 10
			} else {
602
				$min = min( $min, give_sanitize_amount( $price['_give_amount'] ) );
603
			}
604
605
			if ( $price['_give_amount'] == $min ) {
606
				$min_id = $key;
607
			}
608
		}
609
610
		$low = $prices[ $min_id ]['_give_amount'];
0 ignored issues
show
Bug introduced by
The variable $min_id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
611
612
	}
613
614
	return give_sanitize_amount( $low );
615
}
616
617
/**
618
 * Retrieves most expensive price option of a variable priced form
619
 *
620 10
 * @since 1.0
621 10
 *
622
 * @param int $form_id ID of the form
623 10
 *
624
 * @return float Amount of the highest price
625 10
 */
626 10
function give_get_highest_price_option( $form_id = 0 ) {
627 10
628
	if ( empty( $form_id ) ) {
629 10
		$form_id = get_the_ID();
630
	}
631
632 10
	if ( ! give_has_variable_prices( $form_id ) ) {
633
		return give_get_form_price( $form_id );
634
	}
635
636
	$prices = give_get_variable_prices( $form_id );
637
638
	$high = 0.00;
639
640
	if ( ! empty( $prices ) ) {
641
642
		$max = 0;
643
644
		foreach ( $prices as $key => $price ) {
645
			if ( empty( $price['_give_amount'] ) ) {
646
				continue;
647
			}
648
			$give_amount = give_sanitize_amount( $price['_give_amount'] );
649
650
			$max = max( $max, $give_amount );
651
652
			if ( $give_amount == $max ) {
653
				$max_id = $key;
654
			}
655
		}
656
657
		$high = $prices[ $max_id ]['_give_amount'];
0 ignored issues
show
Bug introduced by
The variable $max_id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
658
	}
659
660
	return give_sanitize_amount( $high );
661
}
662
663
/**
664
 * Returns the price of a form, but only for non-variable priced forms.
665
 *
666
 * @since 1.0
667
 *
668
 * @param int $form_id ID number of the form to retrieve a price for
669
 *
670
 * @return mixed string|int Price of the form
671
 */
672
function give_get_form_price( $form_id = 0 ) {
673
674
	if ( empty( $form_id ) ) {
675
		return false;
676
	}
677
678
	$form = new Give_Donate_Form( $form_id );
679
680
	return $form->__get( 'price' );
681
}
682
683
/**
684
 * Returns the minimum price amount of a form, only enforced for the custom amount input.
685
 *
686
 * @since 1.3.6
687
 *
688
 * @param int $form_id ID number of the form to retrieve the minimum price for
689
 *
690
 * @return mixed string|int Minimum price of the form
691
 */
692
function give_get_form_minimum_price( $form_id = 0 ) {
693
694
	if ( empty( $form_id ) ) {
695
		return false;
696
	}
697
698
	$form = new Give_Donate_Form( $form_id );
699
700
	return $form->__get( 'minimum_price' );
701
702
}
703
704
/**
705
 * Displays a formatted price for a donation form
706
 *
707
 * @since 1.0
708
 *
709
 * @param int $form_id ID of the form price to show
710
 * @param bool $echo Whether to echo or return the results
711
 * @param bool|int $price_id Optional price id for variable pricing
712
 *
713
 * @return int $formatted_price
714
 */
715
function give_price( $form_id = 0, $echo = true, $price_id = false ) {
716
717
	if ( empty( $form_id ) ) {
718
		$form_id = get_the_ID();
719
	}
720
721
	if ( give_has_variable_prices( $form_id ) ) {
722
723
		$prices = give_get_variable_prices( $form_id );
724
725
		if ( false !== $price_id ) {
726
727
			//loop through multi-prices to see which is default
728
			foreach ( $prices as $price ) {
729
				//this is the default price
730
				if ( isset( $price['_give_default'] ) && $price['_give_default'] === 'default' ) {
731
					$price = (float) $price['_give_amount'];
732
				};
733
			}
734
735
		} else {
736
737
			$price = give_get_lowest_price_option( $form_id );
738
		}
739
740
		$price = give_sanitize_amount( $price );
0 ignored issues
show
Bug introduced by
The variable $price does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
741
742
	} else {
743
744
		$price = give_get_form_price( $form_id );
745
746
	}
747
748
	$price           = apply_filters( 'give_form_price', give_sanitize_amount( $price ), $form_id );
749
	$formatted_price = '<span class="give_price" id="give_price_' . $form_id . '">' . $price . '</span>';
750
	$formatted_price = apply_filters( 'give_form_price_after_html', $formatted_price, $form_id, $price );
751
752
	if ( $echo ) {
753
		echo $formatted_price;
754
	} else {
755
		return $formatted_price;
756
	}
757
}
758
759
add_filter( 'give_form_price', 'give_format_amount', 10 );
760
add_filter( 'give_form_price', 'give_currency_filter', 20 );
761 10
762
763
/**
764
 * Retrieves the amount of a variable price option
765 10
 *
766
 * @since 1.0
767 10
 *
768
 * @param int $form_id ID of the form
769
 * @param int $price_id ID of the price option
770
 * @param     int @payment_id ID of the payment
771
 *
772
 * @return float $amount Amount of the price option
773
 */
774
function give_get_price_option_amount( $form_id = 0, $price_id = 0 ) {
775
	$prices = give_get_variable_prices( $form_id );
776
777
	$amount = 0.00;
778
779
	foreach ( $prices as $price ) {
780
		if ( isset( $price['_give_id']['level_id'] ) && $price['_give_id']['level_id'] === $price_id ) {
781 1
			$amount = isset( $price['_give_amount'] ) ? $price['_give_amount'] : 0.00;
782
		};
783
	}
784
785 1
	return apply_filters( 'give_get_price_option_amount', give_sanitize_amount( $amount ), $form_id, $price_id );
786
}
787 1
788
/**
789
 * Returns the goal of a form
790
 *
791
 * @since 1.0
792
 *
793
 * @param int $form_id ID number of the form to retrieve a goal for
794
 *
795
 * @return mixed string|int Goal of the form
796
 */
797
function give_get_form_goal( $form_id = 0 ) {
798
799
	if ( empty( $form_id ) ) {
800
		return false;
801
	}
802
803
	$form = new Give_Donate_Form( $form_id );
804
805
	return $form->goal;
0 ignored issues
show
Documentation introduced by
The property $goal is declared private in Give_Donate_Form. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
806
807
}
808
809
/**
810
 * Displays a formatted goal for a donation form
811
 *
812
 * @since 1.0
813
 *
814
 * @param int $form_id ID of the form price to show
815
 * @param bool $echo Whether to echo or return the results
816
 *
817
 * @return string $formatted_goal
818
 */
819
function give_goal( $form_id = 0, $echo = true ) {
820
821
	if ( empty( $form_id ) ) {
822
		$form_id = get_the_ID();
823
	}
824
825
	$goal = give_get_form_goal( $form_id );
826
827
	$goal           = apply_filters( 'give_form_goal', give_sanitize_amount( $goal ), $form_id );
828
	$formatted_goal = '<span class="give_price" id="give_price_' . $form_id . '">' . $goal . '</span>';
829
	$formatted_goal = apply_filters( 'give_form_price_after_html', $formatted_goal, $form_id, $goal );
830
831
	if ( $echo ) {
832
		echo $formatted_goal;
833
	} else {
834
		return $formatted_goal;
835
	}
836
}
837
838
add_filter( 'give_form_goal', 'give_format_amount', 10 );
839
add_filter( 'give_form_goal', 'give_currency_filter', 20 );
840
841
842
/**
843
 * Checks if users can only donate when logged in
844
 *
845
 * @since 1.0
846
 * @global $give_options
847
 * @return bool $ret Whether or not the logged_in_only setting is set
848
 */
849
function give_logged_in_only( $form_id ) {
850
851
	$form_option = get_post_meta( $form_id, '_give_logged_in_only', true );
852
853
	$ret = ! empty( $form_option ) ? $form_option : false;
854
855
	return (bool) apply_filters( 'give_logged_in_only', $ret, $form_id );
856
857
}
858
859
860
/**
861
 * Checks the option for the "Register / Login Option"
862 10
 *
863
 * @since 1.4.1
864 10
 *
865
 * @param $form_id
866 10
 */
867 10
function give_show_login_register_option( $form_id ) {
868 10
869 10
	$show_register_form = get_post_meta( $form_id, '_give_show_register_form', true );
870 10
871
	return apply_filters( 'give_show_register_form', $show_register_form, $form_id );
872
873
}