Passed
Push — master ( 46e064...13ee52 )
by Brian
04:28
created

getpaid_date_format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Contains helper functions.
4
 *
5
 * @since 1.0.0
6
 * @package Invoicing
7
 */
8
 
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * Are we supporting item quantities?
13
 */
14
function wpinv_item_quantities_enabled() {
15
    return true;
16
}
17
18
/**
19
 * Returns the user's ip address.
20
 */
21
function wpinv_get_ip() {
22
    $ip = $_SERVER['REMOTE_ADDR'];
23
24
    if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
25
        //Check ip from share internet.
26
        $ip = $_SERVER['HTTP_CLIENT_IP'];
27
    } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
28
        //Check ip is pass from proxy.
29
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
30
    }
31
32
    return apply_filters( 'wpinv_get_ip', $ip );
33
}
34
35
function wpinv_get_user_agent() {
36
    if ( ! empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
37
        $user_agent = sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] );
38
    } else {
39
        $user_agent = '';
40
    }
41
42
    return apply_filters( 'wpinv_get_user_agent', $user_agent );
43
}
44
45
/**
46
 * Sanitizes an amount.
47
 * 
48
 * @param string $amount The amount to sanitize.
49
 */
50
function wpinv_sanitize_amount( $amount ) {
51
52
    // Format decimals.
53
    $amount = str_replace( wpinv_decimal_separator(), '.', $amount );
54
55
    // Remove thousands.
56
    $amount = str_replace( wpinv_thousands_separator(), '', $amount );
57
58
    // Cast the remaining to a float.
59
    return (float) preg_replace( '/[^0-9\.\-]/', '', $amount );
60
61
}
62
63
function wpinv_round_amount( $amount, $decimals = NULL ) {
64
    if ( $decimals === NULL ) {
65
        $decimals = wpinv_decimals();
66
    }
67
    
68
    $amount = round( (double)$amount, wpinv_currency_decimal_filter( absint( $decimals ) ) );
69
70
    return apply_filters( 'wpinv_round_amount', $amount, $decimals );
71
}
72
73
/**
74
 * Get all invoice statuses.
75
 *
76
 * @since 1.0.19
77
 * @return array
78
 */
79
function wpinv_get_invoice_statuses( $draft = false, $trashed = false, $invoice = false ) {
80
	$invoice_statuses = array(
81
		'wpi-pending'    => _x( 'Pending payment', 'Invoice status', 'invoicing' ),
82
        'publish'        => _x( 'Paid', 'Invoice status', 'invoicing' ),
83
        'wpi-processing' => _x( 'Processing', 'Invoice status', 'invoicing' ),
84
		'wpi-onhold'     => _x( 'On hold', 'Invoice status', 'invoicing' ),
85
		'wpi-cancelled'  => _x( 'Cancelled', 'Invoice status', 'invoicing' ),
86
		'wpi-refunded'   => _x( 'Refunded', 'Invoice status', 'invoicing' ),
87
        'wpi-failed'     => _x( 'Failed', 'Invoice status', 'invoicing' ),
88
        'wpi-renewal'    => _x( 'Renewal Payment', 'Invoice status', 'invoicing' ),
89
    );
90
91
    if ( $draft ) {
92
        $invoice_statuses['draft'] = __( 'Draft', 'invoicing' );
93
    }
94
95
    if ( $trashed ) {
96
        $invoice_statuses['trash'] = __( 'Trash', 'invoicing' );
97
    }
98
99
	return apply_filters( 'wpinv_statuses', $invoice_statuses, $invoice );
100
}
101
102
function wpinv_status_nicename( $status ) {
103
    $statuses = wpinv_get_invoice_statuses( true, true );
104
    $status   = isset( $statuses[$status] ) ? $statuses[$status] : __( $status, 'invoicing' );
105
106
    return $status;
107
}
108
109
/**
110
 * Retrieves the default currency code.
111
 * 
112
 * @param string $current
113
 */
