forked from watn3y/fritzbox-tools-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfb_tools.php
5275 lines (5264 loc) · 268 KB
/
fb_tools.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
#!/usr/bin/php
<?php # (charset=iso-8859-1 / tabs=8 / lines=lf / lang=de)
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */
if($ver = "fb_tools 0.38 (c) GPL 01.04.2023 by Michael Engelke <https://mengelke.de/.dg>") {
if(!(isset($cfg) and is_array($cfg))) // Testen ob $cfg existiert und ein array ist
$cfg = array(); // Config-Variable anlegen
foreach(array( // Vorkonfiguration einzeln durchgehen
'sock' => 'auto', // Socket: http, https, ssl, tls
'host' => 'fritz.box', // Fritz!Box-Addresse
'pass' => 'password', // Fritz!Box Kennwort
'uipw' => false, // Fritz!Box Anmeldekennwort (F!OS 4/5) oder ab F!OS 6: 2FA
'user' => false, // Fritz!Box Username (Optional)
'totp' => false, // Zweite-Faktor-Authentifizierung (2FA)
'port' => 80, // Fritz!Box HTTP-Port (Normalerweise immer 80)
'fiwa' => 100, // Fritz!Box Firmware (Nur Intern)
'livs' => 0, // Login-Version (0 -> Auto, 1 -> MD5, 2 => PBKDF2)
'upnp' => 49000, // Fritz!Box UPnP-Port (Normalerweise immer 49000)
'jsdp' => 512, // Maximale Verschachtelung beim parsen von JSON-Daten
'sbuf' => 4096, // TCP/IP Socket-Buffergröße oder file-Buffer
'tout' => 30, // TCP/IP Socket-Timeout
'pcre' => 64*1024*1024, // pcre.backtrack_limit (RegEx)
'meli' => 128*1024*1024, // Memory Limit
'upda' => 60*60*24*100, // Auto-Update-Check Periode (Kein Update-Check: 0)
'wrap' => 'auto', // Manueller Wortumbruch (Kein Umbruch: 0)
'char' => 'auto', // Zeichenkodierung der Console (auto/ansi/oem/utf8)
'dbfn' => 'debug#.txt', // Template für Debug-Dateien
'time' => 'Europe/Berlin', // Zeitzone festlegen
'slct' => 'de_DE', // Locales Datumsformat nach Land festlegen
'fesc' => '|<>?*+"/\\:', // Illegale Dateizeichen
'frep' => '_', // Ersetzungszeichen für Illegale Dateizeichen
'fbtg' => 'fbtp_*.php', // Plugin Glob-Pattern
'fbtm' => 'fbtp_([\w-]+)\.php',// Plugin Preg_Match-Pattern
'fbtp' => 'plugins', // Plugin-Pfad
'libs' => 'libs', // PHP-Bibliotheken
'argn' => 'https?:|\w:|[\da-f]{2}:',// Args-Filter
'help' => false, // Hilfe ausgeben
'dbug' => false, // Debuginfos ausgeben
'oput' => false, // Ausgaben speichern
'zlib' => array('mode' => -1), // ZLib-Funktionen (mode: packlevel)
'drag' => array('*'=> 'i h *'),// Drag'n'Drop-Modus
'error' => array(), // Fehler Pool Defininieren
'proxy' => false, // HTTP-Proxy ohne Authentifizierung (proxy.tld:port)
'touch' => ".touch", // Workaround, wenn fb_Tools nicht schreiben kann/darf
'usrcfg'=> 'fb_config.php', // Name der Benutzerkonfiguration
'gz' => 9, // ZIP Deflate Pack Level
) as $key => $var)
if(!isset($cfg[$key])) // Existiert die Variable schon
$cfg[$key] = $var; // Wenn nicht - dann anlegen
}
if(!function_exists('array_combine')) { // http://php.net/array_combine
function array_combine($key,$value,$array=array()) {
if(count($key = array_values($key)) == count($value = array_values($value)))
foreach($value as $k => $v)
$array[$key[$k]] = $v;
return $array ? $array : false;
}
}
if(!function_exists('gzdecode')) { // http://php.net/gzdecode (Workaround)
function gzdecode($data,$len=0,$out=false) {
global $cfg;
$out = '';
if(preg_match('/^\x1f\x8b\x08([\x00-\x1f])[\x00-\xff]{4}\x02[\x00-\xff]([\x00-\xff]+)([\x00-\xff]{4})([\x00-\xff]{4})$/s',$data,$gz)) {
$flag = ord($gz[1]); // Flags lesen
$tmp = $gz[2];
while($flag >>= 1) // Extra-Header überspringen
$tmp = substr($gz[2],strpos($gzip[2],"\0")+1);
$tmp = gzinflate($tmp); // Deflate-Daten entpacken
if(strlen($tmp) == hexdec(bin2hex(strrev($gz[4]))) and hash('crc32b',$tmp,1) == strrev($gz[3])) // Alles Prüfen (Länge & CRC32)
if($len)
$out = substr($data,0,$len);
}
if(!$out and $tmp = tempnam(null,'gz') and $fp = fopen($tmp,'w')) { // Gepackte Daten speichern
fwrite($fp,$data);
fclose($fp);
if($fp = $cfg['zlib']['open']($tmp,'rb')) { // Daten entpackt lesen
while(!$cfg['zlib']['eof']($fp))
$out .= $cfg['zlib']['read']($fp,$cfg['sbuf']);
$cfg['zlib']['close']($fp);
if($len)
$out = substr($out,0,$len);
}
@unlink($tmp); // Überreste löschen
}
return $out;
}
}
if(!function_exists('hash')) { // http://php.net/hash (Workaround für crc32b, md5, sha1 und optional sha256)
function hash($algo,$data,$raw=false) {
return ($algo == 'sha256' and function_exists('mhash') and $a = mhash(MHASH_SHA256,$data)) ? ($raw ? $a : bin2hex($a))
: ((preg_match('/^(md5|sha\d+)$/',$algo) and function_exists($algo) and $a = $algo($data) or $algo == 'crc32b' and $a = sprintf('%08x',crc32($data))) ? ($raw ? pack("H*",$a) : $a) : false);
}
}
if(!function_exists('strftime')) { // http://php.net/strftime
function strfime($data,$time=false,$last=0) {
if(!$time)
$time = time();
if(preg_match_all('/(.)(.)/',"AlBFGoHHIhMiPaSsVWYYZTaDbMddejhMkGlgmmpAsUuNwwyyzO",$m))
$c = array_combine($m[1],$m[2]) + array('D' => 'm/d/y', 'x' => 'm/d/y', 'F' => 'Y-m-d',
'R' => 'H:i', 'T' => 'H:i:s', 'X' => 'H:i:s', 'r' => 'h:i:s A', 'c' => 'D M j H:i:s Y');
while(preg_match('/%(-?)(\w|%)/',substr($data,$last),$m,PREG_OFFSET_CAPTURE)) {
$new = isset($c[$a = $m[2][0]]) ? date($c[$a],$time) : (($a == 'j') ? substr("00".(date('z',$time) + 1),-3)
: (($a == 'C') ? floor(date('Y',$time) / 100) : (($a == 'g') ? substr(date('o',$time),-2) : (($a == 'U')
? substr("0".floor((date('z',$time) + date('w',strtotime(date('Y',$time)."-01-01"))) / 7),-2) : (($a == 'W')
? substr("0".floor((date('z',$time) + date('N',strtotime(date('Y',$time)."-01-01")) - 1) / 7),-2)
: preg_replace('/^%\w$/','',strtr($m[0][0],array("%n" => "\n", "%t" => "\t", "%-n" => "\n", "%-t" => "\t", "%%" => "%"))))))));
$data = substr_replace($data,$m[1][0] ? preg_replace('/^([+-])[0\s]?(\d*)$/','$1$2',$new) : $new,$last + $m[0][1],strlen($m[0][0]));
$last += strlen($m[0][0]) + $m[0][1];
}
return $data;
}
}
function utf8($str,$mode=0) { // UTF-8 Tool mode: Bit0 -> 0:decode 1:encode
if(is_array($str) and preg_array('/[deuhx]|u[0-3]/',$str,5)) {
if(isset($str['u0'])) { // Entwertete Zeichen in UTF8 umwandeln
if(($a = $str['u0']) != "" or isset($str['u3']) and ($a = $str['u3']) != "" or isset($str['x']) and ($a = $str['x']) != "") // hex -> Int
$a = hexdec($a);
elseif(isset($str['u1']) and isset($str['u2']) and $a = $str['u1'] and $b = $str['u2']) // hex 20 Bit -> Int
$a = (hexdec($a) & 1023) * 1024 + (hexdec($b) & 1023) + 65536;
elseif(isset($str['h']) and $a = ifset($str['h'])) // Dec -> Int
$a = intval($a);
else // Fehler
$a = false;
}
else
$a = $str[0];
if(isset($str['e']) or is_int($a)) { // Ansi -> UTF8
// if(function_exists('utf8_encode') and !is_int($a)) return utf8_encode($a);
if(($a = is_int($a) ? $a : ord($a)) < 128)
return chr($a);
$b = "";
$c = 6;
while($a >= 1 << $c and --$c) {
$b = chr($a & 63 | 128).$b;
$a >>= 6;
}
return chr((1 << 7 - $c) -1 << ++$c | $a).$b;
}
elseif(isset($str['d'])) { // UTF8 -> Ansi
// if(function_exists('utf8_decode')) return utf8_decode($a);
for($b = ord($a[0]) % (1 << 7 - strlen($a)), $c = 1; $c < strlen($a); $c++)
$b = $b * 64 + (ord($a[$c]) & 63);
return ($b < 256) ? chr($b) : "\\u".(($b < 65536) ? str_pad(dechex($b),4,0,STR_PAD_LEFT)
: str_pad(dechex(($b - 65536) >> 10 | 55296),4,0,STR_PAD_LEFT)."\\u".str_pad(dechex(($b - 65536) & 1023 | 56320),4,0,STR_PAD_LEFT));
}
return $a;
}
elseif(is_array($str)) { // Array -> utf8[mode]
foreach($str as $key => $var)
if(is_string($var) or is_array($var))
$str[$key] = call_user_func(__FUNCTION__,$var,$mode);
}
else {
$p = "[\x80-\xbf]";
$p = "[\xc0-\xdf]$p|[\xe0-\xef]$p{2}|[\xf0-\xf7]$p{3}|[\xf8-\xfb]$p{4}|[\xfc-\xfd]$p{5}|\xfe$p{6}";
$p = "/".(($mode & 1) ? "(?P<u>$p)|(?P<e>[\x80-\xff])".(($mode & 2)
? '|\\\\(?:u\{(?P<u0>[\da-f]+)\}|(?:u(?P<u1>d[89ab][\da-f]{2})\\\\u(?P<u2>d[cdef][\da-f]{2}))|u(?P<u3>[\da-f]{4}))|(?:&\#(?:(?P<h>\d+)|x(?P<x>[\da-f]+));)'
: '') : "(?P<d>$p)")."/";
if((float)phpversion() > 5.2)
return preg_replace_callback($p,__FUNCTION__,$str);
elseif(preg_match_all($p,$str,$match,PREG_OFFSET_CAPTURE)) { // Workaround PHP 4.3 - 5.2
for($a=count($match[0])-1; $a >= 0; $a--) {
$var = array($match[0][$a][0]);
$var[(isset($match['e']) and $match['e'][$a][1] > -1) ? 'e' : ((isset($match['d']) and $match['d'][$a][1] > -1) ? 'd' : 'u')] = $var[0];
$str = substr_replace($str,utf8($var),$match[0][$a][1],strlen($match[0][$a][0]));
}
}
}
return $str;
}
function file_contents($file,$data=false,$mode=false) { // (Gepackte) Datei lesen/schreiben|mode: Bit1 -> Lock, Bit3 -> Append
global $cfg;
if(is_string($data)) { // Datei schreiben
if($file == ':') // Bei nur ":" nichts schreiben
return true;
if(strpos($file,'%') !== false) // strftime auflösen
$file = @strftime($file);
if(is_bool($mode) and !$mode)
if(preg_match('/\.t?gz$/i',$file) and $fp = $cfg['zlib']['open']($file,'w'.$cfg['zlib']['mode'])) {// Write GZip
dbug("Schreibe GZip-File: $file",9);
$data = $cfg['zlib']['write']($fp,$data);
$cfg['zlib']['close']($fp);
return $data;
}
elseif(preg_match('/\.t?bz(ip)?2?$/i',$file) and ifset($cfg['bzip']) and $fp = bzopen($file,'w')) { // Write BZip2
dbug("Schreibe BZip2-File: $file",9);
$data = bzwrite($fp,$data);
bzclose($fp);
return $data;
}
elseif(preg_match('/\.zip$/i',$file) and !preg_match('/^PK\x03\x04/',$data))
$data = data2zip(array(preg_replace('/.*?([^\/]*)\.zip$/','$1',$file) => $data));
$file = preg_replace('/\.(t?gz|t?bz(ip)?2?)$/i','',$file);// Pack-Extension löschen
if(function_exists('file_put_contents'))
return file_put_contents($file,$data,$mode); // Ungepackt schreiben
else { // file_put_contents ($mode ist nicht vollständig implemmentiert)
if($fp = fopen($file,($mode & 1<<3) ? 'a' : 'w')) { // FILE_APPEND -> 8
if(is_array($data))
$data = implode('',$data);
if($mode & 1<<1) { // LOCK_EX -> 2
if(flock($fp,2)) { // flock LOCK_EX
fputs($fp,$data);
flock($fp,3); // flock LOCK_UN
}
else {
fclose($fp);
return null;
}
}
else
fputs($fp,$data);
fclose($fp);
$fp = strlen($data);
}
return $fp;
}
}
elseif(!$data and !$mode and !preg_match('/\.t?gz$/i',$file)) // Datei vollständig lesen (data:0)
return file_get_contents($file);
elseif(is_int($data) and (float)phpversion() >= 5.1) { // Datei ab Offset lesen (data:offset, mode:length) & PHP 5.1+
$data = array($file,false,null,filesize($file) + (($data < 0) ? max($data,-filesize($file)) : min($data,filesize($file))));
if($mode)
$data[] = $mode;
return call_user_func_array('file_get_contents',$data);
}
elseif(is_int($data) and $fp = fopen($file,'r')) { // Datei ab Offset lesen (data:offset, mode:length)
dbug("Lese File: $file ($data/$mode)",9);
fseek($fp,$data,($data < 0) ? SEEK_END : SEEK_SET);
$data = "";
if($mode)
$data = fread($fp,$mode);
else
while(!feof($fp))
$data .= fread($fp,$cfg['sbuf']);
fclose($fp);
return $data;
}
elseif(preg_match('/\.t?bz(ip)?2?$/i',$file) and ifset($cfg['bzip']) and $fp = bzopen($file,'r')) { // BZip2 lesen
dbug("Lese BZip2-File: $file",9);
$data = "";
while(($var = bzread($fp,$cfg['sbuf'])) !== false)
$data .= $var;
bzclose($fp);
return $data;
}
elseif($fp = $cfg['zlib']['open']($file,'r')) { // (gz)Datei entpackt lesen
dbug("Lese gzFile: $file",9);
$data = "";
while(!$cfg['zlib']['eof']($fp))
$data .= $cfg['zlib']['read']($fp,$cfg['sbuf']);
$cfg['zlib']['close']($fp);
return $data;
}
return false;
}
function file_stream($file,$data=false) { // Datei-Stream Zeilenweise Lesen/Schreiben - Optional mit GZip/BZip2
global $cfg,$fsData;
$out = $fs = false;
if(!(isset($fsData) and is_array($fsData))) // Globale Variabel vorhanden?
$fsData = array('bs' => $cfg['sbuf'], 'pt' => 0, 'fs' => array()); // Globale Variable anlegen
if(is_string($file)) { // OPEN (file)
if(strpos($file,'%') !== false) // strftime auflösen
$file = @strftime($file);
$fs = array('file' => $file, 'seek' => 0, 'data' => '', 'mode' => (is_int($data)) ? $data : ($data ? 1 : 0)); // Init
$rw = ($fs['mode'] & 1) ? 'w' : 'r';
$mode = $fs['mode'] & 6;
dbug("file_stream: open ",9,6);
if(($mode == 2 or preg_match('/\.t?gz$/i',$file)) and $fp = $cfg['zlib']['open']($file,$rw.$cfg['zlib']['mode'])) { // GZip
dbug("GZip-File",9,12);
$fs['mode'] |= 2;
$fs['fp'] = $fp;
}
elseif($mode == 4 or preg_match('/\.t?bz(ip)?2?$/i',$file) and ifset($cfg['bzip']) and $fp = bzopen($file,$rw)) { // BZip2
dbug("BZip2-File",9,12);
$fs['mode'] |= 4;
$fs['fp'] = $fp;
}
elseif($fp = fopen(preg_replace('/\.(t?gz|t?bz(ip)?2?)$/i','',$file),$rw)) { // Normal
dbug("File",9,12);
$fs['fp'] = $fp;
}
else {
dbug("Fail",9,12);
$file = $fs = false;
}
if($fs) // Neuen FileStream ablegen
$fsData['fs'][$file = ++$fsData['pt']] = $fs;
$out = $file;
}
elseif($file and is_int($file) and isset($fsData['fs'][$file]) and $fs = $fsData['fs'][$file]) { // Daten lesen / schreiben
$mode = $fs['mode'] & 6; // GZip/BZip2/Std
if(!($fs['mode'] & 1)) { // LESEN
if(is_int($data)) { // Byteweise
if($mode == 2) // GZip
$out = $cfg['zlib']['read']($fs['fp'],$data);
elseif($mode == 4) { // BZip
if(($len = strlen($fs['data'])) < $data)
$fs['data'] .= bzread($fs['fp'],$data-$len);
$out = substr($fs['data'],0,$data+1);
$fs['data'] = substr($fs['data'],strlen($out));
}
elseif(!$mode) // Normal
$out = fread($fs['fp'],$data);
}
elseif($mode == 2) // GZip (Zeilenweise)
$out = $cfg['zlib']['gets']($fs['fp'],$fsData['bs']);
elseif($mode == 4) { // BZip (Zeilenweise)
if(($len = strlen($fs['data'])) < $fsData['bs']) {
$var = bzread($fs['fp'],$fsData['bs'] - $len);
$fs['data'] .= $var;
$fs['seek'] += strlen($var);
}
if(($pos = strpos($fs['data'],"\n")) === false)
$pos = strlen($fs['data']);
$out = substr($fs['data'],0,$pos+1);
$fs['data'] = substr($fs['data'],strlen($out));
}
elseif(!$mode) // Normal (Zeilenweise)
$out = fgets($fs['fp'],$fsData['bs']);
$fs['seek'] += strlen($out);
}
elseif(($fs['mode'] & 1) and $data) { // SCHREIBEN (Byteweise)
if($mode == 2) // GZip
$out = $cfg['zlib']['write']($fs['fp'],$data);
elseif($mode == 4) // BZip
$out = bzwrite($fs['fp'],$data);
elseif(!$mode) // Normal
$out = fwrite($fs['fp'],$data);
$fs['seek'] += $out;
}
if(!$out or $fs['mode'] & 1 and !$data) { // CLOSE
if($mode == 2) // GZip
$cfg['zlib']['close']($fs['fp']);
elseif($mode == 4) // BZip
bzclose($fs['fp']);
elseif(!$mode) // Normal
fclose($fs['fp']);
unset($fsData['fs'][$file]); // Pointer löschen
$file = $fs = false; // Variabeln löschen
}
}
if($file and $fs)
$fsData['fs'][$file] = $fs;
return $out;
}
function listDir($pat,$dirs='',$mode=0,$list=array()) { // Liest ein Verzeichnis aus (Pattern, Verzeichnis(e), Modus) // Bit0 > Pattern, Bit1 > PathPat
if(!($mode & 1<<0)) { // Simple-Pattern // Bit2 > basename, Bit3 > noFile, Bit4 > noDir, Bit5 > Recusiv, Bit6 > Sort
if(!$dirs) { // Kein Verzeichnis angegeben
if(file_exists($pat)) // Pattern existiert
if(is_file($pat)) { // Pattern ist ein File
$dirs = dirname($pat);
$pat = basename($pat);
}
else { // Pattern ist ein Verzeichnis
$dirs = $pat;
$pat = '*';
}
elseif($var = ifset($pat,'/^(.*?)([^\\\\\/]*[*?][^\\\\\/]*)$/')) { // Pattern besteht aus Verzeichnis und Pattern (glob)
$dirs = $var[1];
$pat = $var[2];
}
if(!$dirs)
$dirs = '.';
}
if($pat and !function_exists('fnmatch')) { // Workaround wenn fnmatch() nicht verfügbar ist
$pat = "/^".strtr(preg_quote($pat,'/'),array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'))."$/i";
$mode |= 1<<0;
}
}
foreach(array_unique((array)$dirs) as $dir) { // Alle Verzeichnisse durchgehen
if(file_exists($dir) and $dp = opendir($dir)) {
$dir = preg_replace('/[\\\\\/]$/','',$dir); // Letzten Slash entfernen
while(($file = readdir($dp)) !== false)
if(!preg_match('/^\.\.?$/',$file)) { // Kein Current oder Parent
$fn = (($mode & 1<<1) ? "$dir/" : '').$file; // Bit 1 -> Filename für Pattern
if(!$pat or $mode & 1<<0 and preg_match($pat,$fn) or !($mode & 1<<0) and fnmatch($pat,$fn,FNM_CASEFOLD) // Bit 0 -> Patterncheck
and (!($mode & (1<<3 | 1<<4)) or $mode & 1<<3 and !is_file("$dir/$file") or $mode & 1<<4 and !is_dir("$dir/$file"))) { // Bit3 -> file / Bit4 -> dir
$fn = ($mode & 1<<2) ? $file : (($dir != '.') ? "$dir/" : "").$file.((is_dir("$dir/$file")) ? '/' : '');
if($mode & 1<<2)
$list[realpath("$dir/$file")] = $fn;
else
array_push($list,$fn);
if($mode & 1<<5 and is_dir("$dir/$file") and $array = call_user_func(__FUNCTION__,$pat,"$dir/$file",$mode)) // Bit 5 -> Rekursiv
if($mode & 1<<2) // Bit 2 -> Basename
$list[($mode & 1<<2) ? realpath($file) : $file] = $array; // Assoc
else
$list = array_merge($list,$array); // List
}
}
closedir($dp);
}
}
if(!$mode & 1<<2)
$list = array_unique($list);
if($mode & 1<<6) // Bit 6 -> Sortieren
natcasesort($list);
return $list ? $list : false;
}
function ifset(&$x,$y=false) { // Variabeln prüfen und Optional vergleichen (var,test)
return (isset($x) and ($x or $x != '')) ? ($y ? ((is_string($y) and preg_match('!^(([^\w\s]).*\2[imsuxADU]{0,8})((\d)|(a))?($)!Us',$y,$w) and is_string($x)
and ($w[5] and preg_match_all($w[1],$x,$z) or preg_match($w[1],$x,$z))) ? (($z and $w[4] != "") ? $z[(int)$w[4]] : $z) : (is_array($x)
? ((is_string($y) and $w) ? preg_grep($y,$x) : (is_int($y) ? count($x) == $y : (is_bool($y) ? $x : array_search($y,$x))))
: (((is_callable($y) and $z = call_user_func($y,$x)) ? (is_bool($z) ? $x : $z) : ((!is_bool($x) or is_bool($y)) and $x == $y)))))
: (is_string($x) ? (is_string($y) ? $x : strlen($x)) : ((is_numeric($x) or is_bool($x)) ? $x : (is_array($x) ? count($x) : !$y)))) : false;
}
function preg_array($x,$y,$z=0) { // Durchsucht einen Array mit Regulären Ausdruck (preg,array,mode)
$w = ($z & 1<<1) ? array() : false; // Return All/First // Bit 0: Search 0:value / 1:key 1
foreach($y as $k => $v) // Bit 1: Result 0:first / 1:all 2
if(($z & (1<<4)) and is_array($v) and $u = call_user_func(__FUNCTION__,$x,$v,$z)) // Bit 2: Result 0:value / 1:key 4
if($z & 1<<1) // Result All // Bit 3: Search 0:found / 1:not found 8
$w[$k] = $u; // Bit 4: 0:iterativ / 1:rekusiv 16
else // Result First
return ($z & 1<<2) ? $k : $u; // Return Key/Value
elseif(($z & 1<<3) xor preg_match($x,($z & 1<<0) ? $k : (is_array($v) ? "" : $v))) // (not)Found & Key/Value
if($z & 1<<1) // Result All
$w[$k] = $v;
else // Result First
return ($z & 1<<2) ? $k : $v; // Return Key/Value
return $w;
}
function unBase($data,$base=false,$bits=false) { // unBase2-128 (data-string, base-chars[Default: AVM-Base32], input-bits)
for($base = $base ? $base : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456', $bits = $bits ? $bits : intval(log(strlen($base),2)), $a=$b=$c=0, $out=""; $a < strlen($data); )
if(($e = strpos($base,$data[$a++])) !== false)
for($c = ($c << $bits) + $e, $b += $bits; $b >= 8; $c %= 1 << $b)
$out .= chr($c >> ($b -= 8));
return $out;
}
function getArg($name=false,$preg=false,$arg=null) { // Nächsten Parameter holen (argname, /preg_match/, argname-only & return@false)
global $cfg,$pset; // args,argc,argn,arg,$opts
$tst = $arg; // Parameter retten für TEST-Modus
if(is_string($name) and $name[0] == '-') { // Optionen abfragen
$def = 'opts';
$name = substr($name,1);
}
else // Argumente abfragen
$def = 'args';
if($name) { // Benanntes Argument (name)
if(is_bool($name)) // Ungeprüfte Parameter vorhanden? (name -> true)
$arg = preg_array("/^(".str_replace('\|','|',preg_quote(implode('|',array_keys($cfg['argk'])),'/')).")$/",$cfg['arg'],11);
elseif(isset($cfg[$def][$name]) and is_array($var = $cfg[$def][$name])) { // Benanntes Argument ist ein Array
if(is_string($preg) and strlen($preg) == 1) // Array als CSV zurückgeben? (preg -> .)
$arg = implode($preg,str_replace($preg,$preg.$preg,$var));
elseif(!is_array($preg) and $var = current($cfg[$def][$name]) and ifset($var,$preg)) // Aktuelles Argument aus Array zurückgeben (preg)
$arg = $preg ? $var : current($cfg[$def][$name]);
elseif(is_array($preg)) // Nur Argumente zurückgeben, die auf [preg] passen oder alle
$arg = (isset($preg[0]) and $preg[0]) ? preg_array($preg[0],$cfg[$def][$name],(isset($preg[1])) ? $preg[1] : 2) : $cfg[$def][$name];
}
elseif(isset($cfg[$def][$name])) // Benannter Parameter
$arg = $preg ? ifset($cfg[$def][$name],$preg) : $cfg[$def][$name];
}
elseif(is_null($arg) and is_array($preg) and $cfg['argc']) // Alle restlichen Nummerischen Parameter zurückgeben
for($arg=array(); $name = array_shift($cfg['argc']);)
$arg[] = $cfg['arg'][$name];
if($def == 'opts') // Optionen sofort zurückgeben
return (is_null($arg)) ? false : ((is_array($preg)) ? (array)$arg : $arg); // Vorgabe oder false zurückgeben
elseif($tst === true) // Parameter nur Testweise zurückgeben
return ($arg === true) ? (($var = ifset($cfg['arg'][$name = reset($cfg['argc'])],$preg)) ? ($preg ? $var : $cfg['arg'][$name]) : false) : $arg;
elseif(is_null($arg) or $arg == $tst and $cfg['argc']) { // Nummerierter/Unbenannter Parameter
foreach($cfg['argc'] as $val => $name) // Auf Inhaltprüfen
if(($var = ifset($cfg['arg'][$name],$preg)) != "")
break;
if(ifset($var) != "") { // Wurde ein Nummerierter/Unbenannter Parameter gefunden?
if(!$cfg['argn']) // Übergabe/Abfrage vom alten Parameter-System ermöglichen
$pset++;
unset($cfg['argc'][$val]); // Parameter löschen
$arg = $preg ? $var : $cfg['arg'][$name];
}
}
return (is_null($arg) or !$arg and (is_array($arg) or is_string($arg) and is_bool($arg))) ? false : $cfg['argk'][$name] = ((is_array($preg)) ? (array)$arg : $arg); // Vorgabe oder false zurückgeben
}
function out($str,$mode=0,$lf=PHP_EOL) { // Textconvertierung vor der ausgabe (mode: 0 -> echo / 1 -> noautolf / 2 -> debug)
global $cfg;
$cp = ifset($cfg['char']) ? (array)$cfg['char'] : array('c' => 1);
if(ifset($cp['n'])) // Char:none
return ""; // Keine Ausgabe
if(is_array($str))
$str = print_r($str,true);
if(is_string($str) and $str != "") {
if(!($mode & 1<<1) and preg_match('/\S$/D',$str)) // AutoLF
$str .= $lf;
if($mode & 1<<2) // Unnötige Whitespaces im Debug-Modus löschen
$str = preg_replace('/(?<=\n\n|\r\n\r\n)\s+$/','',$str);
if(isset($cfg['anon']) and is_array($cfg['anon'])) // Möglichkeit die Ausgabe zu anonymisieren
$str = preg_replace(array_keys($cfg['anon']),array_values($cfg['anon']),$str);
if($cfg['oput'] and !($mode & 1<<2)) // Ausgabe speichern
file_contents($cfg['oput'],textTable($str,-1),8);
if(ifset($cp['d']) and preg_match_all('/(.)(.)/',base64_decode(
"thSnFceA/IHpguKD5ITgheWG54fqiOuJ6Irvi+6M7I3EjsWPyZDmkcaS9JP2lPKV+5b5l/+Y1pncmqOc4aDtofOi+qPxpNGlqqa6p7+orKq9q7ysoa2rrruv3+G15rHx9/aw+Lf6sv2g/"
.((substr($cp['d'],-3) == 437) ? "6KbpZ0=" : "/ib2J3Xnq6pwbXCtsC3qbiivaW+48bDx6TP8NDQ0crSy9PI1M3WztfP2KbdzN7T4NTi0uP15NXl/ufe6Nrp2+rZ6/3s3e2v7rTvrfC+87b0p/W496j5ufuz/A==")),$m))
$str = strtr(utf8($str),array_combine($m[1],$m[2])); // DOS
elseif(ifset($cp['m']) and preg_match_all('/(.)(.)/',"ÇüéâäçëîÄÉôöÖÜ×á í¡ó¢ú£¬ª«®»¯ÁµÂ¶¤ÏËÓÍÖÎ×ÓàßáÔâÚéýìÝí´ïð§õ÷ö¸÷°ø¨ù ÿ",$m))
$str = strtr(utf8($str),array_combine($m[1],$m[2])); // cp852
elseif(ifset($cp['u']))
$str = utf8($str,3); // UTF8
elseif(ifset($cp['h']) and preg_match_all('/(.)([\da-z#]+)/','&<lt>gt"quot\'#39äaumlöoumlüuumlßszligÄAumlÖOumlÜUuml',$m))
$str = strtr($str,array_combine($m[1],preg_replace('/.+/','&$0;',$m[2]))); // HTML
elseif((ifset($cp['c']) or ifset($cp['l']) or ifset($cp['r']) or !ifset($cp['a']))
and preg_match_all('/([^ -~]+)([ -~]+)/','¡!£GBP|§\\S"©(c)«<<¬-®(R)º°\'¯^±+-²2³3\'µu¶I·\''
.'.¹1»>>1/41/23/4¿?ÆAEÄAeÖOeÜUeæäaeöoeüueßssÀÁÂÃÅAÇCÈÉÊËEÌÍÎÏIÐDÑNÒÓÔÕØOÙÚÛUÝ¥YÞpàáâãåªaç¢cèéêëeìíîïiñnðòóôõøoùúûuþPýÿy×x÷:',$m)) {
$a = array(); // 7 Bit ASCII
foreach($m[1] as $key => $var)
for($b=0; $b < strlen($var); $b++)
$a[$var[$b]] = $m[2][$key];
$str = strtr(utf8($str),$a);
}
else // Ansi
$str = utf8($str);
$str = textTable($str,-1); // Tabelle im String
if($var = ifset($cp['l'],"") and preg_match_all('/([a-z\d])(.)/i','1I2Z3E4A5S6G7T8B9g0Oa4A4b8B8e3E3g6G6l1L1o0O0q9Q9s5S5t7T7z2Z2'.(is_numeric($var) ? '' : 'c<C(h#H#i!I!x+X+'),$m))
$str = strtr($str,array_combine($m[1],$m[2]));
elseif(ifset($cp['r']))
$str = str_rot13($str);
if($col = (int)$cfg['wrap'] and --$col) { // My WordWrap
# $str = wordwrap($str,$cfg['wrap']-1,$lf,true);
$esc = array(); // Mutibytes Entwerten
$pos = 0;
$p = "[\x80-\xbf]";
while(preg_match("/\x7f|[\xc0-\xdf]$p|[\xe0-\xef]$p{2}|[\xf0-\xf7]$p{3}|[\xf8-\xfb]$p{4}|[\xfc-\xfd]$p{5}|\xfe$p{6}
|\\\\(u\{[\da-f]+\}|ud[89ab][\da-f]{2}\\\\ud[cdef][\da-f]{2}|u[\da-f]{4})|(&\#(\d+|x[\da-f]+);)/x",substr($str,$pos),$m,PREG_OFFSET_CAPTURE)) {
$str = substr_replace($str,"\x7f",$pos + $m[0][1], strlen($m[0][0]));
$esc[] = $m[0][0];
$pos += $m[0][1] + 1;
}
$inp = str_replace("\x0b"," ",$str); // WordWrap vorbereiten
$len = strlen($inp);
$str = "";
$pos = 0;
while(preg_match('/^([ \t]*)(.*?(?:\r?\n|$))/',substr($inp,$pos),$m) and $pos < $len) {
if(($col-($spc = strlen($m[1]))) < 16) {
$spc = 0;
$m[1] = "";
}
$str .= preg_replace(array("/^/","/\x0b/"),array($m[1],"$lf$m[1]"),wordwrap($m[2],$col-$spc,"\x0b",true));
$pos += strlen($m[0]);
}
$m = 0; // Entwertete Zeichen wieder zurückholen
while(($m = strpos($str,"\x7f",$m)) !== false) {
$str = substr_replace($str,$esc[0],$m,1);
$m += strlen(array_shift($esc));
}
}
}
elseif(is_array($str)) // Leeres Array
$str = "";
return ($mode & 1<<0) ? $str : print $str;
}
function dbug($str,$level=0,$mode=4) { // Debug-Daten ausgeben/speichern (mode: 4 -> Debug) # dbug(compact(explode(',','array,key,var')));
global $cfg;
if(floor($cfg['dbug']/(1<<$level))%2) { // Nur Entsprechenden Debug-Level ausgaben
if(is_string($mode)) // Entweder Mode-Angabe oder Dateiname
if(preg_match('/^(\d+),(.+)$/',$mode,$var)) {
$mode = $var[1];
$file = $var[2];
}
else {
$file = $mode;
$mode = 4;
}
else
$file = false;
$time = ($cfg['dbug'] & 1<<2 and !($mode & 1<<3)) ? number_format(array_sum(explode(' ',microtime()))-$cfg['stim'],3,',','.').' ' : '';
if($cfg['dbug'] & 1<<1 and $cfg['dbfn'] and $file) // Debug: Array in separate Datei sichern
if(strpos($file,'#') and is_array($str))
foreach($str as $key => $var) // Debug: Array in mehrere separaten Dateien sichern
file_contents($cfg['dbcd'].str_replace('#',"-".str_replace('#',$key,$file),$cfg['dbfn']),$time.(is_array($var) ? print_r($var,true) : $var),8);
else
file_contents($cfg['dbcd'].str_replace('#',"-$file",$cfg['dbfn']),$time.(is_array($str) ? print_r($str,true) : $str),8); // Alles in EINE Datei Sichern
else {
if(is_string($str)) {
if(preg_match('/^\$(\w+)$/',$str,$var) and isset($GLOBALS[$var[1]])) // GLOBALS Variable ausgeben
$str = "$str => ".(is_array($GLOBALS[$var[1]]) ? print_r($GLOBALS[$var[1]],true) : $GLOBALS[$var[1]]);
elseif(!($mode & 1<<1) and preg_match('/\S$/D',$str))// AutoLF
$str .= "\n";
}
elseif(is_array($str))
$str = print_r($str,true);
if($cfg['dbug'] & 1<<1 and $cfg['dbfn']) { // Debug: Ausgabe/Speichern
file_contents($cfg['dbcd'].str_replace('#','',$cfg['dbfn']),$time.$str,8);
if(!$level) // Nur Level 0 Ausgeben!
out($time.$str,($mode | 4) & 7);
}
else
out($time.$str,($mode | 4) & 7);
}
}
}
function errmsg($msg=0,$name='main') { // Fehlermeldung(en) Sichern
global $cfg;
if(!ifset($cfg['errmute'])) // Fehleraufzeichnung pausieren?
if($msg) { // Fehlermeldung speichern
dbug("Fehler: $msg",9);
$cfg['error'][$name][] = trim($msg);
}
else { // Letzte Fehlermeldung abrufen
dbug("Suche Fehler von Funktion: $name",9);
if($name == "*" and $var = array_keys($cfg['error']))
$name = end($var); // Letzte Fehlermeldung finden
while(isset($cfg['error'][$name]) and is_array($cfg['error'][$name]))// Fehlermeldung vorhanden?
if($val = end($cfg['error'][$name]) and preg_match('/^\w+$/',$val)) // Möglicher Rekusive Fehlermeldung?
$name = $val; // Nächste Fehlermeldung suchen
else {
if($name != 'main')
$cfg['error']['main'][] = $val;
return (substr($val,0,2) != '1:') ? preg_replace('/^\d+:/','',$val) : false;// Nur Fehlermeldung ohne Error-Code ausgeben
}
}
return ($msg and $name == 'main') ? preg_replace('/^\d+:/','',$msg) : false; // Ohne Funktionsname: Fehler ausgeben oder failat
}
function phperr($no,$str,$file,$line) { // PHP-Fehler Debuggen
foreach(preg_split("/\s+/","ERROR WARNING PARSE NOTICE CORE_ERROR CORE_WARNING COMPILE_ERROR COMPILE_WARNING
USER_ERROR USER_WARNING USER_NOTICE STRICT RECOVERABLE_ERROR DEPRECATED USER_DEPRECATED UNKNOWN") as $b => $c)
if($no == 1 << $b)
break;
$a = "$str on line $line";
$b = &$GLOBALS["cfg"]["error"][$c][$file];
// $b["backtrace"][] = debug_backtrace();
if(!isset($a,$b) or array_search($a,$b) === false)
$b[] = $a;
return false;
}
function makedir($dir,$mode=1) { // Erstellt ein Verzeichnis und wechselt dorthin
if(!$dir or ifset($dir,$GLOBALS['cfg']['ptar'])) // Self-Dir und Archive nicht bearbeiten
return true;
$dir = preg_replace('/[\\\\\/]+$/','',$dir); // Abschlussshlash entfernen
if(strpos($dir,'%') !== false) // strftime auflösen (Problematische Zeichen werden umgewandelt)
$dir = @strftime($dir);
if(preg_match('/^(\w:)?(.*)$/',$dir,$var)) // Windows Verzeichnis Prüfen
$dir = $var[1].preg_replace('/[<:*|?">]+/','-',$var[2]);
if(!file_exists($dir)) { // Neues Verzeichniss erstellen
if($mode) // Debug-Meldung unterdrücken
dbug("Erstelle Ordner $dir");
$dirs = preg_split('/[\\\\\/]/',$dir); // Verzeichniskette erstellen
$val = '';
foreach($dirs as $var) {
$val .= $var;
if($val and !file_exists($val))
mkdir($val);
$val .= '/';
}
}
if($mode and is_dir($dir)) { // Aktuelles-Dir setzen
dbug("Wechsle zu Ordner $dir");
chdir($dir);
}
return is_dir($dir) ? $dir : false;
}
function mytouch($mode=false) { // Ermitteln ob fb_Tools wieder nach Updates suchen soll
global $cfg,$script;
$rt = false;
if(is_string($mode)) { // Prüfen, ob eine Datei geschrieben werden kann
$file = $mode;
if(file_exists($file)) { // Test mit einer Datei, die schon da ist
$new = preg_replace('/(?=\.\w+$)|$/','_test',$file);
if(rename($file,$new)) {
if(file_contents($file,$file) and unlink($file))
$rt = true;
rename($new,$file);
}
}
elseif(file_contents($file,$file) and unlink($file)) // Einfacher Schreibtest
$rt = true;
}
else {
$dbg = ($cfg['upda'] < 0) ? 0 : 9; // Debug-Modus festlegen
$time = time(); // Aktuelle Uhrzeit
$data = is_array($mode) ? array2json($mode) : "$time";// Touchinhalt festlegen
$name = "/$cfg[touch]-$cfg[cu]"; // Touch-Dateinamen aus der Konfig holen
$temp = (function_exists('sys_get_temp_dir')) ? sys_get_temp_dir() : (($var = getenv('TEMP')) ? $var : "/tmp");
$array = array_unique(array_merge(array_reverse(array_slice($cfg['fbta'],2)),array_reverse(array_slice($cfg['fbtl'],2)),array_slice($cfg['fbta'],1,1),
array_slice($cfg['fbtl'],1,1),array($script,"$cfg[dir]/$cfg[usrcfg]","$cfg[home]/$cfg[usrcfg]",$cfg['dir'],$cfg['home'],".",$temp)));
if($mode) { // Datum setzen
foreach($array as $file) // Verschiedene Speicherorte probieren
if(file_exists($file = realpath($file)) and (is_file($file) and @touch($file,$time) or is_dir($file) and @file_contents($file .= $name,$data) and file_exists($file)) and filemtime($file) == $time) {
dbug("Touch-Datei: '$file' erfolgreich auf '".date('r',$time)."' gesetzt",$dbg);
$rt = true;
break;
}
}
elseif($cfg['upda'] > 0) { // Datum abfragen
$max = filemtime($script); // Das Script selber
$data = array(); // Leere Daten
array_push($array,$cfg['dir'],$cfg['home']); // Touch-Datei
if($cfg['usrcfg']) // Globale/Lokale Konfig-Datei
array_unshift($array,"$cfg[dir]/$cfg[usrcfg]","$cfg[home]/$cfg[usrcfg]",$cfg['usrcfg'],"$cfg[dir]/.$cfg[usrcfg]","$cfg[home]/.$cfg[usrcfg]",".$cfg[usrcfg]");
if(ifset($cfg['loadcfg'])) // Geladene Konfig-Datei
array_merge((array)explode(',',$cfg['loadcfg']),$array);
array_push($array,"$temp");
$dir = array(); // Pfade auf echte Pfade reduzieren
foreach($array as $file)
if($var = realpath($file))
$dir[$var] = 1;
$array = array_keys($dir);
foreach($array as $var)
if($var and file_exists($var) and (is_dir($var) and $files = glob(realpath($var)."/$cfg[touch]-*") or is_file($var) and $files = array($var)))
foreach($files as $file) {
dbug("Touch-Datei gefunden: $file (Datum: ".date('r',($val = filemtime($file))).")",$dbg);
if($max < $val) { // Neuere Touch-Datei gefunden
$max = $val; // Das neuste Datum sichern
if(substr(basename($file),0,strlen($cfg['touch'])) == $cfg['touch'] and preg_match('/^\{.*\}$/',$val = file_contents($file)))
$data = json2array($val); // Daten aus der Touchdatei holen
}
}
dbug("Letztes Touch-Datum: ".date('r',$max),$dbg);
$rt = $time - $max > $cfg['upda']; // Array zurückgeben oder Vergleichen
}
}
$rt = ($mode === 0 and $data) ? array('chk' => $rt) + $data : $rt; // Rückgabe
return $rt;
}
function otpauth($key,$rep=1,$time=0,$digit=6,$sec=30) {// OTP-Token Generieren für Zweite-Faktor-Authentifizierung
dbug("OATH-TOTP-Secret: $key",9,2);
$otp = array();
if(function_exists('hash_hmac') or cfgdecrypt(0,'hashtool')) {
$time = floor(($time ? $time : time()) / $sec); // Zeit auf $sec Sekunden runden
while($rep--) {
$hash = hash_hmac('sha1',str_pad(pack('N*',$time),8,"\0",STR_PAD_LEFT),unBase(strtoupper($key),'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),true); // Hash aus Zeit und Secret berechnen
$hash = unpack('N',substr($hash,ord(substr($hash,-1)) & 15, 4)); // Hash auf 32 Bits reduzieren
$otp[$time++*$sec] = str_pad(($hash[1] & (1 << 31) - 1) % 1e6,$digit,0,STR_PAD_LEFT);// fertigen Code ausgeben
}
}
else
return errmsg("hash_hmac steht nicht zur verfügung",__FUNCTION__);
dbug(" -> Token: ".implode(", ",$otp),9);
return (count($otp) == 1) ? reset($otp) : $otp;
}
function xml2array($xml,$attr="_attribute") { // Konvertiert eine XML-Datei in ein Array
if(preg_match_all('/<([\w:.-]+)([^\/>]*)(?:\/>|>\s*((?:[^<]|<(?!\/?\1>)|(?R))*)\s*<\/\1>)/x',$xml,$val)) {
$xml = array();
foreach($val[1] as $key => $var) {
$sub = call_user_func(__FUNCTION__,$val[3][$key],$attr);// Untertag einlesen
if($val[2][$key] and preg_match_all('/([\w:.-]+)="((?:[^"]+|\\\\")*)"/',$val[2][$key],$m))
foreach($m[1] as $k => $v) { // Attribute einlesen
if(is_string($sub))
$sub = $sub ? array($sub) : array();
if($attr)
$sub[$attr][$v] = $m[2][$k];
else
$sub[$v] = $m[2][$k];
}
if(isset($xml[$var])) { // Tag schon vorhanden
if(!isset($xml[$var][0]) or !is_array($xml[$var])) // Noch nicht Nummeriert?
$xml[$var] = array($xml[$var]); // Einträge in Nummer 0 verschieben
elseif(isset($xml[$var][0]) and !is_array($xml[$var][0]) and isset($xml[$var][$attr])) {
$xml[$var][0] = array($xml[$var][0],$attr => $xml[$var][$attr]);
unset($xml[$var][$attr]);
}
$xml[$var][] = $sub; // Tag hinten dran hängen
}
else
$xml[$var] = $sub; // Tag normal speichern
}
}
return $xml;
}
function tar2array($file,$preg=false) { // Liest ein Tar-Archiv vom File als Array ein
global $cfg;
if(file_exists($file) and preg_match($cfg['ptar'],$file,$var) and $func = ($cfg['bzip'] and ifset($var[3])) ? array('bzopen','bzread','bzclose')
: array($cfg['zlib']['open'],$cfg['zlib']['read'],$cfg['zlib']['close']) and $fp = call_user_func($func[0],$file,'r')) {
dbug("Entpacke Tar-Archiv aus Datei",9);
$tar = array();
while($meta = call_user_func($func[1],$fp,512) and preg_match('/^[^\0]+/',substr($meta,0,100),$name)) {
$data = substr_replace($meta," ",148,8);
for($crc=$a=0; $a < 512; $crc += ord($data[$a++]));
if($crc != octdec(substr($meta,148,6)))
return errmsg("16:Defektes Tar-Archiv",__FUNCTION__);
if($size = octdec(substr($meta,124,11)))
for($data = "", $a = $size + 512 - $size % 512; $a and ($var = call_user_func($func[1],$fp,$a)) !== false; $a -= strlen($var))
$data .= $var;
if(!$meta[156] and (!$preg or preg_match($preg,$name[0])))
$tar[$name[0]] = substr($data,0,$size);
}
call_user_func($func[2],$fp);
dbug($tar,9,'8,tar2array-#');
return $tar;
}
return errmsg("8:TAR-Archiv nicht gefunden oder läßt sich nicht öffnen",__FUNCTION__);
}
function datatar2array($tar,$preg=false) { // Parst aus einer Variable ein Tar-Archiv mit Meta-Daten als Array
dbug("Entpacke Tar-Archiv aus Variable",9);
if(preg_match_all('/(\D+)(\d+)/',"name100mode8UID8GID8SIZE12MTIME12CHKSUM8TYPEFLAG1linkname100magic6VERSION2uname32gname32devmajor8devminor8prefix155",$array))
$array = array_combine($array[1],$array[2]);
$out = array();
$pos = 0;
while($pos < strlen($tar) and $tar[$pos] != "\0") {
$meta = array();
$data = substr_replace(substr($tar,$pos,512)," ",148,8);// Buffer ohne Checksumme vorbereiten
for($crc=$a=0; $a < 512; $crc += ord($data[$a++])); // Checksumme berechnen
if($crc != octdec(substr($tar,$pos + 148,6)))
return errmsg("16:Defektes Tar-Archiv",__FUNCTION__);
$a = $pos;
foreach($array as $key => $var) {
if($data = preg_replace('/\0+$/','',substr($tar,$a,$var)))
$meta[strtolower($key)] = (strtoupper($key) == $key and preg_match('/^[0-7]+$/',$data)) ? octdec($data) : $data;
$a += $var;
}
$meta['data'] = substr($tar,$pos + 512,$meta['size']);
if($size = $meta['size'])
$pos += $size + 512 - $size % 512;
$pos += 512;
if(!ifset($meta['typeflag']) and (!$preg or preg_match($preg,$meta['name'])))
$out[$meta['name']] = $meta;
}
return $out;
}
function data2tar($name,$data='',$time=0) { // Erstellt ein Tar-Header
$data = str_pad($name,100,chr(0))."0100777".chr(0).str_repeat(str_repeat("0",7).chr(0),2).str_pad(decoct(strlen($data)),11,"0",STR_PAD_LEFT).chr(0)
.str_pad(decoct($time),11,"0",STR_PAD_LEFT).chr(0)." 0".str_repeat(chr(0),100)."ustar".chr(0)."00".str_repeat(chr(0),247)
.$data.str_repeat(chr(0),(512 - strlen($data) % 512) % 512);
for($a=$b=0; $a<512; $a++)
$b += ord($data[$a]);
return substr_replace($data,str_pad(decoct($b),6,"0",STR_PAD_LEFT).chr(0)." ",148,8);
}
function zip2array($data,$pass=array(),$zip=array(),$x=0) {// Liest ein ZIP-Archiv auf einer Variable als Array ein
global $cfg;
if(is_int($pass)) { // Unterfunktionen für zip2array
if($pass >=0) { // le2int (str,pos,len,raw)
$data = strrev(substr($data,intval($pass),$zip ? intval($zip) : 2));
$zip = $x ? $data : hexdec(bin2hex($data));
}
elseif($pass >= -2) { // zipcrypto (str,-[12],array(zipcrc))
$nhash = "";
for($a = 0; $a < strlen($data); $a++) {
if($pass == -2)
$nhash .= chr(ord($data[$a]) ^ call_user_func(__FUNCTION__,$b = $zip[2] | 2,-5,$b ^ 1) >> 8 & 255);
$zip[0] = call_user_func(__FUNCTION__,call_user_func(__FUNCTION__,$nhash ? $nhash[$a] : $data[$a],-3,$zip[0]),-4,0);
$zip[1] = call_user_func(__FUNCTION__,call_user_func(__FUNCTION__,$zip[1] + ($zip[0] & 255),-5,0x8088405) + 1,-4,0);
$zip[2] = call_user_func(__FUNCTION__,call_user_func(__FUNCTION__,chr(call_user_func(__FUNCTION__,$zip[1],-4,24)),-3,$zip[2]),-4,0);
}
if($pass == -2)
$zip = $nhash;
}
elseif($pass == -3) { // crc32 (str,-3,crc)
if(!isset($cfg['czip']))
for($a=0; $a < 256; $cfg['czip'][$a++] = $c)
for($b=0,$c=$a; $b < 8; $b++)
$c = ($c>>1) & 0x7FFFFFFF ^ ($c & 1) * 0xEDB88320;
for($zip = intval($zip), $a=0; $a < strlen($data); $a++)
$zip = $cfg['czip'][($zip ^ ord($data[$a])) & 255] ^ ( $zip >> 8 ) & 0xFFFFFF;
# $zip = substr("0000000".dechex($zip < 0 ? ~$zip : 0xFFFFFFFF + ~ --$zip),-8);
}
elseif($pass == -4) { // urShift (a,-4,b)
if($zip >= 32 or $zip < -32)
$zip %= 32;
elseif($zip < 0)
$zip += 32;
$zip = !$zip ? ($data>>1 & 0x7fffffff) * 2 + ($data>>$zip & 1) : (($data < 0) ? ($data >> 1 & 0x7fffffff | 0x40000000) >> $zip - 1 : $data >> $zip);
}
elseif($pass == -5) // imul (a,-5,b)
$zip = call_user_func(__FUNCTION__,($data >> 16 & 65535) * ($c = $zip & 65535) + ($data &= 65535) * ($zip >> 16 & 65535) << 16,-4,0) + $data * $c;
}
else { // data2zip
if(!$pass and ifset($cfg['zp']))
$pass = $cfg['zp'];
if($pass and (!($aes = cfgdecrypt(0,'aes')) or !preg_array('/^(openssl|mcrypt)$/i',$aes,1) or !(function_exists('hash_pbkdf2') or cfgdecrypt(0,'hashtool'))
or !(function_exists('hash_algos') or !cfgdecrypt(0,'mhash') or !cfgdecrypt(0,'sha256')))) // Ist Verschlüsslung möglich?
return errmsg("Keine AES-CTR Funktion gefunden",__FUNCTION__);
for($pos = $d = 0; $pos < strlen($data)
and preg_match('/^PK(?:(\x03\x04)|(\x01\x02)|\x05(?:(\x05)|(\x06))|\x06(?:(\x06)|(\x07)|(\x08))|(\x07\x08))()/',substr($data,$pos),$c); $pos += $d) {
if($c[1] and call_user_func(__FUNCTION__,$data,$pos + 4,1) < 52) { // \x03\x04 (Local file header) Bis Version 5.1
$g = (call_user_func(__FUNCTION__,$data,$pos + 6) & 8 and preg_match('/PK\x07\x08.{12}PK[\x01-\x09]{2}/s',substr($data,$pos),$h)) ? $h : 0; // Stream-ZIP Ersatz-Header suchen
$i = substr($data,$pos + 30,$d = $h = call_user_func(__FUNCTION__,$data,$pos + 26)); // Dateiname
$j = strtotime((1980 + (($e = call_user_func(__FUNCTION__,$data,$pos + 10,4))>>25))."-".($e>>21 & 15)."-".($e>>16 & 31)." ".($e>>11 & 31).":".($e>>5 & 63).":".(($e & 31) * 2)); // Datum
$e = substr($data,$pos + 30 + ($d += call_user_func(__FUNCTION__,$data,$pos + 28)),($f = $g ? call_user_func(__FUNCTION__,$g[0],8,4) : call_user_func(__FUNCTION__,$data,$pos + 18,4))); // Gepackte Daten holen (f = länge)
$d += 30 + $f; // Offset um Header mit Daten zu überspringen
if(!(call_user_func(__FUNCTION__,$data,$pos + 6) & ~2062) and (!$e or ($e = (($f = call_user_func(__FUNCTION__,$data,$pos + 8)) == 8) ? gzinflate($e)// Flags abfragen
: (($f == 12 and $cfg['bzip']) ? bzdecompress($e) : (!$f ? $e : "")))) // UnZip
and strlen($e) == ($g ? call_user_func(__FUNCTION__,$g[0],12,4) : call_user_func(__FUNCTION__,$data,$pos + 22,4)) // Stimmt die Länge?
and (hash('crc32b',$e,1) == ($g ? call_user_func(__FUNCTION__,$g[0],4,4,1) : call_user_func(__FUNCTION__,$data,$pos + 14,4,1)))) { // Entpackte Daten korrekt?
if(substr($i,-1) != "/")
$zip[$i] = $x ? $e : array('data' => $e, 'mtime' => $j); // Entpackte Daten & Datum sichern
$i = 0;
}
else if(!$g and !(($g = call_user_func(__FUNCTION__,$data,$pos + 6)) & ~2055) and $g % 2 and call_user_func(__FUNCTION__,$data,$pos + 8) == 99 and substr($data,$g = $pos + 30 + $h,2) == "\x01\x99" // AES-ZIP
and (($f = call_user_func(__FUNCTION__,$data,$g + 4)) == 2 and !call_user_func(__FUNCTION__,$data,$pos + 14,4) or $f == 1) and $f = call_user_func(__FUNCTION__,$data,$g + 8,1) and $f = ++$f * 64) { // f: AES-Bits / g: offset extra-header
if(!$pass)
return errmsg("Archiv benötigt ein Kennwort (-zp:'password')",__FUNCTION__);
foreach($pass as $pw) // Password-manager befragen
if(substr(($c = hash_pbkdf2("sha1",$pw,substr($e,0,$f >> 4),1e3,$f / 4 + 16,1)),$f / 4,2) == substr($e,$f >> 4,2))// Kennwort-Hash erstellen und testen
break;
else
$pw = false;
if($c and $pw and substr($c,$f / 4,2) == substr($e,$f >> 4,2) and substr(hash_hmac("sha1",$h = substr($e,$f / 16 + 2, strlen($e) - ($f / 16 + 2) - 10),substr($c,$f / 8, $f / 8),1),0,10) == substr($e,-10)) {
for($e = ""; strlen($e) < strlen($h); ) {
$b = array(substr($h,strlen($e),16),substr($c,0,$f/8),str_pad(pack('V',(strlen($e) >> 4) + 1),16,chr(0)));
if(isset($aes['openssl']))
$e .= openssl_decrypt($b[0],"aes-$f-ctr",$b[1],OPENSSL_RAW_DATA,$b[2]);
elseif(isset($aes['mcrypt'])) // Extension: MCrypt
$e .= mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$b[1],$b[0],'ctr',$b[2]);
else
break;
}
if(($e = (($c = call_user_func(__FUNCTION__,$data,$g + 9)) == 8) ? gzinflate($e) : (($c == 12 and $cfg['bzip']) ? bzdecompress($e) : (!$c ? $e : "")) or $e === "")// UnZip
and strlen($e) == call_user_func(__FUNCTION__,$data,$pos + 22,4) and (($c = call_user_func(__FUNCTION__,$data,$g + 4)) == 1 and call_user_func(__FUNCTION__,$data,$pos + 14,4,1) == hash('crc32b',$e,1) or $c == 2)) { // Länge & Optional CRC32 überprüfen
if(substr($i,-1) != "/") // Nur Dateien eintragen
$zip[$i] = $x ? $e : array('data' => $e, 'mtime' => $j, 'pass' => $pw, 'bits' => $f); // Entpackte Daten & Datum sichern
$i = 0;
}
else
return errmsg("Entschlüsselung ist fehlgeschlagen",__FUNCTION__);
}
else
return errmsg("Das Kennwort ist falsch",__FUNCTION__);
}
else if(($g = call_user_func(__FUNCTION__,$data,$pos + 6)) % 2 and !($g & ~2063) and call_user_func(__FUNCTION__,$data,$pos + 14,4)) { // Crypto-ZIP
if(!$pass)
return errmsg("Archiv benötigt ein Kennwort (-zp:'password')",__FUNCTION__);
foreach($pass as $pw) {// Password-manager befragen
$f = call_user_func(__FUNCTION__,$pw,-1,array(0x12345678,0x23456789,0x34567890));
if(substr($data,$pos + ($g & 8 ? 11 : 17),1) == substr($f = call_user_func(__FUNCTION__,$e,-2,$f),11,1)) // Kennwort-Hash erstellen und testen
break;
else
return errmsg("Das Kennwort ist falsch",__FUNCTION__);
}
if($f and (!($e = substr($f,12)) or ($e = ($f = call_user_func(__FUNCTION__,$data,$pos + 8)) == 8 ? gzinflate($e) : (($f == 12) ? bzdecompress($e) : (!$f ? $e : "")))// UnZip
and strlen($e) == call_user_func(__FUNCTION__,$data,$pos + 22,4) and hash('crc32b',$e,1) == call_user_func(__FUNCTION__,$data,$pos + 14,4,1))) { // Länge & CRC32 überprüfen
if(substr($i,-1) != "/") // Nur Dateien eintragen
$zip[$i] = $x ? $e : array('data' => $e, 'mtime' => $j, 'pass' => $pw, 'bits' => $f); // Entpackte Daten & Datum sichern
$i = 0;
}
}
if($i)
$data .= 0; // Fehler erkennen (Sourcelänge verändern)
}
else // Alle Header werden übersprungen (Ignoriert)
$d = $c[2] ? 46 + call_user_func(__FUNCTION__,$data,$pos + 28) + call_user_func(__FUNCTION__,$data,$pos + 30) + call_user_func(__FUNCTION__,$data,$pos + 32)// \x01\x02 (Central directory file header)
: ($c[3] ? call_user_func(__FUNCTION__,$data,$pos + 4) + 6 // \x05\x05 (Digital signature)
: ($c[4] ? call_user_func(__FUNCTION__,$data,$pos + 20) + 22 // \x05\x06 (End of central directory record)
: ($c[5] ? call_user_func(__FUNCTION__,$data,$pos + 4,8) + 12 // \x06\x06 (Zip64 end of central directory record)
: ($c[6] ? 20 // \x06\x07 (Zip64 end of central directory locator)
: ($c[7] ? call_user_func(__FUNCTION__,$data,$pos + 4,4) + 8 // \x06\x08 (Archive extra data record)
: ($c[8] ? 16 : 1)))))); // \x07\x08 (Stream-Header: crc32, df-len, if-len)
}
# dbug($zip,9,'8,zip2array-#');
if($pos != strlen($data))
$zip = errmsg("Archiv ist beschädigt oder wird nicht unterstützt",__FUNCTION__);
}
return $zip;
}
function data2zip($files,$pass=false,$time=false) { // Erstellt aus ein Array ein ZIP-Archiv
global $cfg;
if(!is_array($files))
return errmsg("Unbekannte Parameter",__FUNCTION__);
if(!$pass and ifset($cfg['zp'])) // Password von Optionen übernehmen
$pass = $cfg['zp'] ? reset($cfg['zp']) : false;
if($pass) // Prüfen ob Verschlüsselung überhaupt möglich ist
if(!$aes = cfgdecrypt(0,'aes') or !preg_array('/^(openssl|mcrypt)$/i',$aes,1) or !(function_exists('hash_pbkdf2') or cfgdecrypt(0,'hashtool'))
or !(function_exists('hash_algos') or !cfgdecrypt(0,'mhash') or !cfgdecrypt(0,'sha256')) or !$cfg['zb']) // Ist Verschlüsslung möglich?
return errmsg("Keine möglichkeit gefunden die AES-CTR Funktion auszuführen",__FUNCTION__);
$zip = $dir = ""; // Leeres Zip-Archiv
foreach($files as $file => $meta) { // Array durchgehen
if(!is_array($meta))
$meta = array('data' => $meta);
$time = isset($meta['time']) ? $meta['time'] : ($time ? $time : time());
$m = "";
$i = strlen($meta['data']) ? ($cfg['bz'] ? bzcompress($meta['data'],$cfg['bz']) : ($cfg['gz'] ? gzdeflate($meta['data'],$cfg['gz']) : "")) : ""; // Deflate Data
if(!$i or strlen($i) > strlen($meta['data'])) // Store Data?
$i = $meta['data'];
if($pass) { // Verschlüsselung AES-AE2 (128/192/256)
$jk = function_exists("openssl_random_pseudo_bytes") ? openssl_random_pseudo_bytes($cfg['zb']/8) : sha1(mt_rand().time()); // key
$js = substr(hash_hmac('sha256',$file.time().serialize($meta).$pass,$jk,1),0,$cfg['zb']/16);
$jh = hash_pbkdf2("sha1",$pass,$js,1e3,$cfg['zb']/4+16,1); // (48,64,80)
for($k = $m; strlen($k) < strlen($i);) {
$b = array( substr($i,strlen($k),16), // Data
substr($jh,0,$cfg['zb'] / 8), // Key
str_pad(pack('V',(strlen($k) >> 4) + 1),16,"\0")); // Counter
if(isset($aes['openssl']))
$k .= openssl_encrypt($b[0],"aes-$cfg[zb]-ctr",$b[1],OPENSSL_RAW_DATA,$b[2]);
elseif(isset($aes['mcrypt']) and $x = mcrypt_module_open(MCRYPT_RIJNDAEL_128,'','ctr','')) { // Extension: MCrypt
mcrypt_generic_init($x, $b[1], $b[2]); // https://github.com/beyonderyue/aes-ctr-php
$k .= mcrypt_generic($x, $b[0]);
mcrypt_generic_deinit($x);
mcrypt_module_close($x);
}
else
break;
}
$m = "\1\x99\7\0\2\0AE".chr($cfg['zb']/64-1).chr((strlen($k) == strlen($meta['data'])) ? 0 : ($cfg['bz'] ? 12 : 8))."\0"; // Extra-Data Header
$i = $js.substr($jh,$cfg['zb'] / 4,2).$k.substr(hash_hmac("sha1",$k,substr($jh,$cfg['zb'] / 8,$cfg['zb'] / 8),1),0,10);// Salt + Chk + Cipher + Hash
}
$k = (($k = utf8($file)) != $file) ? $k : $file;
$j = ($m ? "\x33" : (($i != $meta['data']) ? chr($cfg['bz'] ? 46 : 20) : "\n"))."\0"
.pack("v",(($k != $file) ? 2048 : 0) | ($m ? 1 : 0)).($m ? "c" : chr(($i != $meta['data']) ? ($cfg['bz'] ? 12 : 8) : 0))."\0"
.pack('v*',intval(date('G',$time)) * (1<<11) + intval(date('i',$time)) * (1<<5) + (intval(date('s',$time)) >>1),// Time
(intval(date('Y',$time)) - 1980) * (1<<9) + intval(date('n',$time)) * (1<<5) + intval(date('j',$time))) // Date
.strrev(!$m ? hash("crc32b",$meta['data'],1) : pack("V",0)) // CRC32
.pack('V*',strlen($i),strlen($meta['data'])).pack('v*',strlen($k),strlen($m));
$dir .= "PK\1\2\0\0$j".str_repeat("\0",10).pack('V',strlen($zip)).$k.$m; // Central directory file header
$zip .= "PK\3\4$j$k$m$i"; // Local file header
}
return $zip.$dir."PK\5\6\0\0\0\0".str_repeat(pack('v',count($files)),2).pack('V*',strlen($dir),strlen($zip))."\0\0";
}
function array2json($array,$opt=0,$c=0) { // Macht aus einem Array eine JSON-Textdatei (opt: 1:utf8, 2:jsmode, 4:utfesc, 8:noGLOBALS)
if(is_array($array))
if(isset($array[0]) and is_string($array[0]) and strlen($array[0]) == 1 and isset($array[1])
and (isset($array['s']) or isset($array['u']) or count($array) == 2 and $array[0] == $array[1]))
$str = '\\'.((($a = ord($array[0])) < 14 and isset($array['s'])) ? substr("01234567btnvfr",$a,1) : (($a < 32) ? 'u'.str_pad(dechex($a),4,0,STR_PAD_LEFT) : $array[0]));