forked from k0a1a/hotglue2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.inc.php
630 lines (570 loc) · 13.1 KB
/
util.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<?php
/*
* util.inc.php
* Static utility functions
*
* Copyright Gottfried Haider, Danja Vasiliev 2010.
* This source code is licensed under the GNU General Public License.
* See the file COPYING for more details.
*/
/**
* convert an associative array to a javascript block
*
* @param array $container container array
* @return string
*/
function array_to_js($container)
{
$ret = '<script type="text/javascript">'.nl();
// sort container by keys
ksort($container);
$exists = array();
foreach ($container as $key=>$val) {
// make sure the keys exist
$objs = expl('.', $key);
for ($i=0; $i < count($objs)-1; $i++) {
$obj = implode('.', array_slice($objs, 0, $i+1));
if (!in_array($obj, $exists)) {
if ($i == 0) {
$ret .= tab().'var '.$obj.' = '.$obj.' || {};'.nl();
} else {
$ret .= tab().$obj.' = '.$obj.' || {};'.nl();
}
$exists[] = $obj;
}
}
$ret .= tab().''.$key.' = '.json_encode($val).';'.nl();
}
$ret .= '</script>'.nl();
return $ret;
}
/**
* make an array off associative array unique in a certain key-value
*
* @param array &$a reference to array
* @param mixed $key key whose value we compare
*/
function array_unique_element(&$a, $key)
{
// for each row
for ($cur=0; $cur < count($a); $cur++) {
// look in every row further down
for ($i=$cur+1; $i < count($a); $i++) {
// to see if the value of a key in the array is the same as in the
// current row
if ($a[$i][$key] == $a[$cur][$key]) {
// delete the row further down
array_splice($a, $i, 1);
$i--;
}
}
}
}
/**
* check if a directory already contains a file (based on its content)
*
* @param string $dir directory to check
* @param string $fn file to look for
* @param string $orig_fn first check this filename (optional)
* @return (basename) filename of identical file in $dir or false if
* there is none
*/
function dir_has_same_file($dir, $fn, $orig_fn = '')
{
// strip any slash at the end of $dir
if (substr($dir, -1) == '/') {
$dir = substr($dir, 0, -1);
}
if (empty($orig_fn)) {
$orig_fn = basename($fn);
} else {
$orig_fn = basename($orig_fn);
}
if (($dir_fns = @scandir($dir)) === false) {
return false;
}
// optimization: check $orig_fn first
if (($i = array_search($orig_fn, $dir_fns)) !== false) {
$a = array_splice($dir_fns, $i, 1);
array_unshift($dir_fns, $a[0]);
}
foreach ($dir_fns as $f) {
if ($f == '.' || $f == '..') {
continue;
}
if (!file_is_different($fn, $dir.'/'.$f)) {
return $f;
}
}
return false;
}
/**
* check if two directories are different
*
* @param string $a filename
* @param string $b filename
* @return bool
*/
function dir_is_different($a, $b)
{
if (substr($a, -1) == '/') {
$a = substr($a, 0, -1);
}
if (substr($b, -1) == '/') {
$b = substr($b, 0, -1);
}
$a_fns = @scandir($a);
$b_fns = @scandir($b);
if ($a_fns !== $b_fns) {
return true;
}
foreach ($a_fns as $fn) {
if ($fn == '.' || $fn == '..') {
continue;
}
if (is_dir($a.'/'.$fn) || is_dir($b.'/'.$fn)) {
if (dir_is_different($a.'/'.$fn, $b.'/'.$fn)) {
return true;
}
} else {
if (file_is_different($a.'/'.$fn, $b.'/'.$fn)) {
return true;
}
}
}
return false;
}
/**
* split a string by string
*
* like php's explode() but handles empty strings better.
* @param string $delimiter boundary string
* @param string $string input string
* @return array
*/
function expl($delimiter, $string)
{
$ret = explode($delimiter, $string);
if (count($ret) == 1 && empty($ret[0])) {
return array();
} else {
return $ret;
}
}
/**
* explode a string splitting it by whitespace characters
*
* @param string $s input string
* @param bool $honor_quot don't split inside quotation marks
* @return array of strings
*/
function expl_whitesp($s, $honor_quot = false)
{
// same characters as trim() uses
$whitesp = array(' ', "\t", "\n", "\r", "\0", "\x0B");
$quot = array('"', "'");
$ret = array();
$prev = -1;
$cur_quot = false;
for ($i=0; $i < strlen($s); $i++) {
if ($honor_quot && in_array($s[$i], $quot)) {
if ($cur_quot === false) {
// begin of quote
$cur_quot = $s[$i];
} elseif ($cur_quot == $s[$i] && ($i < 1 || $s[$i-1] != "\\")) {
// end of quote
$cur_quot = false;
}
}
if ($cur_quot !== false) {
// do nothing while on a quote
continue;
}
if (in_array($s[$i], $whitesp)) {
if ($prev+1 == $i) {
$prev++;
} else {
$ret[] = substr($s, $prev+1, $i-$prev-1);
$prev = $i;
}
}
}
if ($prev+2 < $i) {
$ret[] = substr($s, $prev+1);
}
return $ret;
}
/**
* check if two files are different
*
* @param string $a filename
* @param string $b filename
* @return bool
*/
function file_is_different($a, $b)
{
if (@filesize($a) !== @filesize($b)) {
return true;
}
if (@md5_file($a) !== @md5_file($b)) {
return true;
} else {
return false;
}
}
/**
* get the extension of a file
*
* @param string $s filename
* @return string
*/
function filext($s)
{
$a = expl('.', $s);
if (1 < count($a)) {
return(array_pop($a));
} else {
return '';
}
}
/**
* select the first element of an array, or other Traversable
*
* @param Traversable|array $iterable the array where to pick the first value
* @return mixed
*/
function get_first_item($iterable)
{
if (!is_iterable($iterable)) {
throw new InvalidArgumentException("Argument isn't iterable.");
}
foreach ($iterable as $item) {
return $item;
}
}
/**
* return a http error message to the client
*
* if $header_only is false (the default), the function doesn't
* return if successful.
* @param int $code error code
* @param bool $header_only only output the header and return
* @return bool true if successful (only if $header_only is true), false
* if not
*/
function http_error($code, $header_only = false)
{
switch ($code) {
case 400:
$error = 'Bad Request';
break;
case 404:
$error = 'Not Found';
break;
case 500:
$error = 'Internal Server Error';
break;
default:
// unsupported
return false;
}
header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$error);
if (!$header_only) {
echo $error;
die();
} else {
return true;
}
}
/**
* check if the user is http digest authenticated
*
* @param array $users array of possible users (usernames as keys,
* password as values)
* @param string $realm realm (e.g. name of the site)
* @retval 0 authenticated
* @retval -1 user did not request authentication
* @retval -2 parts of the response are missing
* @retval -3 unknown username
* @retval -4 invalid password
*/
function http_digest_check($users, $realm = '')
{
// code based on the php documentation
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
return -1;
} else {
$auth = $_SERVER['PHP_AUTH_DIGEST'];
}
// taken from one of the comments
$data = array();
preg_match("/username=\"([^\"]+)\"/i", $auth, $match);
if (isset($match[1])) {
$data['username'] = $match[1];
} else {
return -2;
}
preg_match('/nonce=\"([^\"]+)\"/i', $auth, $match);
if (isset($match[1])) {
$data['nonce'] = $match[1];
} else {
return -2;
}
preg_match('/nc=([0-9a-f]+)/i', $auth, $match);
if (isset($match[1])) {
$data['nc'] = $match[1];
} else {
return -2;
}
preg_match('/cnonce=\"([^\"]+)\"/i', $auth, $match);
if (isset($match[1])) {
$data['cnonce'] = $match[1];
} else {
return -2;
}
// fixed for Safari
// qop comes as qop="auth"
preg_match('/qop=\"?([^,\"]+)/i', $auth, $match);
if (isset($match[1])) {
$data['qop'] = $match[1];
} else {
return -2;
}
preg_match('/uri=\"([^\"]+)\"/i', $auth, $match);
if (isset($match[1])) {
$data['uri'] = $match[1];
} else {
return -2;
}
preg_match('/response=\"([^\"]+)\"/i', $auth, $match);
if (isset($match[1])) {
$data['response'] = $match[1];
} else {
return -2;
}
// check username
if (!array_key_exists($data['username'], $users)) {
return -3;
}
// generate the valid response
$a1 = md5($data['username'].':'.str_replace("\"", '', $realm).':'.$users[$data['username']]);
$a2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($a1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$a2);
if ($data['response'] != $valid_response) {
return -4;
} else {
return 0;
}
}
/**
* prompt the user for http digest authentication
*
* make sure the script stops execution after calling this function.
* @param string $realm realm (e.g. name of the site)
*/
function http_digest_prompt($realm = '')
{
// code based on the php documentation
header($_SERVER['SERVER_PROTOCOL'].' 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.str_replace("\"", '', $realm).'",qop="auth",nonce="'.uniqid().'",opaque="'.md5(str_replace("\"", '', $realm)).'"');
}
/**
* check if a string is a url
*
* @param string $s
* @return bool
*/
function is_url($s)
{
if (strpos($s, '://') || strtolower(substr($s, 0, 7)) == 'mailto:') {
return true;
} else {
return false;
}
}
if (!function_exists('is_iterable'))
{
/**
* determine if a variable is iterable (already implemented in PHP 7.1+)
*
* @param mixed $var the variable to check
* @return bool
*/
function is_iterable($var)
{
return is_array($var) || $var instanceof Traversable;
}
}
/**
* return a number of newline characters
*
* @param int $count count (one is default)
* @return string
*/
function nl($count = 1)
{
$s = '';
while (0 < $count--) {
$s .= "\n";
}
return $s;
}
/**
* pad a string to have at least $num characters
*
* @param string $s string to operate on
* @param int $num number of characters desired
* @param string $chr character to pad the string with
* @return string
*/
function pad($s, $num, $chr = ' ')
{
for ($i=strlen($s); $i < $num; $i++) {
$s .= $chr;
}
return $s;
}
/**
* return a string with double quotation marks wrapped around
*
* @param string $s string
* @return string
*/
function quot($s)
{
return '"'.$s.'"';
}
/**
* delete a file or directory
*
* @param string $f file name
* @return true if successful, false if not
*/
function rm_recursive($f)
{
if (@is_file($f) || @is_link($f)) {
// note: symlinks get deleted right away, and not recursed into
return @unlink($f);
} else {
if (($childs = @scandir($f)) === false) {
return false;
}
// strip a tailing slash
if (substr($f, -1) == '/') {
$f = substr($f, 0, -1);
}
foreach ($childs as $child) {
if ($child == '.' || $child == '..') {
continue;
} else {
rm_recursive($f.'/'.$child);
}
}
return @rmdir($f);
}
}
/**
* serve a file to the client
*
* this function only returns on errors.
* @param string $fn filename
* @param bool $dl download file
* @param string $mime mime type
*/
function serve_file($fn, $dl, $mime = '')
{
if (($size = @filesize($fn)) === false) {
return false;
}
if (empty($mime)) {
// fall back to octet-stream
$mime = 'application/octet-stream';
}
// TODO (later): optionally set the mime type based on the file extension only
// see http://www.php.net/manual/en/function.readfile.php#52722
// TODO (later): handle byte range
// TODO (later): handle if-modified-since etc
// TODO (later): also check apache_request_headers()
if ($dl) {
// these are taken from the php documentation (on readfile())
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($fn).'"');
header('Content-Transfer-Encoding: binary');
} else {
header('Content-Type: '.$mime);
}
header('Content-Length: '.$size);
flush();
@readfile($fn);
die();
}
/**
* return a number of tab characters
*
* @param int $count count (one is default)
* @return string
*/
function tab($count = 1)
{
$s = '';
while (0 < $count--) {
$s .= "\t";
}
return $s;
}
/**
* find a unique filename for copying a file to destination directory
*
* @param string $dir destination directory
* @param string $orig_fn original filename
* @return string (basename) proposed filename
*/
function unique_filename($dir, $orig_fn)
{
// strip any slash at the end of $dir
if (substr($dir, -1) == '/') {
$dir = substr($dir, 0, -1);
}
$fn = basename($orig_fn);
$num = 1;
// is_link() is there to catch dangling symlinks
while (is_file($dir.'/'.$fn) || is_dir($dir.'/'.$fn) || is_link($dir.'/'.$fn)) {
// find first dot and prepend _$num there
// TODO (later): we could handle the case where $orig_fn is already
// something like foo_2.bar
$fn = basename($orig_fn);
if (($p = strpos($fn, '.')) !== false) {
$fn = substr($fn, 0, $p).'_'.(++$num).substr($fn, $p);
} else {
$fn .= '_'.(++$num);
}
}
return $fn;
}
/**
* print human-readable information about a variable in inline format
*
* @param mixed $var variable
* @return string
*/
function var_dump_inl($var)
{
// print_r returns true/false as '1'/''
// fix this at least for the value of $var itself
if (is_bool($var) && $var) {
return 'true';
} elseif (is_bool($var)) {
return 'false';
}
$ret = print_r($var, true);
// remove control characters
$ret = str_replace("\n", ' ', $ret);
$ret = str_replace("\r", ' ', $ret);
$ret = str_replace("\t", ' ', $ret);
// remove double spaces
do {
$ret = str_replace(' ', ' ', $ret, $cnt);
} while (0 < $cnt);
return trim($ret);
}