114
function wpinv_get_currency( $current = '' ) {
115
116
    if ( empty( $current ) ) {
117
        $current = apply_filters( 'wpinv_currency', wpinv_get_option( 'currency', 'USD' ) );
118
    }
119
120
    return trim( strtoupper( $current ) );
121
}
122
123
/**
124
 * Given a currency, it returns a currency symbol.
125
 * 
126
 * @param string|null $currency The currency code. Defaults to the default currency.
127
 */
128
function wpinv_currency_symbol( $currency = null ) {
129
130
    // Prepare the currency.
131
    $currency = empty( $currency ) ? wpinv_get_currency() : wpinv_clean( $currency );
132
133
    // Fetch all symbols.
134
    $symbols = wpinv_get_currency_symbols();
135
136
    // Fetch this currencies symbol.
137
    $currency_symbol = isset( $symbols[$currency] ) ? $symbols[$currency] : $currency;
138
139
    // Filter the symbol.
140
    return apply_filters( 'wpinv_currency_symbol', $currency_symbol, $currency );
141
}
142
143
function wpinv_currency_position() {
144
    $position = wpinv_get_option( 'currency_position', 'left' );
145
    
146
    return apply_filters( 'wpinv_currency_position', $position );
147
}
148
149
/**
150
 * Returns the thousands separator for a currency.
151
 * 
152
 * @param $string|null $current
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string|null at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string|null.
Loading history...
153
 */
154
function wpinv_thousands_separator( $current = null ) {
155
156
    if ( null == $current ) {
157
        $current = wpinv_get_option( 'thousands_separator', '.' );
158
    }
159
160
    return trim( $current );
161
}
162
163
/**
164
 * Returns the decimal separator for a currency.
165
 * 
166
 * @param $string|null $current
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string|null at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string|null.
Loading history...
167
 */
168
function wpinv_decimal_separator( $current = null ) {
169
170
    if ( null == $current ) {
171
        $current = wpinv_get_option( 'decimal_separator', '.' );
172
    }
173
    
174
    return trim( $current );
175
}
176
177
/**
178
 * Returns the number of decimals to use.
179
 * 
180
 * @param $string|null $current
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string|null at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string|null.
Loading history...
181
 */
182
function wpinv_decimals( $current = null ) {
183
184
    if ( null == $current ) {
185
        $current = wpinv_get_option( 'decimals', 2 );
186
    }
187
    
188
    return absint( $current );
189
}
190
191
/**
192
 * Retrieves a list of all supported currencies.
193
 */
194
function wpinv_get_currencies() {
195
    return apply_filters( 'wpinv_currencies', wpinv_get_data( 'currencies' ) );
196
}
197
198
/**
199
 * Retrieves a list of all currency symbols.
200
 */
201
function wpinv_get_currency_symbols() {
202
    return apply_filters( 'wpinv_currency_symbols', wpinv_get_data( 'currency-symbols' ) );
203
}
204
205
/**
206
 * Get the price format depending on the currency position.
207
 *
208
 * @return string
209
 */
210
function getpaid_get_price_format() {
211
	$currency_pos = wpinv_currency_position();
212
	$format       = '%1$s%2$s';
213
214
	switch ( $currency_pos ) {
215
		case 'left':
216
			$format = '%1$s%2$s';
217
			break;
218
		case 'right':
219
			$format = '%2$s%1$s';
220
			break;
221
		case 'left_space':
222
			$format = '%1$s&nbsp;%2$s';
223
			break;
224
		case 'right_space':
225
			$format = '%2$s&nbsp;%1$s';
226
			break;
227
	}
228
229
	return apply_filters( 'getpaid_price_format', $format, $currency_pos );
230
}
231
232
/**
233
 * Format the amount with a currency symbol.
234
 *
235
 * @param  float  $amount Raw price.
236
 * @param  string $currency Currency.
237
 * @return string
238
 */
