/
Utility.php
1243 lines (1042 loc) · 32.4 KB
/
Utility.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 /* Utility.php | https://github.com/victopia/php-node */
namespace core;
use framework\Configuration;
use framework\MustacheResource;
use framework\Resolver;
/**
* Utility class.
*
* This is a collection of handy utility methods,
* read the code for hidden gems.
*
* Mostly snippets here that is not big enough
* (either size or functionality) for a standalone
* class.
*
* @author Vicary Archangel <vicary@victopia.org>
*/
class Utility {
/**
* Shorthand access to common filter types.
*/
static function &commonFilters() {
static $filters;
if ( !$filters ) {
$filters = array(
'raw' => array(
'filter' => FILTER_UNSAFE_RAW
, 'flags' => FILTER_NULL_ON_FAILURE
)
, 'rawS' => array(
'filter' => FILTER_UNSAFE_RAW
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
)
, 'rawA' => array(
'filter' => FILTER_UNSAFE_RAW
, 'flags' => FILTER_FORCE_ARRAY | FILTER_NULL_ON_FAILURE
)
, 'boolS' => array(
'filter' => FILTER_VALIDATE_BOOLEAN
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
)
, 'intS' => array(
'filter' => FILTER_VALIDATE_INT
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
)
, 'intA' => array(
'filter' => FILTER_VALIDATE_INT
, 'flags' => FILTER_FORCE_ARRAY | FILTER_NULL_ON_FAILURE
)
, 'floatS' => array(
'filter' => FILTER_VALIDATE_FLOAT
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
)
, 'floatA' => array(
'filter' => FILTER_VALIDATE_FLOAT
, 'flags' => FILTER_FORCE_ARRAY | FILTER_NULL_ON_FAILURE
)
, 'strS' => array(
'filter' => FILTER_SANITIZE_STRING
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE | FILTER_FLAG_NO_ENCODE_QUOTES
)
, 'strA' => array(
'filter' => FILTER_SANITIZE_STRING
, 'flags' => FILTER_FORCE_ARRAY | FILTER_NULL_ON_FAILURE | FILTER_FLAG_NO_ENCODE_QUOTES
)
, 'urlS' => array(
'filter' => FILTER_VALIDATE_URL
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
)
, 'urlA' => array(
'filter' => FILTER_VALIDATE_URL
, 'flags' => FILTER_FORCE_ARRAY | FILTER_NULL_ON_FAILURE
)
, 'date' => array(
'filter' => FILTER_CALLBACK
, 'flags' => FILTER_NULL_ON_FAILURE
, 'options' => '\core\Utility::validateDateTime'
)
, 'dateS' => array(
'filter' => FILTER_CALLBACK
, 'flags' => FILTER_REQUIRE_SCALAR | FILTER_NULL_ON_FAILURE
, 'options' => '\core\Utility::validateDateTime'
)
, 'priceS' => array(
'filter' => FILTER_CALLBACK
, 'options' => function($input) {
return preg_match('/[+-]?\d+(?:\.\d+)?(?:\:\w+)?/', trim(Utility::unwrapAssoc($input))) ? $input : null;
}
)
, 'regex' => function($pattern) {
return array(
'filter' => FILTER_CALLBACK
, 'options' => function($input) use($pattern) {
return preg_match($pattern, $input) ? $input : null;
}
);
}
);
}
return $filters;
}
/**
* Get callee of the current script.
*/
static function getCallee($level = 2) {
$backtrace = debug_backtrace();
if ( count($backtrace) <= $level ) {
$level = count($backtrace) - 1;
}
/* Added by Vicary @ 23 Dec, 2012
This script should:
1. try its best to search until there is a file, and
2. stop before framework scripts are reached.
*/
if ( !@$backtrace[$level]['file'] ) {
for ( $level = count($backtrace);
$level-- && !@$backtrace[$level]['file'];
);
}
// Framework scripts are:
// - resolvers
// to be added ...
while (strrchr(dirname(@$backtrace[$level]['file']), '/') == '/resolvers') {
$level--;
}
if ( $level < 0 ) {
$level = 0;
}
return @$backtrace[$level];
}
/**
* Gets all network interfaces with an appropriate IPv4 address.
*
* Mimic the output of os.networkInterfaces() in node.js.
*/
static function networkInterfaces() {
switch ( strtoupper(PHP_OS) ) {
case 'DARWIN': // MAC OS X
$res = preg_split('/\n/', @`ifconfig`);
$res = array_filter(array_map('trim', $res));
$result = array();
foreach ( $res as $row ) {
if ( preg_match('/^(\w+\d+)\:\s+(.+)/', $row, $matches) ) {
$result['__currentInterface'] = $matches[1];
$result[$result['__currentInterface']]['__internal'] = false !== strpos($matches[2], 'LOOPBACK');
}
else if ( preg_match('/^inet(6)?\s+([^\/\s]+)(?:%.+)?/', $row, $matches) ) {
$iface = &$result[$result['__currentInterface']];
@$iface[] = array(
'address' => $matches[2]
, 'family' => $matches[1] ? 'IPv6' : 'IPv4'
, 'internal' => $iface['__internal']
);
unset($iface);
}
unset($matches);
} unset($row, $res);
unset($result['__currentInterface']);
return array_filter(array_map(compose('array_filter', removes('__internal')), $result));
case 'LINUX':
// $ifaces = `ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d'`;
// $ifaces = preg_split('/\s+/', $ifaces);
$res = preg_split('/\n/', @`ip addr`);
$res = array_filter(array_map('trim', $res));
$result = array();
foreach ( $res as $row ) {
if ( preg_match('/^\d+\:\s+(\w+)/', $row, $matches) ) {
$result['__currentInterface'] = $matches[1];
}
else if ( preg_match('/^link\/(\w+)/', $row, $matches) ) {
$result[$result['__currentInterface']]['__internal'] = strtolower($matches[1]) == 'loopback';
}
else if ( preg_match('/^inet(6)?\s+([^\/]+)(?:\/\d+)?.+\s([\w\d]+)(?:\:\d+)?$/', $row, $matches) ) {
@$result[$matches[3]][] = array(
'address' => $matches[2]
, 'family' => $matches[1] ? 'IPv6' : 'IPv4'
, 'internal' => Utility::cascade(@$result[$matches[3]]['__internal'], false)
);
}
unset($matches);
} unset($row, $res);
unset($result['__currentInterface']);
return array_filter(array_map(compose('array_filter', removes('__internal')), $result));
case 'WINNT': // Currently not supported.
default:
return array();
}
}
/**
* Check whether specified file is somehow in CSV format.
*/
static function isCSV($file) {
$file = fopen($file, 'r');
if ( !$file ) {
return false;
}
for ( $i=0; $i<5; $i-- ) {
if ( fgetcsv($file) ) {
fclose($file);
return true;
}
}
fclose($file);
return false;
}
/**
* Determine whether the given string is a well formed URL.
*/
static function isURL($value) {
// SCHEME
$urlregex = '^(?:(?:file|https?|ftps?|php|zlib|data|glob|phar|ssh2|ogg|expect)\:)?\/\/\/?';
// USER AND PASS (optional)
$urlregex .= '([a-z0-9+!*(),;?&=$_.-]+(\:[a-z0-9+!*(),;?&=$_.-]+)?@)?';
// HOSTNAME OR IP
$urlregex .= '[a-z0-9+$_-]+(\.[a-z0-9+$_-]+)*'; // http://x = allowed (ex. http://localhost, http://routerlogin)
//$urlregex .= '[a-z0-9+$_-]+(\.[a-z0-9+$_-]+)+'; // http://x.x = minimum
//$urlregex .= '([a-z0-9+$_-]+\.)*[a-z0-9+$_-]{2,3}'; // http://x.xx(x) = minimum
//use only one of the above
// PORT (optional)
$urlregex .= '(\:[0-9]{2,5})?';
// PATH (optional)
$urlregex .= '(\/([a-z0-9%+$ _\-\=~\!\(\),]\.?)+)*\/?';
// GET Query (optional)
$urlregex .= '(\?[a-z+&$_.-][a-z0-9;:@\/&%=+$_.-]*)?';
// ANCHOR (optional)
$urlregex .= '(#[a-z_.-][a-z0-9+$_.-]*)?$';
// check
return (bool) preg_match("/$urlregex/i", (string) $value);
}
/**
* Determine whether an array is associative.
*
* To determine a numeric array, inverse the result of this function.
*/
static function isAssoc($value, $strict = false) {
/*! Note
* This is the original version found somewhere in the internet,
* keeping it to respect the author.
*
* Problem is numeric arrays with inconsecutive keys will return
* as associative, might be a desired outcome when doing json_encode,
* but this led to a not very descriptive function name.
*
* return is_array($value) && count($value) &&
* count(array_diff_key($value, array_keys(array_keys($value))));
*/
$ret = is_array($value) && $value &&
// all keys must be numeric to qualify as NOT assoc.
array_filter(array_keys($value), compose('not', 'is_numeric'));
// numeric keys must be consecutive to be NOT assoc (favors json_encode)
if ( $strict && !$ret ) {
$ret = $ret || array_sum(array_keys($value)) != (count($value) - 1) / 2 * count($value);
}
return $ret;
}
/**
* Wrap an associative array with a new array(), making it iteratable.
*/
static function wrapAssoc($item) {
return !is_array($item) || self::isAssoc($item) ? array($item) : $item;
}
/**
* Unwrap an array of primitives, hash-arrays or objects,
* and returns the first element.
*
* Null is returned if input array is empty.
*/
static function unwrapAssoc($list) {
if ( $list && is_array($list) && !self::isAssoc($list) ) {
return reset($list);
}
return $list;
}
/**
* Case-insensitive version of array_merge.
*
* Character case of the orginal array is preserved.
*/
static function arrayMergeIgnoreCase(&$subject) {
$args = func_get_args();
if ( !$args ) {
return null;
}
$n = count($args);
for ( $i=1; $i<$n; $i++ ) {
foreach ( $args[$i] as $objKey => &$objValue ) {
foreach ($subject as $subKey => &$subValue) {
if ( strcasecmp($subKey, $objKey) === 0 ) {
$subject[$subKey] = $objValue;
$objValue = null;
break;
}
}
if ( $objValue !== null ) {
$subject[$objKey] = $objValue;
}
}
}
return $subject;
}
/**
* Case-insenstive version of array_diff.
*/
static function arrayDiffIgnoreCase() {
$arrays = array_map(function($input) {
return array_map('strtolower', array_filter($input, 'is_string')) + $input;
}, func_get_args());
return call_user_func_array('array_diff', $arrays);
}
/**
* Case-insensitve version of in_array.
*/
static function inArrayIgnoreCase($needle, $haystack) {
return self::arraySearchIgnoreCase($needle, $haystack) !== false;
}
/**
* Case-insensitive version of array_search.
*/
static function arraySearchIgnoreCase($needle, $haystack) {
// Only lower case strings, then adding non-string key-value pairs back.
$haystack = array_map('strtolower', array_filter($haystack, 'is_string')) + $haystack;
return array_search(strtolower($needle), $haystack);
}
/**
* Case-insensitive version of array_search over keys.
*/
static function arrayKeySearchIgnoreCase($key, $search) {
$keys = array_keys($search);
$index = array_search(strtolower($key), array_map('strtolower', $keys));
if ( $index !== false ) {
$index = $keys[$index];
}
return $index;
}
/**
* Case-insensitive version of array_key_exists.
*/
static function arrayKeyExistsIgnoreCase($key, $search) {
return self::arrayKeySearchIgnoreCase($key, $search) !== false;
}
/**
* Deep conversion from stdClass (object) to array.
*/
static function objectToArray($data) {
if ( is_object($data) ) {
$data = get_object_vars($data);
}
if ( is_array($data) ) {
return array_map(array(__CLASS__, __FUNCTION__), $data);
}
return $data;
}
/**
* Deep conversion from associative arrays to objects, numeric arrays will be kept as is.
*
* For values which is already objects, this function will not traverse inside.
*/
static function arrayToObject($data) {
if ( !is_array($data) ) {
return $data;
}
else {
$data = array_map(array(__CLASS__, __FUNCTION__), $data);
if ( static::isAssoc($data) ) {
$data = (object) $data;
}
return $data;
}
}
/**
* Flatten an array, concatenating keys with specified delimiter.
*
* @param {array} $input The array to be flattened
* @param {string} $options['delimiter'] The delimiter string of the output key
* @param {boolean} $options['numeric'] Include numeric array when flattening, default true.
* @param {int} $options['level'] Maximum level of flattening, defaults to infinite.
*/
static function flattenArray($input, $options = array(), $_numeric = null) {
// Backward compatibility
if ( is_string($options) ) {
$options = array(
'delimiter' => $options
);
}
if ( is_bool($_numeric) ) {
$options['numeric'] = $_numeric;
}
// Default values
$options+= array(
'numeric' => true
, 'delimiter' => '.'
);
$recursion = function(&$input, $options) use(&$recursion) {
if ( !$input || !is_array($input) || (is_numeric(@$options['level']) && --$options['level'] <= 1) ) {
return $input;
}
// Traverse for array items.
foreach ( $input as &$value ) {
$value = $recursion($value, $options);
}
$result = array();
// Finished traversion, append array keys.
foreach ( $input as $key1 => $value1 ) {
if ( is_array($value1) ) {
if ( ( self::isAssoc($value1) || @$options['numeric'] ) ) {
foreach ( $value1 as $key2 => $value2 ) {
$result["$key1$options[delimiter]$key2"] = $value2;
}
}
else {
@$result[$key1][$key2][] = $value2;
}
}
else {
$result[$key1] = $value1;
}
}
return $result;
};
return $recursion($input, $options);
}
/**
* Reconstruct an array by breaking the keys with $delimiter, reverse of flattenArray().
*/
static function unflattenArray($input, $delimiter = '.') {
if ( !is_array($input) ) {
return $input;
}
$result = $input;
if ( self::isAssoc($input) ) {
foreach ($input as $key => $value) {
$keyPath = explode($delimiter, $key);
// Skip if it is just the same.
if ( $keyPath == (array) $key ) {
continue;
}
$valueNode = &$result;
while ( $keyPath ) {
$valueNode = &$valueNode[array_shift($keyPath)];
}
// Saves memory
unset($input[$key], $result[$key]);
$valueNode = $value;
}
}
return $result;
}
/**
* Return the first truthy value.
*
* This is made for those lazy shits like me, who does (foo || bar || baz)
* a lot in Javascript.
*
* @param {array} $list Array of values to cascade, or it will func_get_args().
*/
static function cascade($list) {
if ( func_num_args() > 1 ) {
$list = func_get_args();
}
while ( $list && !($arg = array_shift($list)) );
return @$arg; // return null when empty array is given.
}
/**
* Create deep array path if any intermediate property does not exists.
*/
static function &deepRef($path, &$input) {
if ( !is_array($path) ) {
$path = explode('.', $path);
}
$ref = &$input;
while ( $path ) {
$ref = &$ref[array_shift($path)];
}
return $ref;
}
/**
* Value version of deepRef.
*/
static function deepVal($path, $input) {
return self::deepRef($path, $input);
}
/**
* Invoke target function or method, regardless the declaration
* modifier (private, protected or public).
*
* This is achieved by the Reflection model of PHP.
*/
static function forceInvoke($callable, $parameters = null) {
$parameters = (array) $parameters;
// Normal callable
if ( !is_array($callable) && is_callable($callable) ) {
return call_user_func_array($callable, $parameters);
}
// Direct invoke ReflectionFunction
if ( $callable instanceof \ReflectionFunction ) {
return $callable->invokeArgs($parameters);
}
// "class::method" static thing
if ( is_string($callable) && strpos($callable, '::') !== false ) {
$callable = explode('::', $callable);
}
// Not callable but is an array, cast it to ReflectionMethod.
if ( is_array($callable) ) {
$method = new \ReflectionMethod($callable[0], $callable[1]);
$method->setAccessible(true);
$callable = $method->invokeArgs(
is_object($callable[0])? $callable[0]: null,
$parameters
);
if ( $method->isProtected() || $method->isPrivate() ) {
$method->setAccessible(false);
}
return $callable;
}
}
static function connectUnixSocket($address) {
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
if ( socket_connect($socket, $address) ) {
return $socket;
}
else {
$num = socket_last_error($socket);
$str = socket_strerror($num);
if ( error_reporting() ) {
throw new \Exception($str, $num);
}
return false;
}
}
/**
* Wrapper for socket_select().
*
* @param {array} $read Reading sockets to watch.
* @param {array} $write Writing sockets to watch.
* @param {array} $except Watch for exceptions in these sockets.
* @param {double} $timeout Timeout in seconds, will be properly converted into $tv_sec and $tv_usec.
*
* @return {array} In the format of [$read, $write, $except], or false when nothing is changed.
*/
static function selectSockets($read = [], $write = [], $except = [], $timeout = 0) {
$tv_sec = (int) $timeout;
$tv_usec = ($timeout - $tv_sec) * 1000000;
if ( socket_select($read, $write, $except, $tv_sec, $tv_usec) ) {
return [$read, $write, $except];
}
else {
return false;
}
}
/**
* Returns all readable data from a unix socket.
*/
static function readUnixSocket($address, $type = PHP_BINARY_READ) {
if ( is_resource($address) ) {
$socket = $address;
}
else {
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
if ( !socket_connect($socket, $address) ) {
return false;
}
}
$result = '';
// note; a single read consist of following steps
// 1. peek until there are data ready for read
// 2. consumes the data length from target socket (use the length returned from peek)
while ( true ) {
if ( !self::selectSockets([$socket]) ) {
usleep(100000);
continue;
}
$data = socket_read($socket, 1024, $type);
if ( $data === false ) {
$num = socket_last_error();
$str = socket_strerror($num);
switch ($num) {
case 11: // Resource temporary unavailable (non-blocking)
case 35: // Socket temporary unavailable (non-blocking)
usleep(100000); // sleep for 0.1 sec
break;
default:
throw new \Exception($str, $num);
break;
}
return $result ? $result : false;
}
else if ( !$data ) {
// note; we're in the half way of receiving, keep retrying even if nothing is read.
if ( $result && !@unserialize($result) ) {
usleep(100000);
continue;
}
break;
}
$result.= $data;
// note; reading finished, exit.
$data = @unserialize($result);
if ( $data ) {
return $data;
}
}
}
/**
* Bump into socket until the whole buffer is sent.
*/
static function writeUnixSocket($address, $value) {
if ( is_resource($address) ) {
$socket = $address;
}
else {
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
if ( !socket_connect($socket, $address) ) {
return false;
}
}
$value = serialize($value);
while ( $value ) {
// note; wait until sockets are writable.
if ( !self::selectSockets([], [$socket]) ) {
usleep(100000);
continue;
}
$length = socket_write($socket, substr($value, 0));
if ( $length === false ) {
$num = socket_last_error();
$str = socket_strerror($num);
switch ($num) {
case 11: // Resource temporary unavailable (non-blocking)
case 35: // Socket temporary unavailable (non-blocking)
usleep(100000); // sleep for 0.1 sec
break;
default:
throw new \Exception($str, $num);
break;
}
unset($num, $str);
}
else {
$value = substr($value, $length);
}
}
return true;
}
/**
* This function is very much like the date() function with microsecond support
* and also takes a string which originally needs an extra call to strtotime().
*/
public static /* string */
function formatDate($pattern, $date = 'now', $timezone = null) {
// todo; microseconds should only appears on now or relative dates, which counts from now.
// note; ->modify() does not alter microseconds, thus we must know whether
// $date is absolute or relative and calls that on __construct().
// note; Unable to implement such feature since date format supports string
// mixed with both absolute and relative date. e.g. "+1 day 12:01:01", "+1 hour 01 Feb, 2001"
if ( $date == 'now' ) {
$date = \DateTime::createFromFormat(
'U.u',
sprintf('%.f', microtime(1)),
new \DateTimeZone('GMT')
);
}
else {
$date = new \DateTime($date);
}
if ( $timezone === null ) {
$timezone = date_default_timezone_get();
}
$date->setTimezone(new \DateTimeZone($timezone));
return $date->format($pattern);
}
/* Added and Quoted by Vicary @ 17 Feb, 2013
Not very useful, should be a standalone duration class, or even resource bundle
for this kind of thing.
/**
* Make a "in ... (time unit)" string, compared between the input times.
*
* @param (uint) $target The target time to be compared against.
* @param (uint) $since Optional, the relative start time to compare. Defaults to current time.
public static function composeDateString($target, $since = null) {
if ( $since === null ) {
$since = time();
}
// Already past
if ( $target > $since ) {
return 'expired';
}
if ( $target > strtotime('+1 year', $since) ) {
$target = $target - $since + EPOACH;
$target = intval( date('Y', $target) );
return "in $target " . ($target > 1 ? 'years' : 'year');
}
if ( $target > strtotime('+1 month', $since) ) {
$target = $target - $since + EPOACH;
$target = intval( date('n', $target) );
return "in $target " . ($target > 1 ? 'months' : 'month');
}
if ( $target > strtotime('+1 week', $since) ) {
$target = $target - $since + EPOACH;
$target = intval( date('N', $target) );
return "in $target " . ($target > 1 ? 'weeks' : 'week');
}
// return "warn" in 3 days
if ( $target < strtotime('+3 days', $since) ) {
return 'warn';
}
$target = $target - $since + EPOACH;
$target = intval( date('j', $target) );
return "in $target " . ($tmp > 1 ? 'days' : 'day');
}
*/
/**
* Sanitize the value to be an integer.
*/
static function sanitizeInt($value) {
return filter_var($value, FILTER_SANITIZE_NUMBER_INT);
}
/**
* Sanitize the value to be plain text.
*/
static function sanitizeString($value) {
return filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH);
}
/**
* Sanitize the value to be an Regexp.
*/
static function sanitizeRegexp($value) {
if ( !preg_match('/^\/.+\/g?i?$/i', $value) ) {
$value = '/' . addslashes($value) .'/';
}
return $value;
}
/**
* Try parsing the value as XML string.
*
* @returns true on success, false otherwise.
*/
static function sanitizeXML($value) {
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xml);
$errors = libxml_get_errors();
// Allow error levels 1 and 2
if ( empty($errors) || $errors[0]->level < 3 ) {
return $value;
}
return filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH);
}
/**
* Try sanitizing the value as date.
*
* A date of zero timestamp will be returned on invalid.
*/
static function sanitizeDate($value, $format = '%Y-%m-%d') {
if ( strptime($value, $format) === false ) {
return strftime($format, 0);
}
else {
return $value;
}
}
/**
* Validate if specified input is a parsable date.
*/
static function validateDateTime($value) {
return strtotime($value) === false ? false : $value;
}
/**
* Expanding 2 digit year to 4 digits.
*
* false will be returned when parse failure.
*/
static function sanitizeYear($input) {
if ( !is_int($input-0) ) {
return false;
}
$strlen = strlen("$input");
if ( $strlen === 2 ) {
$time = strptime($input, '%y');
return $time['tm_year'] + 1900;
}
else if ( $strlen === 4 ) {
$time = strptime($input, '%Y');
return $time['tm_year'] + 1900;
}
return false;
}
/**
* Returns an array of the same length of $input and all it's elements set to $value.
*
* Optionally passing $glue will implode the created array with it.
*
* @param $input Source array to be counted.
* @param $value Any PHP value to be filled to the new array.
* @param $glue (Optional) Cusotmize implode() behavior of the result array, specify false to skip this action and return an array instead.
*
* @returns Array of the same length of $input filled with $value,
* or an imploded string of the resulting array.
*/
static function fillArray($input, $value = '?', $glue = ',') {
$result = array_fill(0, count($input), $value);
if ( $glue !== false ) {
$result = implode($glue, $result);
}
return $result;
}
/**
* Fix weird array format in $_FILES.
*/
static function filesFix() {
if ( @$_FILES && !@$_FILES['@fixed'] ) {
foreach ( $_FILES as &$file ) {
$output = array();
foreach ( $file as $fileKey => &$input ) {
$recursor = function($input, &$output) use(&$fileKey, &$recursor) {
if ( is_array($input) ) {
foreach ( $input as $key => $value ) {
$recursor($value, $output[$key]);
}
}
else {
$output[$fileKey] = $input;
}
};
$recursor($input, $output);
}
$file = $output;
}
$_FILES['@fixed'] = true;
}