-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper-functions.inc.php
1860 lines (1700 loc) · 59 KB
/
helper-functions.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file contains a number of "pure" helper funciton used for
* sanitising and validating user inputs
*
* These functions have no side effects
*
* PHP Version 7.1
*
* @category Validation
* @package Validation
* @author Evan Wills <evan.i.wills@gmail.com>
* @license GPL2 <https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html>
* @link https://github.com/evanwills/php-utils
*/
if (!defined('GST_PERCENT')) {
/**
* The amount of GST charged
*
* @var float GST_PERCENT
*/
define('GST_PERCENT', 10);
}
if (!defined('GST_FACTOR')) {
/**
* Proportion of displayed dollar value that is GST
*
* @var float GST_FACTOR
*/
define('GST_FACTOR', (1 / ((100 + GST_PERCENT) / 100)));
}
if (!defined('SHOW_COMMENTS')) {
define('SHOW_COMMENTS', false);
}
if (!defined('ABSOLUTE_MIN_TIME')) {
/**
* Unix timestamp for absolute minimum time allowed
*
* @var integer ABSOLUTE_MIN_TIME
*/
define('ABSOLUTE_MIN_TIME', strtotime('- 110 years'));
}
if (!defined('ABSOLUTE_MAX_TIME')) {
/**
* Unix timestamp for absolute maximum time allowed
*
* @var integer ABSOLUTE_MAX_TIME
*/
define('ABSOLUTE_MAX_TIME', strtotime('+ 50 years'));
}
if (!function_exists('newrelic_add_custom_tracer')) {
function newrelic_add_custom_tracer() {} // phpcs:ignore
}
/**
* Check if an array has the specified key and return validated value
* or default value if desired field was missing or invalid.
*
* This primarily intended for validating/sanitising user supplied
* values from `$_POST`, `$_GET` `$_SESSION`, `$_COOKIES` (etc.)
* before they are
* processed by application code.
*
* The call signature is intended to feel like an enhanced version of
* PHP's built in `array_key_exists()` fuction.
*
* > __Note:__ By passing in the array, instead of depending on
* > $_POST, $_GET $_SESSION, $_COOKIES etc, this function
* > is much easier to test and use.
*
* @param string $key Array key to be checked
* @param array $inputArray Array (almost always $_POST) whose
* key is to be checked
* @param mixed $default Default value to be returned if key
* is not present or invalid
* @param string $mode What (if any) extra
* validation/sanitisation should be
* applied to the matched value
* Mode options are:
* * `anyphone` Any Australian or
* international phone number (see:
* [sanitiseAnyPhone()](#function_sanitiseAnyPhone))
* * `aupostcode` Australian post code (see:
* [validateAUPostCode()](#function_validateAUPostCode))
* * `bool` Used for checkboxes
* (expected value: 1 or 'true' or 'yes'
* or 'on' or TRUE)
* * `callable` Passes found value
* (& default)to callback function and
* returns the result
* * `checkbox` Returns TRUE if key
* exits (value is ignored)
* * `date` Expected input is an
* ISO 8601 date formated string
* (return value is an integer YYYY-MM-DD) (see:
* [validateIsoDate()](#function_validateIsoDate))
* * `datetime` Expected input is an
* ISO 8601 datetime formated string
* (return value is an integer
* "YYYY-MM-DD HH:MM:SS") (see:
* [validateIsoDateTime()](#function_validateIsoDateTime))
* * `email` Any valid email (see:
* [validateEmail()](#function_validateEmail))
* * `fixedphone` Australian fixed line
* phone number (with area code) (see:
* [sanitiseLandline()](#function_sanitiseLandline))
* * `html` Make sure HTML doesn't
* have any nasties
* * `int` Make sure a value is an
* integer
* * `intphone` Any international phone
* number (see
* [sanitiseOsPhone](#function_sanitiseOsPhone))
* * `landline` (see
* [fixedphone](#function_sanitiseLandline))
* * `mobile` Australian mobile phone
* number (see
* [sanitiseMobile](#function_sanitiseMobile))
* * `name` Make sure name only has
* alpha-numeric characters, hyphens,
* apostropies, spaces and/or full stops (see
* [sanitiseName](#function_sanitiseName))
* * `number` Make sure value is
* either integer or float (see
* [sanitiseNumeric](#function_sanitiseNumeric))
* * `numeric` Make sure value is
* either integer or float (see
* [sanitiseNumeric](#function_sanitiseNumeric))
* * `osphone` (see
* [`intphone`](#function_function_sanitiseOsPhone))
* * `select` Make sure the user
* supplied value is one of the options
* available (see
* [validateSelected](#function_validateSelected))
* * `text` Any text (with
* potentially bad content removed) (see
* [sanitiseText](#function_sanitiseText))
* * `time` ISO 8601 time formatted
* string ("HH:MM:SS") (see
* [validateIsoTime](#function_validateIsoTime))
* * `title` String that can be used
* as the Title of something (see
* [sanitiseTitle](#function_sanitiseTitle))
* * `url` Any URL (see
* [validateURL](#function_validateURL))
* * `year` Calendar year within (see
* [validateYear](#function_validateYear))
* 100 years of the current day
* @param mixed $modifiers modifiers to pass on to validation/sanitisation
* function (check the function link for
* the validation/sanitisation mode you're
* using)
*
* @return mixed Valid value matched by array key or default value
* if key was not found or value was invalid
*/
function getValidFromArray(
$key,
$inputArray,
$default = false,
$mode = 'default',
$modifiers = null
) {
if ( NEW_RELIC ) { newrelic_add_custom_tracer('getValidFromArray'); } // phpcs:ignore
$_default = is_string($default)
? $default
: false;
if (array_key_exists($key, $inputArray)) {
$output = trim($inputArray[$key]);
switch (strtolower($mode)) {
case 'anyphone':
return sanitiseAnyPhone($output, $_default, $modifiers);
case 'aupostcode':
return validateAUPostCode($output, $_default, $modifiers);
case 'bool':
$output = strtolower($output);
return ($output == 1 || $output == 'true'
|| $output == 'yes' || $output == 'on'
|| $output === true || $output == $key);
case 'callback':
if (is_callable($modifiers)) {
return $modifiers($output, $_default);
} else {
trigger_error(
'getValidFromArray() expects fifth '.
'parameter to be a callable function when '.
'fourth parameter `$mode` = "callback"',
E_USER_ERROR
);
}
case 'checkbox':
return true;
case 'date':
return validateIsoDate($output, $_default, $modifiers);
case 'datetime':
return validateIsoDateTime($output, $_default, $modifiers);
case 'email':
return validateEmail($output, $_default);
case 'fixedphone':
case 'landline':
return sanitiseLandline($output, $_default);
case 'html':
return sanitiseHTML($output);
case 'int':
return sanitiseInt($output, $default, $modifiers);
case 'intphone':
case 'osphone':
return sanitiseOsPhone($output, $_default);
case 'mobile':
return sanitiseMobile($output, $_default);
case 'name':
return sanitiseName($output, $modifiers);
case 'number':
case 'numeric':
return sanitiseNumeric($output, $default, $modifiers);
case 'select':
return validateSelected($output, $modifiers, $_default);
case 'text':
return sanitiseText($output, $modifiers);
case 'time':
return validateIsoTime($output, $default, $modifiers);
case 'title':
return sanitiseTitle($output, $modifiers);
case 'url':
return validateURL($output, $_default);
case 'year':
return validateYear($output, $_default, $modifiers);
default:
return $output;
}
}
return $default;
}
/**
* Check whether a supplied array value (almost always $_POST) is an
* integer greater than or equal to zero and less than or equal to
* the value supplied in $max
*
* The primary purpose of this function is to see if a user supplied
* value can be used as a "primary" or "foreign" key value in
* database queries
*
* > __Note:__ This is just a sortcut for:
* > ```php
* > getValidFromArray(
* > $key, $inputArray, $default, 'int',
* > ['min' => 0, 'max' => $max]
* > );
* > ```
*
* @param string $key array key to be tested
* @param array $inputArray array containing the key/value to
* be tested
* @param integer $default default value to be used if value
* is invalid
* @param integer $max The upper limit of the ID
*
* @return integer a valid unique to be used for that table
*/
function getMaxPosInt(
string $key,
array $inputArray,
int $default,
int $max = 100000
) : int {
if ( NEW_RELIC ) { newrelic_add_custom_tracer('getMaxPosInt'); } // phpcs:ignore
return getValidFromArray(
$key, $inputArray, $default, 'int', ['min' => 0, 'max' => $max]
);
}
// =======================================================
// START: Sanitisation functions
/**
* Convert any numeric type to an float
*
* @param mixed $input Numeric value to be forced to float
* @param float $_default Default value to be returned
*
* @return integer If input is numeric, it will be converted to a
* float. Otherwise $_default will be returned
*/
function makeFloat($input, float $_default = 0.0)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('makeFloat'); } // phpcs:ignore
if (!is_numeric($input)) {
return $_default;
}
$output = $input * 1;
settype($output, 'float');
return $output;
}
/**
* Convert any numeric type to an integer
*
* @param mixed $input Numeric value to be forced to integer
* @param int $_default Default value to be returned
*
* @return integer If input is numeric, it will be converted to an
* integer. Otherwise $_default will be returned
*/
function makeInt($input, int $_default = 0)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('makeInt'); } // phpcs:ignore
if (!is_int($_default)) {
trigger_error(
'makeInt() expects second parameter $_default to '.
'be an integer. '.gettype($_default).' given',
E_USER_ERROR
);
}
if (!is_numeric($input)) {
return $_default;
}
$output = $input * 1;
settype($output, 'integer');
return $output;
}
/**
* Removes potentially dangerous tags and attributes from HTML
*
* @param string $html HTML content to be sanitised
* @param string[]|false $_modifiers List of allowed HTML tags that
* should not be stripped.
* If FALSE, no extra tags will be
* stripped
*
* @return string Clean HTML code
*/
function sanitiseHTML($html, $_modifiers = false)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('sanitiseHTML'); } // phpcs:ignore
$badTags = array(
'applet',
'datalist', 'details', 'dir', 'embed',
'fieldset', 'form', 'frame', 'frameset',
'iframe', 'input',
'legend', 'link',
'map', 'math', 'meta',
'object', 'optgroup', 'option',
'script', 'select', 'style',
'textarea',
'video',
);
$badAttrs = array(
'align', 'alink',
'background', 'bgcolor', 'border',
'clear', 'data[a-z0-9-]+',
'height', 'hspace',
'language', 'link',
'nowrap', 'on[a-z]+', 'style',
'text', 'type',
'vlink', 'vspace', 'width'
);
$depricated = array('center', 'font');
$find = array(
// 1 (repeated spaces)
'/(?:\ |\s)+/is',
// 2 (bad tags)
'`<('.implode('|', $badTags).')[^>]*>.*?</\1>`is',
// 3 (self closing)
'/<(?:link|meta|input)[^>]*>/is',
// 4 (depricated tags)
'`</?(?:'.implode('|', $depricated).')[^>]+>`is',
// 5 (bad attributes)
'`\s(?:'.implode('|', $badAttrs).')='.
'(?:"[^">]+"|\'[^>\']+\'|[^\s>]+(?=\s|>))`i',
// 6 (redundant tags)
'/(?:<br ?\/?>)?\s*(<\/?p>)\s*(?:<br ?\/?>)?/i',
// 7 (custom elements)
'/<([a-z]+(?:-[a-z0-9]+)+)[^>]*>.*?<\/\1[^>]*>/i',
// 8 (empty tags)
'/<([a-z]+)[^>]*>\s*<\/\1[^>]*>/'
);
$replace = array(
' ', // 1
'', // 2
'', // 3
'', // 4
'', // 4
'\1', // 5
'', // 6
'' // 7
);
$output = preg_replace($find, $replace, $html);
if (is_array($_modifiers)) {
$output = strip_tags($output, $_modifiers);
}
return $output;
}
/**
* Make sure a person's name only has valid characters
*
* Characters allowed are:
* * alphabetical
* * spaces
* * hypens
* * full stops
* * apostrophies
*
* NOTE: Numbers are forbidden
*
* @param string $name Name of person to be sanitised
* @param integer $_modifier Maximum number of characters allowed
* (default: 64, min: 1, max: 64)
*
* @return string
*/
function sanitiseName($name, $_modifier = 64)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('sanitiseName'); } // phpcs:ignore
$_modifier = _charLimit($_modifier, 64, 1, 64);
// trim is done second because we may end up with white space at
// the beginin or end if there are invalid characters at the
// begining or end of the string.
return trim(
substr(
trim(
preg_replace(
array(
'`[^\w \-.\']+`i',
'`\d+(?:\.\d+)*`',
// remove duplicate consecutive non-alpha characters
'`([ \-.\'])+`'
),
array(
' ',
' ',
'\1'
),
strip_tags($name)
)
),
0, $_modifier
)
);
}
/**
* Makes sure a text has no invalid characters.
*
* Characters allowed are: alpha numeric, spaces and basic punctuation.
* Forbidden characters: ` ~ @ # $ % ^ * _ + = { } | \ ; " < >
* plus most other special characters
*
* @param string $text Title to be sanitised
* @param integer|array $_modifiers Maximum number of characters allowed
* (default: 128, min: 32, max: 2048)
* Or an array with the following keys:
* * `max` {int} maximum character length
* * `min` {int} minimum character length
* * `allowed` {string[]} List of extra
* characters that are also allowed in
* sanitised output
* * `allowonly` {string[]} List of
* characters that replace the default
* allowed characters. Only these
* characters will be returned in
* sanitised output
* * `allowraw` {string} custom regular expression
* * `dedupe` {bool} Whether or not
* to remove duplicate allowed characters
*
* @return string Clean, safe text string
*/
function sanitiseText($text, $_modifiers = false)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('sanitiseText'); } // phpcs:ignore
$minLen = 32;
$maxLen = 128;
$allowedChars = '\w&, \-.?:!\'()\/';
$regex = '';
$doDedupe = false;
$ignore = 'i';
$replaceStr = ' ';
if (is_array($_modifiers)) {
foreach ($_modifiers as $key => $value) {
$_key = strtolower($key);
$_modifiers[$_key] = $value;
}
if (array_key_exists('max', $_modifiers)) {
// Set the maximum length
$maxLen = _charLimit($_modifiers['max'], 128, $minLen, 2048);
}
if (array_key_exists('min', $_modifiers)) {
// Set the maximum length
$minLen = _charLimit($_modifiers['min'], 128, 0, $maxLen - 1);
}
if (array_key_exists('ignore', $_modifiers)
&& is_bool($_modifiers['ignore'])
) {
$ignore = ($_modifiers['ignore'] === true)
? 'i'
: '';
}
if (array_key_exists('allowed', $_modifiers)) {
// Add extra characters to the allowed character class
$regex = '/[^' .$allowedChars.
_sanitiseCharClass($_modifiers['allowed']).
']/'.$ignore;
} elseif (array_key_exists('allowonly', $_modifiers)) {
// Replace the default allowed characters with caller
// supplied characters
$regex = '/[^' .
_sanitiseCharClass($_modifiers['allowonly']).
']/'.$ignore;
} elseif (array_key_exists('allowraw', $_modifiers)) {
// Replace the default allowed characters with caller
// supplied characters
$regex = $_modifiers['allowraw'];
}
if (array_key_exists('replace', $_modifiers)) {
$replaceStr = $_modifiers['replace'];
}
if (array_key_exists('dedupe', $_modifiers)
&& is_bool($_modifiers['dedupe'])
) {
$doDedupe = $_modifiers['dedupe'];
}
} elseif (is_numeric($_modifiers)) {
// Set the maximum length
$maxLen = _charLimit($_modifiers, 128, $minLen, 2048);
}
if ($regex === '') {
$regex = '/[^'.$allowedChars.']+/'.$ignore;
}
$find = [$regex];
$replace = [$replaceStr];
if ($doDedupe === true) {
$find[] = '/\s+/';
$replace[] = ' ';
}
// Trim is done second because we may end up with white space at
// the beginin or end if there are invalid characters at the
// begining or end of the string.
return trim(
substr(
trim(
preg_replace($find, $replace, strip_tags($text))
),
0, $maxLen
)
);
}
/**
* Makes sure a title has no invalid characters.
*
* Characters allowed are: alpha numeric, spaces and basic punctuation.
*
* @param string $title Title to be sanitised
* @param integer $_modifier Maximum number of characters allowed
* (default: 64, min: 1, max: 64)
*
* @return string Clean, safe title string
*/
function sanitiseTitle(string $title, $_modifier = 128) : string
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('sanitiseTitle'); } // phpcs:ignore
$_modifier = _charLimit($_modifier, 64, 1, 64);
// trim is done last because we may end up with white space at
// the begining or end if there are invalid characters at the
// begining and/or end of the string.
return trim(
substr(
trim(
preg_replace(
[
'/[\s\t\r\n ]+/',
'/[^\w\d&,.?:! \-_\'()]+/i',
'/([&,.?:! \-_\'()])\1+/i'
],
[' ', '', '\1'],
strip_tags($title)
),
),
0,
$_modifier
)
);
}
/**
* Sanitise Australian mobile phone number
*
* @param string $number phone number sanitised
*
* @return string sanitised phone number
*/
function sanitiseMobile(string $number) : string
{
$number = preg_replace('/[^+0-9]+/', '', $number);
// debug($number);
if (preg_match('/^(?:\+61|0)(4\d{2})(\d{3})(\d{3})$/', $number, $matches)) {
return '0'.$matches[1].' '.$matches[2].' '.$matches[3];
}
// debug('[[LINE]][[LINE]]', $number);
return '';
}
/**
* Sanitise Australian fixed line phone number
*
* @param string $number phone number sanitised
*
* @return string sanitised phone number
*/
function sanitiseLandline(string $number) : string
{
$number = preg_replace('/[^+0-9]+/', '', $number);
if (preg_match('/^(?:\+61|0)([2378])(\d{4})(\d{4})$/', $number, $matches)) {
return '0'.$matches[1].' '.$matches[2].' '.$matches[3];
}
return '';
}
/**
* Sanitise international phone number
*
* @param string $number phone number sanitised
*
* @return string sanitised phone number
*/
function sanitiseOsPhone(string $number) : string
{
$number = preg_replace('/[^+0-9]+/', '', $number);
if (preg_match('/^(\+\d{2})(\d{4,12})$/', $number, $matches)) {
return $matches[1].' '.
strrev(
preg_replace(
'/(\d{4})/',
' \1',
strrev($matches[2])
)
);
}
return '';
}
/**
* Sanitise any phone number
*
* @param string $number Phone number sanitised
* @param string|mixed $_default Default value to be returned if
* phone number didn't validate
* @param array|mixed $_modifiers To be used $_modifiers must be
* array containing any of the
* following strings:
* * `os` Overseas/International
* phone number
* * `fixed` Australian land-line
* phone number
* * `mobile` Australian mobile
* phone number
* > __NOTE:__ none of the above
* strings are present, the supplied
* $_default value will always be
* returned because nothing will
* validate
*
* @return string|mixed Sanitised phone number or default value if
* phone number could not be validated.
*/
function sanitiseAnyPhone(string $number, $_default = '', $_modifiers = false)
{
if (!is_array($_modifiers)) {
$output = sanitiseMobile($number);
// debug($number, $output);
if ($output !== '') {
return $output;
}
$output = sanitiseLandline($number);
// debug($number, $output);
if ($output !== '') {
return $output;
}
$output = sanitiseOsPhone($number);
if ($output !== '') {
return $output;
}
} else {
// Standardise the identifiers for the phone number types
for ($a = 0, $c = count($_modifiers); $a < $c; $a += 1) {
if (is_string($_modifiers[$a])) {
$_modifiers[$a] = strtolower(trim($_modifiers[$a]));
if (substr($_modifiers[$a], 0, 3) === 'int') {
$_modifiers[$a] = 'os';
} elseif (substr($_modifiers[$a], 0, 4) === 'land') {
$_modifiers[$a] = 'fixed';
} elseif (substr($_modifiers[$a], 0, 4) === 'cell') {
$_modifiers[$a] = 'mobile';
}
}
}
$ok = false;
if (in_array('mobile', $_modifiers)) {
// Can be mobile number
$output = sanitiseMobile($number);
$ok = true;
if ($output !== '') {
return $output;
}
}
if (in_array('fixed', $_modifiers)) {
// Can be fixed/land line number
$output = sanitiseLandline($number);
$ok = true;
if ($output !== '') {
return $output;
}
}
if (in_array('os', $_modifiers)) {
// Can be overseas/international number
$output = sanitiseOsPhone($number);
$ok = true;
if ($output !== '') {
return $output;
}
}
if ($ok === false) {
trigger_error(
'sanitiseAnyPhone() expects modifiers to be an '.
'array containing at least one of the following '.
'strings: `mobile`, `fixed`, `os`. None of these '.
'were found so default value will be returned',
E_USER_WARNING
);
}
}
return $_default;
}
/**
* Make sure value is an integer and (if specified) within min & max
*
* > __NOTE:__ There is no validation done on $_default as this is
* always supplied by a developer who may have their own
* reasons for passing an alternative data type.
*
* @param string|integer $number Year to be validated
* @param int|mixed $_default Default value to return if year
* is invalid
* @param array|false $_modifiers Array with up to 2 integer values:
* * `min` - minimum allowable value
* * `max` - maximum allowable value
*
* Other keys will be ignored
*
* @return integer|mixed If nubmer is valid then integer is returned.
* Otherwise, $_default is returned
*/
function sanitiseInt(string $number, int $_default = 0, $_modifiers = false) : int
{
if (is_array($_modifiers)) {
$_modifiers['precision'] = 0;
} else {
$_modifiers = ['precision' => 0];
}
return sanitiseNumeric($number, $_default, $_modifiers);
}
/**
* Make sure value is an integer and (if specified) within min & max
*
* @param string $number Year to be validated
* @param mixed $_default Default value to return if year
* is invalid
* @param array|false $_modifiers Array with up to 3 integer values:
* * `min` - minimum allowable value
* * `max` - maximum allowable value
* * `precision` - number of decimal places
* * `limit` - if input is outside
* min/max, return appropriate min/max
*
* Other keys will be ignored
*
* @return integer|float|mixed If number is valid then integer or
* float is returned. Otherwise,
* $_default is returned
*/
function sanitiseNumeric(string $number, $_default = 0, $_modifiers = false)
{
$_default = ($_default === false || $_default === null)
? 0
: $_default;
if (!is_numeric($_default)) {
debug('backtrace');
trigger_error(
'sanitiseNumeric() expects second param `$_default` to be '.
'numeric. '.gettype($_default).' given',
E_USER_ERROR
);
}
$_num = preg_replace(
[
'/[^0-9.-]+/',
'/^(-?[0-9]+(?:\.[0-9]+)?).*$/'
],
[
'',
'\1'
],
$number
);
// debug($number, $_num);
if (is_numeric($_num)) {
$_num *= 1;
// debug($_num);
if (is_array($_modifiers)) {
if (array_key_exists('min', $_modifiers)) {
if (!is_numeric($_modifiers['min'])) {
trigger_error(
'sanitiseNumeric() expects `min` value to be an '.
'integer'.' "'.$_modifiers['min'].'" given',
E_USER_ERROR
);
}
if ($_num < $_modifiers['min']) {
return (array_key_exists('limit', $_modifiers))
? $_modifiers['min']
: $_default;
}
}
if (array_key_exists('max', $_modifiers)) {
if (!is_numeric($_modifiers['max'])) {
trigger_error(
'sanitiseNumeric() expects `max` value to be an '.
'integer "'.$_modifiers['max'].'" given',
E_USER_ERROR
);
}
if ($_num > $_modifiers['max']) {
return (array_key_exists('limit', $_modifiers))
? $_modifiers['max']
: $_default;
}
}
if (array_key_exists('precision', $_modifiers)) {
if (!is_int($_modifiers['precision'])) {
trigger_error(
'sanitiseNumeric() expects `precision` value to be an '.
'integer. "'.$_modifiers['precision'].'" given',
E_USER_ERROR
);
}
$_num = round($_num, $_modifiers['precision']);
}
// debug($_num);
}
// debug($_num);
return $_num;
}
return $_default;
}
// END: Sanitisation functions
// =======================================================
// START: Validation functions
/**
* Validate an Australian post code
*
* Data for this function came from
* https://en.wikipedia.org/wiki/Postcodes_in_Australia
*
* @param string $postCode HTML content to be sanitised
* @param boolean $noPoBox Exclude PO Box only post codes
*
* @return string Valid post code or empty string
*/
function validateAUPostCode(string $postCode, $noPoBox = true) : string
{
if (strlen($postCode) === 4) {
$_postCode = $postCode * 1;
$normal = [
[800, 899],
[2000, 4999],
[5000, 5799],
[6000, 6797],
[7000, 7799]
];
for ($a = 0; $a < count($normal); $a += 1) {
$min = $normal[$a][0];
$max = $normal[$a][1];
if ($_postCode >= $min && $_postCode <= $max) {
return $postCode;
}
}
if ($noPoBox === false) {
$poBox = [
[200, 299],
[900, 999],
[1000, 1999],
[5800, 5999],
[6800, 6999],
[7800, 9999],
];
for ($a = 0; $a < count($poBox); $a += 1) {
$min = $poBox[$a][0];
$max = $poBox[$a][1];
if ($_postCode >= $min && $_postCode <= $max) {
return $postCode;
}
}
}
}
return '';
}
/**
* Checks whether a string is a valid URL
*
* @param string $email URL to be parsed
* @param string|false $_default Default value to be returned
*
* @return string|false URL if it's valid, FALSE otherwise
*/
function validateEmail($email, $_default = false)
{
if ( NEW_RELIC ) { newrelic_add_custom_tracer('validateEmail'); } // phpcs:ignore
$regex = '`^[\d\w\-_.\']+@[\d\w-]+(?:\.[\d\w-]+)*(?:\.[a-z]+){1,2}$`i';
$_email = strtolower($email);
$_tmp = explode('@', $_email);
return (!isset($_tmp[1])
// Don't accept email addresses with example anywhere
|| substr_count($_email, 'example') > 0
// Don't accept emails from the "email.tst" domain
|| substr_count($_tmp[1], 'email.tst') > 0
// Don't accept emails from domains with test in them
|| substr_count($_tmp[1], 'test') > 0
// Do final regex validation
|| !preg_match($regex, $email))
? $_default
: $email;
}
/**
* Normalise select values so they are easier to match
*
* @param string $input String to be normalised
*
* @return string Normalised string
*/
function normalise(string $input) : string
{
return trim(strtolower(preg_replace('/\s+/', ' ', $input)));
}