239
function wpinv_price( $amount = 0, $currency = '' ) {
240
241
    // Backwards compatibility.
242
    $amount             = floatval( wpinv_sanitize_amount( str_replace( wpinv_thousands_separator(), '', $amount ) ) );
243
244
    // Prepare variables.
245
    $currency           = wpinv_get_currency( $currency );
246
    $amount             = (float) $amount;
247
    $unformatted_amount = $amount;
248
    $negative           = $amount < 0;
249
    $amount             = apply_filters( 'getpaid_raw_amount', floatval( $negative ? $amount * -1 : $amount ) );
250
    $amount             = wpinv_format_amount( $amount );
251
252
    // Format the amount.
253
    $format             = getpaid_get_price_format();
254
    $formatted_amount   = ( $negative ? '-' : '' ) . sprintf( $format, '<span class="getpaid-currency__symbol">' . wpinv_currency_symbol( $currency ) . '</span>', $amount );
255
256
    // Filter the formatting.
257
    return apply_filters( 'wpinv_price', $formatted_amount, $amount, $currency, $unformatted_amount );
258
}
259
260
/**
261
 * Format an amount with separators.
262
 *
263
 * @param  float    $amount Raw amount.
264
 * @param  null|int $decimals Number of decimals to use.
265
 * @param  bool     $calculate Whether or not to apply separators.
266
 * @return string
267
 */
268
function wpinv_format_amount( $amount, $decimals = null, $calculate = false ) {
269
    $thousands_sep = wpinv_thousands_separator();
270
    $decimal_sep   = wpinv_decimal_separator();
271
    $decimals      = wpinv_decimals( $decimals );
272
273
    // Format decimals.
274
    $amount = str_replace( $decimal_sep, '.', $amount );
275
276
    // Remove thousands.
277
    $amount = str_replace( $thousands_sep, '', $amount );
278
279
    // Cast the remaining to a float.
280
    $amount = floatval( $amount );
281
282
    if ( $calculate ) {
283
        return $amount;
284
    }
285
286
    // Fomart the amount.
287
    return number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
288
}
289
290
function wpinv_sanitize_key( $key ) {
291
    $raw_key = $key;
292
    $key = preg_replace( '/[^a-zA-Z0-9_\-\.\:\/]/', '', $key );
293
294
    return apply_filters( 'wpinv_sanitize_key', $key, $raw_key );
295
}
296
297
/**
298
 * Returns a file extesion.
299
 * 
300
 * @param $str the file whose extension should be retrieved.
301
 */
302
function wpinv_get_file_extension( $str ) {
303
    $filetype = wp_check_filetype( $str );
304
    return $filetype['ext'];
305
}
306
307
/**
308
 * Checks if a given string is an image URL.
309
 * 
310
 * @param string $string
311
 */
312
function wpinv_string_is_image_url( $string ) {
313
    $extension = strtolower( wpinv_get_file_extension( $string ) );
314
    return in_array( $extension, array( 'jpeg', 'jpg', 'png', 'gif', 'ico' ), true );
315
}
316
317
/**
318
 * Returns the current URL.
319
 */
320
function wpinv_get_current_page_url() {
321
    return ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
322
}
323
324
/**
325
 * Define a constant if it is not already defined.
326
 *
327
 * @since 1.0.19
328
 * @param string $name  Constant name.
329
 * @param mixed  $value Value.
330
 */
