forked from nazar-pc/Useful-PHP-Functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upf.php
executable file
·1433 lines (1424 loc) · 34.3 KB
/
upf.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
/**
* @package UPF (Useful PHP Functions)
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2011-2016, Nazar Mokrynskyi
* @license MIT License, see license.txt
*/
/**
* Special function for files including
*
* @param string $file
* @param bool $once
* @param bool|callable $show_errors If bool error will be processed, if callable - only callable will be called
*
* @return bool
*/
function _require ($file, $once = false, $show_errors = true) {
if (file_exists($file)) {
if ($once) {
return require_once $file;
} else {
return require $file;
}
} elseif (is_bool($show_errors) && $show_errors) {
$data = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
trigger_error("File $file does not exists in $data[file] on line $data[line]", E_USER_ERROR);
} elseif (is_callable($show_errors)) {
return (bool)$show_errors();
}
return false;
}
/**
* Special function for files including
*
* @param string $file
* @param bool $once
* @param bool|callable $show_errors If bool error will be processed, if callable - only callable will be called
*
* @return bool
*/
function _include ($file, $once = false, $show_errors = true) {
if (file_exists($file)) {
if ($once) {
return include_once $file;
} else {
return include $file;
}
} elseif (is_bool($show_errors) && $show_errors) {
$data = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
trigger_error("File $file does not exists in $data[file] on line $data[line]", E_USER_WARNING);
} elseif (is_callable($show_errors)) {
return (bool)$show_errors();
}
return false;
}
/**
* Special function for files including
*
* @param string $file
* @param bool|callable $show_errors If bool error will be processed, if callable - only callable will be called
*
* @return bool
*/
function _require_once ($file, $show_errors = true) {
return _require($file, true, $show_errors);
}
/**
* Special function for files including
*
* @param string $file
* @param bool|callable $show_errors If bool error will be processed, if callable - only callable will be called
*
* @return bool
*/
function _include_once ($file, $show_errors = true) {
return _include($file, true, $show_errors);
}
/**
* Temporary disabling of time limit
*
* @param bool $pause
*/
function time_limit_pause ($pause = true) {
static $time_limit;
if (!isset($time_limit)) {
$time_limit = ['max_execution_time' => ini_get('max_execution_time'), 'max_input_time' => ini_get('max_input_time')];
}
if ($pause) {
set_time_limit(900);
@ini_set('max_input_time', 900);
} else {
set_time_limit($time_limit['max_execution_time']);
@ini_set('max_input_time', $time_limit['max_input_time']);
}
}
/**
* Function for getting content of a directory
*
* @param string $dir Directory for searching
* @param bool|string $mask Regexp for items
* @param string $mode Mode of searching<br>
* <b>f</b> - files only (default)<br>
* <b>d</b> - directories only<br>
* <b>fd</b> - both files and directories
* @param bool|string $prefix_path Path to be added to the beginning of every found item. If <b>true</b> - prefix will
* be absolute path to item on server.
* @param bool $subfolders Search in subdirectories or not
* @param bool $sort Sort mode in format <b>mode|order</b>:<br>
* Possible values for mode: <b>name</b> (default), <b>date</b>, <b>size</b>
* Possible values for mode: <b>asc</b> (default), <b>desc</b>
* @param bool|string $exclusion If specified file exists in scanned directory - it will be excluded from scanning
* @param bool $system_files Show system files: .htaccess .htpasswd .gitignore
* @param callable $apply Apply function to each found item, return nothing (sorting will not work, items will be processed as they found)
* @param int|null $limit If specified - limits total number of found items (if $limit items found - stop further searching)
*
* @return array|bool
*/
function get_files_list (
$dir,
$mask = false,
$mode = 'f',
$prefix_path = false,
$subfolders = false,
$sort = false,
$exclusion = false,
$system_files = false,
$apply = null,
$limit = null
) {
$dir = rtrim($dir, '/');
/**
* If custom prefix for path was specified
*/
if ($prefix_path !== true && $prefix_path) {
$prefix_path = rtrim($prefix_path, '/');
}
if ($mode == 'df') {
$mode = 'fd';
}
/**
* Default sorting
*/
if ($sort === false) {
$sort = 'name';
$sort_x = ['name', 'asc'];
} else {
$sort = mb_strtolower($sort);
$sort_x = explode('|', $sort);
if (@$sort_x[1] != 'desc') {
$sort_x[1] = 'asc';
}
}
$add_to_list_function = '__get_files_list_add_to_list';
/**
* Sort by
*/
if (@$sort_x[0] == 'date') {
$add_to_list_function = '__get_files_list_add_to_list_date';
} elseif (@$sort_x[0] == 'size') {
$add_to_list_function = '__get_files_list_add_to_list_size';
}
$list = [];
__get_files_list($dir, $mask, $mode, $prefix_path, $subfolders, $sort, $exclusion, $system_files, $apply, $limit, $add_to_list_function, $list);
if ($list && @$sort_x) {
switch ($sort_x[0]) {
case 'date':
case 'size':
if ($sort_x[1] == 'desc') {
krsort($list);
} else {
ksort($list);
}
break;
case 'name':
natcasesort($list);
if ($sort_x[1] == 'desc') {
$list = array_reverse($list);
}
break;
}
}
return array_values($list);
}
/**
* Function for internal use by get_files_list()
*
* @param string $dir
* @param bool|string $mask
* @param string $mode
* @param bool|string $prefix_path
* @param bool $subfolders
* @param bool $sort
* @param bool|string $exclusion
* @param bool $system_files
* @param callable $apply
* @param int|null $limit
* @param string $add_to_list_function
* @param string[] $list
*/
function __get_files_list ($dir, $mask, $mode, $prefix_path, $subfolders, $sort, $exclusion, $system_files, $apply, &$limit, $add_to_list_function, &$list) {
if (!is_dir($dir) || ($exclusion !== false && file_exists("$dir/$exclusion"))) {
return;
}
$dir_handle = opendir($dir);
if ($dir_handle === false) {
return;
}
while ($limit >= 0 && ($file = readdir($dir_handle)) !== false) {
$file_path = "$dir/$file";
$is_dir = is_dir($file_path);
if (
$file == '.' ||
$file == '..' ||
(
!$system_files &&
(
$file == '.htaccess' ||
$file == '.htpasswd' ||
$file == '.gitignore'
)
) ||
(
$mask &&
!preg_match($mask, $file) &&
(
!$subfolders || !$is_dir
)
)
) {
continue;
}
if (
$mode == 'fd' ||
(
!$is_dir && $mode == 'f'
) ||
(
$is_dir && $mode == 'd'
)
) {
--$limit;
$item = $file;
if ($prefix_path) {
$item = $prefix_path === true ? $file_path : ($prefix_path ? "$prefix_path/$file" : $file);
}
if (!$apply) {
$add_to_list_function($list, $item, $file_path);
}
}
if ($limit >= 0 && $subfolders && $is_dir) {
__get_files_list(
$file_path,
$mask,
$mode,
$prefix_path === true || $prefix_path === false ? $prefix_path : ($prefix_path ? "$prefix_path/$file" : $file),
$subfolders,
$sort,
$exclusion,
$system_files,
$apply,
$limit,
$add_to_list_function,
$list
);
}
/**
* Apply custom operation to found item without waiting for result returning
*/
if (isset($item) && $apply) {
$apply($item);
}
}
closedir($dir_handle);
}
/**
* Function for internal use by get_files_list()
*
* @param string[] $list
* @param string $item
* @param string $location
*/
function __get_files_list_add_to_list_date (&$list, $item, $location) {
/**
* File access or modification time, access time may be unavailable on some configurations
*/
$list[fileatime($location) ?: filemtime($location)] = $item;
}
/**
* Function for internal use by get_files_list()
*
* @param string[] $list
* @param string $item
* @param string $location
*/
function __get_files_list_add_to_list_size (&$list, $item, $location) {
$list[filesize($location)] = $item;
}
/**
* Function for internal use by get_files_list()
*
* @param string[] $list
* @param string $item
*/
function __get_files_list_add_to_list (&$list, $item) {
$list[] = $item;
}
/**
* Get file extension from filename
*
* @param string $filename
*
* @return string
*/
function file_extension ($filename) {
return mb_substr(mb_strrchr($filename, '.'), 1);
}
/**
* Function takes base filename and possible file extensions, returns filename of first file found in filesystem
*
* @param string $base_filename Base filename without `.` at the end
* @param string[] $possible_extensions
*
* @return false|string
*/
function file_exists_with_extension ($base_filename, $possible_extensions) {
foreach ($possible_extensions as $extension) {
$file = "$base_filename.$extension";
if (file_exists($file)) {
return $file;
}
}
return false;
}
/**
* Recursively remove directory
*
* @param string $dirname Path to directory
*
* @return bool
*/
function rmdir_recursive ($dirname) {
if (!is_dir($dirname)) {
return true;
}
get_files_list(
$dirname,
false,
'fd',
true,
true,
false,
false,
true,
function ($item) {
if (is_dir($item)) {
@rmdir($item);
} else {
@unlink($item);
}
}
);
return @rmdir($dirname);
}
/**
* Protecting against null byte injection
*
* @param string|string[] $in
*
* @return string|string[]
*/
function null_byte_filter ($in) {
if (is_array($in)) {
foreach ($in as &$val) {
$val = null_byte_filter($val);
}
} else {
$in = str_replace(chr(0), '', $in);
}
return $in;
}
/**
* Prepare text to be used as value for html attribute value
*
* @param string|string[] $text
*
* @return string|string[]
*/
function prepare_attr_value ($text) {
if (is_array($text)) {
foreach ($text as &$val) {
$val = prepare_attr_value($val);
}
return $text;
}
return strtr(
$text,
[
'&' => '&',
'"' => '"',
'\'' => ''',
'<' => '<',
'>' => '>'
]
);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $str
*
* @return string|string[]
*/
function _stripslashes ($str) {
if (is_array($str)) {
return array_map('stripslashes', $str);
}
return stripslashes($str);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $str
*
* @return string|string[]
*/
function _addslashes ($str) {
if (is_array($str)) {
return array_map('addslashes', $str);
}
return addslashes($str);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $str
* @param string $charlist
*
* @return string|string[]
*/
function _trim ($str, $charlist = " \t\n\r\0\x0B") {
if (is_array($str)) {
foreach ($str as &$s) {
$s = trim($s, $charlist);
}
return $str;
}
return trim($str, $charlist);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $str
* @param string $charlist
*
* @return string|string[]
*/
function _ltrim ($str, $charlist = " \t\n\r\0\x0B") {
if (is_array($str)) {
foreach ($str as &$s) {
$s = ltrim($s);
}
return $str;
}
return ltrim($str, $charlist);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $str
* @param string $charlist
*
* @return string|string[]
*/
function _rtrim ($str, $charlist = " \t\n\r\0\x0B") {
if (is_array($str)) {
foreach ($str as &$s) {
$s = rtrim($s, $charlist);
}
return $str;
}
return rtrim($str, $charlist);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
* @param int $start
* @param int $length
*
* @return string|string[]
*/
function _substr ($string, $start, $length = null) {
if (is_array($string)) {
foreach ($string as &$s) {
$s = _substr($s, $start, $length);
}
return $string;
}
if ($length) {
return substr($string, $start, $length);
} else {
return substr($string, $start);
}
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
* @param int $start
* @param int $length
*
* @return string|string[]
*/
function _mb_substr ($string, $start, $length = null) {
if (is_array($string)) {
foreach ($string as &$s) {
$s = _mb_substr($s, $start, $length);
}
return $string;
}
if ($length) {
return mb_substr($string, $start, $length);
} else {
return mb_substr($string, $start);
}
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
*
* @return string|string[]
*/
function _strtolower ($string) {
if (is_array($string)) {
return array_map('strtolower', $string);
}
return strtolower($string);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
*
* @return string|string[]
*/
function _strtoupper ($string) {
if (is_array($string)) {
return array_map('strtoupper', $string);
}
return strtoupper($string);
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
*
* @return string|string[]
*/
function _mb_strtolower ($string) {
if (is_array($string)) {
foreach ($string as &$s) {
$s = mb_strtolower($s, 'utf-8');
}
return $string;
}
return mb_strtolower($string, 'utf-8');
}
/**
* Like system function, but accept arrays of strings
*
* @param string|string[] $string
*
* @return string|string[]
*/
function _mb_strtoupper ($string) {
if (is_array($string)) {
foreach ($string as &$s) {
$s = mb_strtoupper($s, 'utf-8');
}
return $string;
}
return mb_strtoupper($string, 'utf-8');
}
/**
* Works similar to the system function, but adds JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES options
*
* @param mixed $value
*
* @return bool|string
*/
function _json_encode ($value) {
return @json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/**
* Works similar to the system function, but always returns array, not object
*
* @param string $in
* @param int $depth
*
* @return bool|mixed
*/
function _json_decode ($in, $depth = 512) {
return @json_decode($in, true, $depth);
}
/**
* Works similar to _json_decode(), but deletes specific comments
*
* @see _json_decode()
*
* @param string $in
* @param int $depth
*
* @return bool|mixed
*/
function _json_decode_nocomments ($in, $depth = 512) {
$in = preg_replace('#^\s*//[^\n]*\n#ims', '', $in);
return @json_decode($in, true, $depth);
}
/**
* file_put_contents(_json_encode())
*
* @param string $filename Name of the file to read.
* @param mixed $data The data to write
* @param int $flags
* @param resource $context
*
* @return mixed
*/
function file_put_json ($filename, $data, $flags = null, &$context = null) {
return file_put_contents(
$filename,
_json_encode($data),
$flags,
$context
);
}
/**
* _json_decode(file_get_contents())
*
* @param string $filename Name of the file to read.
*
* @return mixed
*/
function file_get_json ($filename) {
return _json_decode(
file_get_contents($filename)
);
}
/**
* _json_decode_nocomments(file_get_contents())
*
* @param string $filename Name of the file to read.
*
* @return mixed
*/
function file_get_json_nocomments ($filename) {
return _json_decode_nocomments(
file_get_contents($filename)
);
}
/**
* Similar to system function, but make simple check, whether regexp is correct (actually checks if first symbol is / or #)
*
* @param string $pattern
* @param string $subject
* @param null|mixed $matches
* @param int $flags
* @param int $offset
*
* @return bool|int
*/
function _preg_match ($pattern, $subject, &$matches = null, $flags = 0, $offset = 0) {
if (strpos($pattern, '/') === false && strpos($pattern, '#') === false) {
return false;
}
$pattern = trim($pattern);
return preg_match($pattern, $subject, $matches, $flags, $offset);
}
/**
* Similar to system function, but make simple check, whether regexp is correct (actually checks if first symbol is / or #)
*
* @param string $pattern
* @param string $replacement
* @param string $subject
* @param int $limit
* @param null $count
*
* @return bool|mixed
*/
function _preg_replace ($pattern, $replacement, $subject, $limit = -1, &$count = null) {
if (strpos($pattern, '/') === false && strpos($pattern, '#') === false) {
return false;
}
$pattern = trim($pattern);
return preg_replace($pattern, $replacement, $subject, $limit, $count);
}
/**
* XSS Attack Protection. Returns secure string using several types of filters
*
* @param string|string[] $in HTML code
* @param bool|string $html <b>text</b> - text at output (default)<br>
* <b>true</b> - processed HTML at output<br>
* <b>false</b> - HTML tags will be deleted
* @param bool $iframe Whether to allow iframes without inner content (for example, video from youtube)<br>
* Works only if <i>$html === true</i>
* @return string|string[]
*/
function xap ($in, $html = 'text', $iframe = false) {
if (is_array($in)) {
foreach ($in as &$item) {
$item = xap($item, $html, $iframe);
}
return $in;
/**
* Make safe HTML
*/
} elseif ($html === true) {
$in = preg_replace(
'/
<[^a-z=>]*(link|script|object|applet|embed|[a-z0-9]+-[a-z0-9]+)[^>]*>? # Open tag
(
.* # Some content
<\/[^>]*\\1[^>]*> # Close tag (with reference for tag name to open tag)
)? # Section is optional
/xims',
'',
$in
);
/**
* Remove iframes (regular expression the same as previous)
*/
if (!$iframe) {
$in = preg_replace(
'/
<[^a-z=>]*iframe[^>]*>? # Open tag
(
.* # Some content
<\/[^>]*iframe[^>]*> # Close tag
)? # Section is optional
/xims',
'',
$in
);
/**
* Allow iframes without inner content (for example, video from youtube)
*/
} else {
$in = preg_replace(
'/
(<[^a-z=>]*iframe[^>]*>\s*) # Open tag
[^<\s]+ # Search if there something that is not space or < character
(<\/[^>]*iframe[^>]*>)? # Optional close tag
/xims',
'',
$in
);
$in = preg_replace_callback(
'/
<[^\/a-z=>]*iframe[^>]*>
/xims',
function ($matches) {
$result = preg_replace('/sandbox\s*=\s*([\'"])?[^\\1>]*\\1?/ims', '', $matches[0]);
$result = str_replace(
'>',
' sandbox="allow-same-origin allow-forms allow-popups allow-scripts">',
$result
);
return $result;
},
$in
);
}
$in = preg_replace(
'/(script|data|vbscript):/i',
'\\1:',
$in
);
$in = preg_replace(
'/(expression[\s]*)\(/i',
'\\1(',
$in
);
$in = preg_replace(
'/<[^>]*\s(on[a-z]+|dynsrc|lowsrc|formaction|is)=[^>]*>?/ims',
'',
$in
);
$in = preg_replace(
'/(href[\s\t\r\n]*=[\s\t\r\n]*["\'])((?:http|https|ftp)\:\/\/.*?["\'])/ims',
'\\1redirect/\\2',
$in
);
return $in;
} elseif ($html === false) {
return strip_tags($in);
} else {
return htmlspecialchars($in, ENT_NOQUOTES | ENT_HTML5 | ENT_DISALLOWED | ENT_SUBSTITUTE | ENT_HTML5);
}
}
/**
* Function for converting of IPv4 and IPv6 into hex values to store in db
*
* @link http://www.php.net/manual/ru/function.ip2long.php#82013
*
* @param string $ip
*
* @return bool|string
*/
function ip2hex ($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
$isIPv4 = true;
} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
$isIPv4 = false;
} else {
return false;
}
/**
* IPv4 format
*/
if($isIPv4) {
$parts = explode('.', $ip);
foreach ($parts as &$part) {
$part = str_pad(dechex($part), 2, '0', STR_PAD_LEFT);
}
unset($part);
$ip = "::$parts[0]$parts[1]:$parts[2]$parts[3]";
$hex = implode('', $parts);
/**
* IPv6 format
*/
} else {
$parts = explode(':', $ip);
$last_part = count($parts) - 1;
/**
* If mixed IPv6/IPv4, convert ending to IPv6
*/
if(filter_var($parts[$last_part], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
$parts[$last_part] = explode('.', $parts[$last_part]);
foreach ($parts[$last_part] as &$part) {
$part = str_pad(dechex($part), 2, '0', STR_PAD_LEFT);
}
unset($part);
$parts[] = $parts[$last_part][2].$parts[$last_part][3];
$parts[$last_part] = $parts[$last_part][0].$parts[$last_part][1];
}
$numMissing = 8 - count($parts);
$expandedParts = [];
$expansionDone = false;
foreach($parts as $part) {
if(!$expansionDone && $part == '') {
for($i = 0; $i <= $numMissing; ++$i) {
$expandedParts[] = '0000';
}
$expansionDone = true;
} else {
$expandedParts[] = $part;
}
}
foreach($expandedParts as &$part) {
$part = str_pad($part, 4, '0', STR_PAD_LEFT);
}
$ip = implode(':', $expandedParts);
$hex = implode('', $expandedParts);
}
/**
* Check final IP
*/
if(filter_var($ip, FILTER_VALIDATE_IP) === false) {
return false;
}
return strtolower(str_pad($hex, 32, '0', STR_PAD_LEFT));
}
/**
* Returns IP for given hex representation, function reverse to ip2hex()
*
* @param string $hex
* @param int $mode 6 - result IP will be in form of Ipv6<br>
* 4 - if possible, result will be in form of Ipv4, otherwise in form of IPv6<br>
* 10 - result will be array(IPv6, IPv4)
*
* @return array|bool|string
*/
function hex2ip ($hex, $mode = 6) {
if (!$hex || strlen($hex) != 32) {
return false;
}
$IPv4_range = false;
if (preg_match('/^0{24}[0-9a-f]{8}$/', $hex)) {
$IPv4_range = true;
}
if ($IPv4_range) {
$hex = substr($hex, 24, 8);
switch ($mode) {
case 4:
return hexdec(substr($hex, 0, 2)).'.'.
hexdec(substr($hex, 2, 2)).'.'.
hexdec(substr($hex, 4, 2)).'.'.
hexdec(substr($hex, 6, 2));
case 10:
$result = [];
/**
* IPv6
*/
$result[] = '0000:0000:0000:0000:0000:0000:'.substr($hex, 0, 4).':'.substr($hex, 4, 4);
/**
* IPv4
*/
$result[] = hexdec(substr($hex, 0, 2)).'.'.
hexdec(substr($hex, 2, 2)).'.'.
hexdec(substr($hex, 4, 2)).'.'.
hexdec(substr($hex, 6, 2));
return $result;
default:
return '0000:0000:0000:0000:0000:0000:'.substr($hex, 0, 4).':'.substr($hex, 4, 4);
}
} else {
$result = substr($hex, 0, 4).':'.
substr($hex, 4, 4).':'.
substr($hex, 8, 4).':'.
substr($hex, 12, 4).':'.
substr($hex, 16, 4).':'.
substr($hex, 20, 4).':'.
substr($hex, 24, 4).':'.
substr($hex, 28, 4);
if ($mode == 10) {
return [$result, false];
} else {
return $result;
}
}
}
/**
* Check password strength
*
* @param string $password
* @param int $min_length
*
* @return int In range [0..7]<br><br>
* <b>0</b> - short password<br>
* <b>1</b> - numbers<br>
* <b>2</b> - numbers + letters<br>
* <b>3</b> - numbers + letters in different registers<br>
* <b>4</b> - numbers + letters in different registers + special symbol on usual keyboard +=/^ and others<br>
* <b>5</b> - numbers + letters in different registers + special symbols (more than one)<br>
* <b>6</b> - as 5, but + special symbol, which can't be found on usual keyboard or non-latin letter<br>
* <b>7</b> - as 5, but + special symbols, which can't be found on usual keyboard or non-latin letter (more than one symbol)<br>
*/
function password_check ($password, $min_length = 4) {
$password = preg_replace('/\s+/', ' ', $password);
$strength = 0;
if (strlen($password) >= $min_length) {
if (preg_match_all('/[~!@#\$%\^&\*\(\)\-_=+\|\/;:,\.\?\[\]\{\}]/', $password, $match)) {
$strength = 4;
if (count($match[0]) > 1) {
++$strength;
}
} else {
if (preg_match('/[A-Z]+/', $password)) {
++$strength;
}
if (preg_match('/[a-z]+/', $password)) {
++$strength;
}
if (preg_match('/[0-9]+/', $password)) {
++$strength;
}
}
if (preg_match_all('/[^0-9a-z~!@#\$%\^&\*\(\)\-_=+\|\/;:,\.\?\[\]\{\}]/i', $password, $match)) {
++$strength;
if (count($match[0]) > 1) {
++$strength;
}
}
}
return $strength;
}
/**
* Generates passwords till 5th level of strength, 6-7 - only for humans:)
*
* @param int $length
* @param int $strength In range [1..5], but it must be smaller, than $length<br><br>
* <b>1</b> - numbers<br>
* <b>2</b> - numbers + letters<br>
* <b>3</b> - numbers + letters in different registers<br>
* <b>4</b> - numbers + letters in different registers + special symbol<br>
* <b>5</b> - numbers + letters in different registers + special symbols (more than one)
*
* @return string
*/
function password_generate ($length = 10, $strength = 5) {
static $special = [