331
function getpaid_maybe_define_constant( $name, $value ) {
332
	if ( ! defined( $name ) ) {
333
		define( $name, $value );
334
	}
335
}
336
337
function wpinv_get_php_arg_separator_output() {
338
	return ini_get( 'arg_separator.output' );
339
}
340
341
function wpinv_rgb_from_hex( $color ) {
342
    $color = str_replace( '#', '', $color );
343
344
    // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF"
345
    $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
346
    if ( empty( $color ) ) {
347
        return NULL;
348
    }
349
350
    $color = str_split( $color );
351
352
    $rgb      = array();
353
    $rgb['R'] = hexdec( $color[0] . $color[1] );
354
    $rgb['G'] = hexdec( $color[2] . $color[3] );
355
    $rgb['B'] = hexdec( $color[4] . $color[5] );
356
357
    return $rgb;
358
}
359
360
function wpinv_hex_darker( $color, $factor = 30 ) {
361
    $base  = wpinv_rgb_from_hex( $color );
362
    $color = '#';
363
364
    foreach ( $base as $k => $v ) {
365
        $amount      = $v / 100;
366
        $amount      = round( $amount * $factor );
367
        $new_decimal = $v - $amount;
368
369
        $new_hex_component = dechex( $new_decimal );
0 ignored issues
show
Bug introduced by
$new_decimal of type double is incompatible with the type integer expected by parameter $number of dechex(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

369
        $new_hex_component = dechex( /** @scrutinizer ignore-type */ $new_decimal );
Loading history...
370
        if ( strlen( $new_hex_component ) < 2 ) {
371
            $new_hex_component = "0" . $new_hex_component;
372
        }
373
        $color .= $new_hex_component;
374
    }
375
376
    return $color;
377
}
378
379
function wpinv_hex_lighter( $color, $factor = 30 ) {
380
    $base  = wpinv_rgb_from_hex( $color );
381
    $color = '#';
382
383
    foreach ( $base as $k => $v ) {
384
        $amount      = 255 - $v;
385
        $amount      = $amount / 100;
386
        $amount      = round( $amount * $factor );
387
        $new_decimal = $v + $amount;
388
389
        $new_hex_component = dechex( $new_decimal );
0 ignored issues
show
Bug introduced by
$new_decimal of type double is incompatible with the type integer expected by parameter $number of dechex(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

389
        $new_hex_component = dechex( /** @scrutinizer ignore-type */ $new_decimal );
Loading history...
390
        if ( strlen( $new_hex_component ) < 2 ) {
391
            $new_hex_component = "0" . $new_hex_component;
392
        }
393
        $color .= $new_hex_component;
394
    }
395
396
    return $color;
397
}
398
399
function wpinv_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
400
    $hex = str_replace( '#', '', $color );
401
402
    $c_r = hexdec( substr( $hex, 0, 2 ) );
403
    $c_g = hexdec( substr( $hex, 2, 2 ) );
404
    $c_b = hexdec( substr( $hex, 4, 2 ) );
405
406
    $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
407
408
    return $brightness > 155 ? $dark : $light;
409
}
410
411
function wpinv_format_hex( $hex ) {
412
    $hex = trim( str_replace( '#', '', $hex ) );
413
414
    if ( strlen( $hex ) == 3 ) {
415
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
416
    }
417
418
    return $hex ? '#' . $hex : null;
419
}
420
421
/**
422
 * Get truncated string with specified width.
423
 *
424
 * @since 1.0.0
425
 *
426
 * @param string $str The string being decoded.
427
 * @param int $start The start position offset. Number of characters from the beginning of string.
428
 *                      For negative value, number of characters from the end of the string.
429
 * @param int $width The width of the desired trim. Negative widths count from the end of the string.
430
 * @param string $trimmaker A string that is added to the end of string when string is truncated. Ex: "...".
431
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
432
 * @return string
433
 */
434
function wpinv_utf8_strimwidth( $str, $start, $width, $trimmaker = '', $encoding = 'UTF-8' ) {
435
    if ( function_exists( 'mb_strimwidth' ) ) {
436
        return mb_strimwidth( $str, $start, $width, $trimmaker, $encoding );
437
    }
438
    
439
    return wpinv_utf8_substr( $str, $start, $width, $encoding ) . $trimmaker;
440
}
441
442
/**
443
 * Get the string length.
444
 *
445
 * @since 1.0.0
446
 *
447
 * @param string $str The string being checked for length. 
448
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
449
 * @return int Returns the number of characters in string.
450
 */
451
function wpinv_utf8_strlen( $str, $encoding = 'UTF-8' ) {
452
    if ( function_exists( 'mb_strlen' ) ) {
453
        return mb_strlen( $str, $encoding );
454
    }
455
        
456
    return strlen( $str );
457
}
458
459
function wpinv_utf8_strtolower( $str, $encoding = 'UTF-8' ) {
460
    if ( function_exists( 'mb_strtolower' ) ) {
461
        return mb_strtolower( $str, $encoding );
462
    }
463
    
464
    return strtolower( $str );
465
}
466
467
function wpinv_utf8_strtoupper( $str, $encoding = 'UTF-8' ) {
468
    if ( function_exists( 'mb_strtoupper' ) ) {
469
        return mb_strtoupper( $str, $encoding );
470
    }
471
    
472
    return strtoupper( $str );
473
}
474
475
/**
476
 * Find position of first occurrence of string in a string
477
 *
478
 * @since 1.0.0
479
 *
480
 * @param string $str The string being checked.
481
 * @param string $find The string to find in input string.
482
 * @param int $offset The search offset. Default "0". A negative offset counts from the end of the string.
483
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
484
 * @return int Returns the position of the first occurrence of search in the string.
485
 */
486
function wpinv_utf8_strpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
487
    if ( function_exists( 'mb_strpos' ) ) {
488
        return mb_strpos( $str, $find, $offset, $encoding );
489
    }
490
        
491
    return strpos( $str, $find, $offset );
492
}
493
494
/**
495
 * Find position of last occurrence of a string in a string.
496
 *
497
 * @since 1.0.0
498
 *
499
 * @param string $str The string being checked, for the last occurrence of search.
500
 * @param string $find The string to find in input string.
501
 * @param int $offset Specifies begin searching an arbitrary number of characters into the string.
502
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
503
 * @return int Returns the position of the last occurrence of search.
504
 */
505
function wpinv_utf8_strrpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
506
    if ( function_exists( 'mb_strrpos' ) ) {
507
        return mb_strrpos( $str, $find, $offset, $encoding );
508
    }
509
        
510
    return strrpos( $str, $find, $offset );
511
}
512
513
/**
514
 * Get the part of string.
515
 *
516
 * @since 1.0.0
517
 *
518
 * @param string $str The string to extract the substring from.
519
 * @param int $start If start is non-negative, the returned string will start at the entered position in string, counting from zero.
520
 *                      If start is negative, the returned string will start at the entered position from the end of string. 
521
 * @param int|null $length Maximum number of characters to use from string.
522
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
523
 * @return string
524
 */
525
function wpinv_utf8_substr( $str, $start, $length = null, $encoding = 'UTF-8' ) {
526
    if ( function_exists( 'mb_substr' ) ) {
527
        if ( $length === null ) {
528
            return mb_substr( $str, $start, wpinv_utf8_strlen( $str, $encoding ), $encoding );
529
        } else {
530
            return mb_substr( $str, $start, $length, $encoding );
531
        }
532
    }
533
        
534
    return substr( $str, $start, $length );
535
}
536
537
/**
538
 * Get the width of string.
539
 *
540
 * @since 1.0.0
541
 *
542
 * @param string $str The string being decoded.
543
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
544
 * @return string The width of string.
545
 */
546
function wpinv_utf8_strwidth( $str, $encoding = 'UTF-8' ) {
547
    if ( function_exists( 'mb_strwidth' ) ) {
548
        return mb_strwidth( $str, $encoding );
549
    }
550
    
551
    return wpinv_utf8_strlen( $str, $encoding );
552
}
553
554
function wpinv_utf8_ucfirst( $str, $lower_str_end = false, $encoding = 'UTF-8' ) {
555
    if ( function_exists( 'mb_strlen' ) ) {
556
        $first_letter = wpinv_utf8_strtoupper( wpinv_utf8_substr( $str, 0, 1, $encoding ), $encoding );
557
        $str_end = "";
558
        
559
        if ( $lower_str_end ) {
560
            $str_end = wpinv_utf8_strtolower( wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding ), $encoding );
561
        } else {
562
            $str_end = wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding );
563
        }
564
565
        return $first_letter . $str_end;
566
    }
567
    
568
    return ucfirst( $str );
569
}
570
571
function wpinv_utf8_ucwords( $str, $encoding = 'UTF-8' ) {
572
    if ( function_exists( 'mb_convert_case' ) ) {
573
        return mb_convert_case( $str, MB_CASE_TITLE, $encoding );
574
    }
575
    
576
    return ucwords( $str );
577
}
578
579
function wpinv_period_in_days( $period, $unit ) {
580
    $period = absint( $period );
581
    
582
    if ( $period > 0 ) {
583
        if ( in_array( strtolower( $unit ), array( 'w', 'week', 'weeks' ) ) ) {
584
            $period = $period * 7;
585
        } else if ( in_array( strtolower( $unit ), array( 'm', 'month', 'months' ) ) ) {
586
            $period = $period * 30;
587
        } else if ( in_array( strtolower( $unit ), array( 'y', 'year', 'years' ) ) ) {
588
            $period = $period * 365;
589
        }
590
    }
591
    
592
    return $period;
593
}
594
595
function wpinv_cal_days_in_month( $calendar, $month, $year ) {
596
    if ( function_exists( 'cal_days_in_month' ) ) {
597
        return cal_days_in_month( $calendar, $month, $year );
598
    }
599
600
    // Fallback in case the calendar extension is not loaded in PHP
601
    // Only supports Gregorian calendar
602
    return date( 't', mktime( 0, 0, 0, $month, 1, $year ) );
603
}
604
605
/**
606
 * Display a help tip for settings.
607
 *
608
 * @param  string $tip Help tip text
609
 * @param  bool $allow_html Allow sanitized HTML if true or escape
610
 *
611
 * @return string
612
 */
613
function wpi_help_tip( $tip, $allow_html = false ) {
614
    if ( $allow_html ) {
615
        $tip = wpi_sanitize_tooltip( $tip );
616
    } else {
617
        $tip = esc_attr( $tip );
618
    }
619
620
    return '<span class="wpi-help-tip dashicons dashicons-editor-help" title="' . $tip . '"></span>';
621
}
622
623
/**
624
 * Sanitize a string destined to be a tooltip.
625
 *
626
 * Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
627
 *
628
 * @param string $var
629
 * @return string
630
 */
631
function wpi_sanitize_tooltip( $var ) {
632
    return htmlspecialchars( wp_kses( html_entity_decode( $var ), array(
633
        'br'     => array(),
634
        'em'     => array(),
635
        'strong' => array(),
636
        'small'  => array(),
637
        'span'   => array(),
638
        'ul'     => array(),
639
        'li'     => array(),
640
        'ol'     => array(),
641
        'p'      => array(),
642
    ) ) );
643
}
644
645
/**
646
 * Get all WPI screen ids.
647
 *
648
 * @return array
649
 */
650
function wpinv_get_screen_ids() {
651
652
    $screen_id = sanitize_title( __( 'Invoicing', 'invoicing' ) );
653
654
    $screen_ids = array(
655
        'toplevel_page_' . $screen_id,
656
        'wpi_invoice',
657
        'wpi_item',
658
        'wpi_quote',
659
        'wpi_discount',
660
        'edit-wpi_invoice',
661
        'edit-wpi_item',
662
        'edit-wpi_discount',
663
        'edit-wpi_quote',
664
        'invoicing_page_wpinv-settings',
665
        'invoicing_page_wpinv-subscriptions',
666
        'invoicing_page_wpinv-reports',
667
        'invoicing_page_wpi-addons',
668
    );
669
670
    return apply_filters( 'wpinv_screen_ids', $screen_ids );
671
}
672
673
/**
674
 * Cleans up an array, comma- or space-separated list of scalar values.
675
 *
676
 * @since 1.0.13
677
 *
678
 * @param array|string $list List of values.
679
 * @return array Sanitized array of values.
680
 */
681
function wpinv_parse_list( $list ) {
682
683
    if ( empty( $list ) ) {
684
        $list = array();
685
    }
686
687
	if ( ! is_array( $list ) ) {
688
		return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_split('/[\s,...1, PREG_SPLIT_NO_EMPTY) could also return false which is incompatible with the documented return type array. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
689
	}
690
691
	return $list;
692
}
693
694
/**
695
 * Fetches data stored on disk.
696
 *
697
 * @since 1.0.14
698
 *
699
 * @param string $key Type of data to fetch.
700
 * @return mixed Fetched data.
701
 */
702
function wpinv_get_data( $key ) {
703
704
    // Try fetching it from the cache.
705
    $data = wp_cache_get( "wpinv-data-$key", 'wpinv' );
706
    if( $data ) {
707
        return $data;
708
    }
709
710
    $data = apply_filters( "wpinv_get_$key", include WPINV_PLUGIN_DIR . "includes/data/$key.php" );
711
	wp_cache_set( "wpinv-data-$key", $data, 'wpinv' );
712
713
	return $data;
714
}
715
716
/**
717
 * (Maybe) Adds an empty option to an array of options.
718
 *
719
 * @since 1.0.14
720
 *
721
 * @param array $options
722
 * @param bool $first_empty Whether or not the first item in the list should be empty
723
 * @return mixed Fetched data.
724
 */
725
function wpinv_maybe_add_empty_option( $options, $first_empty ) {
726
727
    if ( ! empty( $options ) && $first_empty ) {
728
        return array_merge( array( '' => '' ), $options );
729
    }
730
    return $options;
731
732
}
733
734
/**
735
 * Clean variables using sanitize_text_field.
736
 *
737
 * @param mixed $var Data to sanitize.
738
 * @return string|array
739
 */
740
function wpinv_clean( $var ) {
741
742
	if ( is_array( $var ) ) {
743
		return array_map( 'wpinv_clean', $var );
744
    }
745
746
    if ( is_object( $var ) ) {
747
		$object_vars = get_object_vars( $var );
748
		foreach ( $object_vars as $property_name => $property_value ) {
749
			$var->$property_name = wpinv_clean( $property_value );
750
        }
751
        return $var;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $var returns the type object which is incompatible with the documented return type array|string.
Loading history...
752
	}
753
    
754
    return is_string( $var ) ? sanitize_text_field( $var ) : $var;
755
}
756
757
/**
758
 * Converts a price string into an options array.
759
 *
760
 * @param string $str Data to convert.
761
 * @return string|array
762
 */
763
function getpaid_convert_price_string_to_options( $str ) {
764
765
	$raw_options = array_map( 'trim', explode( ',', $str ) );
766
    $options     = array();
767
768
    foreach ( $raw_options as $option ) {
769
770
        if ( '' == $option ) {
771
            continue;
772
        }
773
774
        $option = array_map( 'trim', explode( '|', $option ) );
775
776
        $price = null;
777
        $label = null;
778
779
        if ( isset( $option[0] ) && '' !=  $option[0] ) {
780
            $label  = $option[0];
781
        }
782
783
        if ( isset( $option[1] ) && '' !=  $option[1] ) {
784
            $price = $option[1];
785
        }
786
787
        if ( ! isset( $price ) ) {
788
            $price = $label;
789
        }
790
791
        if ( ! isset( $price ) || ! is_numeric( $price ) ) {
792
            continue;
793
        }
794
795
        if ( ! isset( $label ) ) {
796
            $label = $price;
797
        }
798
799
        $options[ $price ] = $label;
800
    }
801
802
    return $options;
803
}
804
805
/**
806
 * Returns the help tip.
807
 */
808
function getpaid_get_help_tip( $tip, $additional_classes = '' ) {
809
    $additional_classes = sanitize_html_class( $additional_classes );
810
    $tip                = esc_attr__( $tip );
811
    return "<span class='wpi-help-tip dashicons dashicons-editor-help $additional_classes' title='$tip'></span>";
812
}
813
814
/**
815
 * Formats a date
816
 */
817
function getpaid_format_date( $date ) {
818
819
    if ( empty( $date ) || $date == '0000-00-00 00:00:00' ) {
820
        return '';
821
    }
822
823
    return date_i18n( getpaid_date_format(), strtotime( $date ) );
824
825
}
826
827
/**
828
 * Formats a date into the website's date setting.
829
 *
830
 * @return string
831
 */
832
function getpaid_format_date_value( $date, $default = "&mdash;" ) {
833
    $date = getpaid_format_date( $date );
834
    return empty( $date ) ? $default : $date;
835
}
836
837
/**
838
 * Get the date format used all over the plugin.
839
 *
840
 * @return string
841
 */
842
function getpaid_date_format() {
843
	return apply_filters( 'getpaid_date_format', get_option( 'date_format' ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression return apply_filters('ge..._option('date_format')) could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
844
}
845
846
/**
847
 * Get the time format used all over the plugin.
848
 *
849
 * @return string
850
 */
851
function getpaid_time_format() {
852
	return apply_filters( 'getpaid_time_format', get_option( 'time_format' ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression return apply_filters('ge..._option('time_format')) could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
853
}
854
855
/**
856
 * Limit length of a string.
857
 *
858
 * @param  string  $string string to limit.
859
 * @param  integer $limit Limit size in characters.
860
 * @return string
861
 */
862
function getpaid_limit_length( $string, $limit ) {
863
    $str_limit = $limit - 3;
864
865
	if ( function_exists( 'mb_strimwidth' ) ) {
866
		if ( mb_strlen( $string ) > $limit ) {
867
			$string = mb_strimwidth( $string, 0, $str_limit ) . '...';
868
		}
869
	} else {
870
		if ( strlen( $string ) > $limit ) {
871
			$string = substr( $string, 0, $str_limit ) . '...';
872
		}
873
	}
874
    return $string;
875
876
}
877
878
/**
879
 * Returns the REST API handler.
880
 * 
881
 * @return WPInv_API
882
 * @since 1.0.19
883
 */
884
function getpaid_api() {
885
    return getpaid()->get( 'api' );
886
}
887
888
/**
889
 * Returns the post types object.
890
 * 
891
 * @return GetPaid_Post_Types
892
 * @since 1.0.19
893
 */
894
function getpaid_post_types() {
895
    return getpaid()->get( 'post_types' );
896
}
897
898
/**
899
 * Returns the session handler.
900
 * 
901
 * @return WPInv_Session_Handler
902
 * @since 1.0.19
903
 */
904
function getpaid_session() {
905
    return getpaid()->get( 'session' );
906
}
907
908
/**
909
 * Returns the notes handler.
910
 * 
911
 * @return WPInv_Notes
912
 * @since 1.0.19
913
 */
914
function getpaid_notes() {
915
    return getpaid()->get( 'notes' );
916
}
917
918
/**
919
 * Returns the main admin class.
920
 * 
921
 * @return GetPaid_Admin
922
 */
923
function getpaid_admin() {
924
    return getpaid()->get( 'admin' );
925
}
926
927
/**
928
 * Retrieves a URL to an authenticated action
929
 *
930
 * @param string $action
931
 * @param string $base the base url
932
 * @return string
933
 */
934
function getpaid_get_authenticated_action_url( $action, $base = false ) {
935
    return wp_nonce_url( add_query_arg( 'getpaid-action', $action, $base ), 'getpaid-nonce', 'getpaid-nonce' );
936
}
937