]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
Add new `admin_ip` configuration option
[jirafeau.git] / lib / functions.php
1 <?php
2 /*
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 /**
23 * Transform a string in a path by separating each letters by a '/'.
24 * @return path finishing with a '/'
25 */
26 function s2p($s)
27 {
28 $block_size = 8;
29 $p = '';
30 for ($i = 0; $i < strlen($s); $i++) {
31 $p .= $s[$i];
32 if (($i + 1) % $block_size == 0) {
33 $p .= '/';
34 }
35 }
36 if (strlen($s) % $block_size != 0) {
37 $p .= '/';
38 }
39 return $p;
40 }
41
42 /**
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
45 */
46 function base_16_to_64($num)
47 {
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
49 $hex2bin = array('0000', # 0
50 '0001', # 1
51 '0010', # 2
52 '0011', # 3
53 '0100', # 4
54 '0101', # 5
55 '0110', # 6
56 '0111', # 7
57 '1000', # 8
58 '1001', # 9
59 '1010', # a
60 '1011', # b
61 '1100', # c
62 '1101', # d
63 '1110', # e
64 '1111'); # f
65 $o = '';
66 $b = '';
67 $i = 0;
68 # Convert long hex string to bin.
69 $size = strlen($num);
70 for ($i = 0; $i < $size; $i++) {
71 $b .= $hex2bin[hexdec($num[$i])];
72 }
73 # Convert long bin to base 64.
74 $size *= 4;
75 for ($i = $size - 6; $i >= 0; $i -= 6) {
76 $o = $m[bindec(substr($b, $i, 6))] . $o;
77 }
78 # Some few bits remaining ?
79 if ($i < 0 && $i > -6) {
80 $o = $m[bindec(substr($b, 0, $i + 6))] . $o;
81 }
82 return $o;
83 }
84
85 /**
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
89 */
90 function jirafeau_gen_random($l)
91 {
92 if ($l <= 0) {
93 return 42;
94 }
95
96 $code="";
97 for ($i = 0; $i < $l; $i++) {
98 $code .= dechex(rand(0, 15));
99 }
100
101 return $code;
102 }
103
104 function jirafeau_gen_download_pass($length, $allowed_chars)
105 {
106 if ($length <= 0) {
107 return false;
108 }
109 $pass="";
110 for ($i = 0; $i < $length; $i++) {
111 $pass .= $allowed_chars[rand(0, strlen($allowed_chars) - 1)];
112 }
113
114 return $pass;
115 }
116
117 function is_ssl()
118 {
119 if (isset($_SERVER['HTTPS'])) {
120 if ('on' == strtolower($_SERVER['HTTPS']) ||
121 '1' == $_SERVER['HTTPS']) {
122 return true;
123 }
124 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
125 return true;
126 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
127 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
128 return true;
129 }
130 }
131 return false;
132 }
133
134 function jirafeau_human_size($octets)
135 {
136 $u = array('B', 'KB', 'MB', 'GB', 'TB');
137 $o = max($octets, 0);
138 $p = min(floor(($o ? log($o) : 0) / log(1024)), count($u) - 1);
139 $o /= pow(1024, $p);
140 return round($o, 1) . $u[$p];
141 }
142
143 // Convert UTC timestamp to a datetime field
144 function jirafeau_get_datetimefield($timestamp)
145 {
146
147 $ts = date_create("@" . $timestamp);
148 $content = '<span class="datetime" data-datetime="' . date_format($ts, 'Y-m-d H:i') . '">'
149 . date_format($ts, 'Y-m-d H:i') . ' (GMT)</span>';
150
151 return $content;
152 }
153
154 function jirafeau_fatal_error($errorText, $cfg = array())
155 {
156 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
157 require(JIRAFEAU_ROOT . 'lib/template/footer.php');
158 exit;
159 }
160
161 function jirafeau_clean_rm_link($link)
162 {
163 $p = s2p("$link");
164 if (file_exists(VAR_LINKS . $p . $link)) {
165 unlink(VAR_LINKS . $p . $link);
166 }
167 if (file_exists(VAR_LINKS . $p . $link . '_download')) {
168 unlink(VAR_LINKS . $p . $link . '_download');
169 }
170 $parse = VAR_LINKS . $p;
171 $scan = array();
172 while (file_exists($parse)
173 && ($scan = scandir($parse))
174 && count($scan) == 2 // '.' and '..' folders => empty.
175 && basename($parse) != basename(VAR_LINKS)) {
176 rmdir($parse);
177 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
178 }
179 }
180
181 function jirafeau_clean_rm_file($hash)
182 {
183 $p = s2p("$hash");
184 $f = VAR_FILES . $p . $hash;
185 if (file_exists($f) && is_file($f)) {
186 unlink($f);
187 }
188 if (file_exists($f . '_count') && is_file($f . '_count')) {
189 unlink($f . '_count');
190 }
191 $parse = VAR_FILES . $p;
192 $scan = array();
193 while (file_exists($parse)
194 && ($scan = scandir($parse))
195 && count($scan) == 2 // '.' and '..' folders => empty.
196 && basename($parse) != basename(VAR_FILES)) {
197 rmdir($parse);
198 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
199 }
200 }
201
202 /**
203 * transforms a php.ini string representing a value in an integer
204 * @param $value the value from php.ini
205 * @returns an integer for this value
206 */
207 function jirafeau_ini_to_bytes($value)
208 {
209 $modifier = substr($value, -1);
210 $bytes = substr($value, 0, -1);
211 switch (strtoupper($modifier)) {
212 default:
213 return intval($value);
214 break;
215 case 'P':
216 $bytes *= 1024;
217 // no break
218 case 'T':
219 $bytes *= 1024;
220 // no break
221 case 'G':
222 $bytes *= 1024;
223 // no break
224 case 'M':
225 $bytes *= 1024;
226 // no break
227 case 'K':
228 $bytes *= 1024;
229 }
230 return $bytes;
231 }
232
233 /**
234 * gets the maximum upload size according to php.ini
235 * @returns the maximum upload size in bytes
236 */
237 function jirafeau_get_max_upload_size_bytes()
238 {
239 return min(
240 jirafeau_ini_to_bytes(ini_get('post_max_size')),
241 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
242 );
243 }
244
245 /**
246 * gets the maximum upload size according to php.ini
247 * @returns the maximum upload size string
248 */
249 function jirafeau_get_max_upload_size()
250 {
251 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
252 }
253
254 /**
255 * get the maximal upload size for a data chunk in async uploads
256 * @param max_upload_chunk_size_bytes
257 */
258 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
259 {
260 if ($max_upload_chunk_size_bytes == 0) {
261 $size = jirafeau_get_max_upload_size_bytes();
262 // Jirafeau must choose an arbitrary number as PHP config does not give any limit nor $max_upload_chunk_size_bytes
263 if ($size == 0) {
264 return 10000000; // 10MB
265 }
266 return $size;
267 }
268 $size = min(
269 jirafeau_get_max_upload_size_bytes(),
270 $max_upload_chunk_size_bytes
271 );
272 if ($size == 0) {
273 return $max_upload_chunk_size_bytes;
274 }
275 return $size;
276 }
277
278 /**
279 * gets a string explaining the error
280 * @param $code the error code
281 * @returns a string explaining the error
282 */
283 function jirafeau_upload_errstr($code)
284 {
285 switch ($code) {
286 case UPLOAD_ERR_INI_SIZE:
287 case UPLOAD_ERR_FORM_SIZE:
288 return t('Your file exceeds the maximum authorized file size. ');
289
290 case UPLOAD_ERR_PARTIAL:
291 case UPLOAD_ERR_NO_FILE:
292 return
293 t('Your file was not uploaded correctly. You may succeed in retrying. ');
294
295 case UPLOAD_ERR_NO_TMP_DIR:
296 case UPLOAD_ERR_CANT_WRITE:
297 case UPLOAD_ERR_EXTENSION:
298 return t('Internal error. You may not succeed in retrying. ');
299 }
300 return t('Unknown error. ');
301 }
302
303 /** Remove link and it's file
304 * @param $link the link's name (hash)
305 */
306
307 function jirafeau_delete_link($link)
308 {
309 $l = jirafeau_get_link($link);
310 if (!count($l)) {
311 return;
312 }
313
314 jirafeau_clean_rm_link($link);
315
316 $hash = $l['hash'];
317 $p = s2p("$hash");
318
319 $counter = 1;
320 if (file_exists(VAR_FILES . $p . $hash. '_count')) {
321 $content = file(VAR_FILES . $p . $hash. '_count');
322 $counter = trim($content[0]);
323 }
324 $counter--;
325
326 if ($counter >= 1) {
327 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
328 fwrite($handle, $counter);
329 fclose($handle);
330 }
331
332 if ($counter == 0) {
333 jirafeau_clean_rm_file($hash);
334 }
335 }
336
337 /**
338 * Delete a file and it's links.
339 */
340 function jirafeau_delete_file($hash)
341 {
342 $count = 0;
343 /* Get all links files. */
344 $stack = array(VAR_LINKS);
345 while (($d = array_shift($stack)) && $d != null) {
346 $dir = scandir($d);
347
348 foreach ($dir as $node) {
349 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
350 preg_match('/\.tmp/i', "$node")) {
351 continue;
352 }
353
354 if (is_dir($d . $node)) {
355 /* Push new found directory. */
356 $stack[] = $d . $node . '/';
357 } elseif (is_file($d . $node)) {
358 /* Read link informations. */
359 $l = jirafeau_get_link(basename($node));
360 if (!count($l)) {
361 continue;
362 }
363 if ($l['hash'] == $hash) {
364 $count++;
365 jirafeau_delete_link($node);
366 }
367 }
368 }
369 }
370 jirafeau_clean_rm_file($hash);
371 return $count;
372 }
373
374
375 /** hash file's content
376 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
377 * @param $file_path file to hash
378 * @returns hash string
379 */
380 function jirafeau_hash_file($method, $file_path)
381 {
382 switch ($method) {
383 case 'md5_outside':
384 return jirafeau_md5_outside($file_path);
385 case 'md5':
386 return md5_file($file_path);
387 case 'random':
388 return jirafeau_gen_random(32);
389 }
390 return md5_file($file_path);
391 }
392
393 /** hash part of file: start, end and size.
394 * This is a partial file hash, faster but weaker.
395 * @param $file_path file to hash
396 * @returns hash string
397 */
398 function jirafeau_md5_outside($file_path)
399 {
400 $out = false;
401 $handle = fopen($file_path, "r");
402 if ($handle === false) {
403 return false;
404 }
405 $size = filesize($file_path);
406 if ($size === false) {
407 goto err;
408 }
409 $first = fread($handle, 64);
410 if ($first === false) {
411 goto err;
412 }
413 if (fseek($handle, $size < 64 ? 0 : $size - 64) == -1) {
414 goto err;
415 }
416 $last = fread($handle, 64);
417 if ($last === false) {
418 goto err;
419 }
420 $out = md5($first . $last . $size);
421 err:
422 fclose($handle);
423 return $out;
424 }
425
426 /**
427 * handles an uploaded file
428 * @param $file the file struct given by $_FILE[]
429 * @param $one_time_download is the file a one time download ?
430 * @param $key if not empty, protect the file with this key
431 * @param $time the time of validity of the file
432 * @param $ip uploader's ip
433 * @param $crypt boolean asking to crypt or not
434 * @param $link_name_length size of the link name
435 * @returns an array containing some information
436 * 'error' => information on possible errors
437 * 'link' => the link name of the uploaded file
438 * 'delete_link' => the link code to delete file
439 */
440 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
441 {
442 if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
443 return (array(
444 'error' =>
445 array('has_error' => true,
446 'why' => jirafeau_upload_errstr($file['error'])),
447 'link' => '',
448 'delete_link' => ''));
449 }
450
451 /* array representing no error */
452 $noerr = array('has_error' => false, 'why' => '');
453
454 /* Crypt file if option is enabled. */
455 $crypted = false;
456 $crypt_key = '';
457 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
458 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
459 }
460 if ($crypt == true && extension_loaded('mcrypt') == true) {
461 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
462 if (strlen($crypt_key) > 0) {
463 $crypted = true;
464 }
465 }
466
467 /* file information */
468 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
469 $name = str_replace(NL, '', trim($file['name']));
470 $mime_type = $file['type'];
471 $size = $file['size'];
472
473 /* does file already exist ? */
474 $rc = false;
475 $p = s2p("$hash");
476 if (file_exists(VAR_FILES . $p . $hash)) {
477 $rc = unlink($file['tmp_name']);
478 } elseif ((file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true))
479 && move_uploaded_file($file['tmp_name'], VAR_FILES . $p . $hash)) {
480 $rc = true;
481 }
482 if (!$rc) {
483 return (array(
484 'error' =>
485 array('has_error' => true,
486 'why' => t('INTERNAL_ERROR_DEL')),
487 'link' =>'',
488 'delete_link' => ''));
489 }
490
491 /* Increment or create count file. */
492 $counter = 0;
493 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
494 $content = file(VAR_FILES . $p . $hash. '_count');
495 $counter = trim($content[0]);
496 }
497 $counter++;
498 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
499 fwrite($handle, $counter);
500 fclose($handle);
501
502 /* Create delete code. */
503 $delete_link_code = jirafeau_gen_random(5);
504
505 /* hash password or empty. */
506 $password = '';
507 if (!empty($key)) {
508 $password = md5($key);
509 }
510
511 /* create link file */
512 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
513 $handle = fopen($link_tmp_name, 'w');
514 fwrite(
515 $handle,
516 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
517 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
518 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O')
519 );
520 fclose($handle);
521 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
522 $l = s2p("$hash_link");
523 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
524 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
525 if (file_exists($link_tmp_name)) {
526 unlink($link_tmp_name);
527 }
528
529 $counter--;
530 if ($counter >= 1) {
531 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
532 fwrite($handle, $counter);
533 fclose($handle);
534 } else {
535 jirafeau_clean_rm_file($hash_link);
536 }
537 return array(
538 'error' =>
539 array('has_error' => true,
540 'why' => t('Internal error during file creation. ')),
541 'link' =>'',
542 'delete_link' => '');
543 }
544 return array( 'error' => $noerr,
545 'link' => $hash_link,
546 'delete_link' => $delete_link_code,
547 'crypt_key' => $crypt_key);
548 }
549
550 /**
551 * Tells if a mime-type is viewable in a browser
552 * @param $mime the mime type
553 * @returns a boolean telling if a mime type is viewable
554 */
555 function jirafeau_is_viewable($mime)
556 {
557 if (!empty($mime)) {
558 $viewable = array('image', 'video', 'audio');
559 $decomposed = explode('/', $mime);
560 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
561 return true;
562 }
563 $viewable = array('text/plain');
564 if (in_array($mime, $viewable)) {
565 return true;
566 }
567 }
568 return false;
569 }
570
571 // Error handling functions.
572 //! Global array that contains all registered errors.
573 $error_list = array();
574
575 /**
576 * Adds an error to the list of errors.
577 * @param $title the error's title
578 * @param $description is a human-friendly description of the problem.
579 */
580 function add_error($title, $description)
581 {
582 global $error_list;
583 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
584 }
585
586 /**
587 * Informs whether any error has been registered yet.
588 * @return true if there are errors.
589 */
590 function has_error()
591 {
592 global $error_list;
593 return !empty($error_list);
594 }
595
596 /**
597 * Displays all the errors.
598 */
599 function show_errors()
600 {
601 if (has_error()) {
602 global $error_list;
603 echo '<div class="error">';
604 foreach ($error_list as $error) {
605 echo $error;
606 }
607 echo '</div>';
608 }
609 }
610
611 function check_errors($cfg)
612 {
613 if (!($cfg['installation_done'] === true)) {
614 if (file_exists(JIRAFEAU_ROOT . 'install.php')) {
615 header('Location: install.php');
616 exit;
617 } else {
618 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
619 }
620 }
621
622 if (!is_writable(VAR_FILES)) {
623 add_error(t('FILE_DIR_W'), VAR_FILES);
624 }
625
626 if (!is_writable(VAR_LINKS)) {
627 add_error(t('LINK_DIR_W'), VAR_LINKS);
628 }
629
630 if (!is_writable(VAR_ASYNC)) {
631 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
632 }
633
634 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
635 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
636 }
637
638 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
639 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
640 }
641 }
642
643 /**
644 * Read link information
645 * @return array containing information.
646 */
647 function jirafeau_get_link($hash)
648 {
649 $out = array();
650 $link = VAR_LINKS . s2p("$hash") . $hash;
651
652 if (!file_exists($link)) {
653 return $out;
654 }
655
656 $c = file($link);
657 $out['file_name'] = trim($c[0]);
658 $out['mime_type'] = trim($c[1]);
659 $out['file_size'] = trim($c[2]);
660 $out['key'] = trim($c[3], NL);
661 $out['time'] = trim($c[4]);
662 $out['hash'] = trim($c[5]);
663 $out['onetime'] = trim($c[6]);
664 $out['upload_date'] = trim($c[7]);
665 $out['ip'] = trim($c[8]);
666 $out['link_code'] = trim($c[9]);
667 $out['crypted'] = trim($c[10]) == 'C';
668
669 return $out;
670 }
671
672 /**
673 * List files in admin interface.
674 */
675 function jirafeau_admin_list($name, $file_hash, $link_hash)
676 {
677 echo '<fieldset><legend>';
678 if (!empty($name)) {
679 echo t('FILENAME') . ": " . jirafeau_escape($name);
680 }
681 if (!empty($file_hash)) {
682 echo t('FILE') . ": " . jirafeau_escape($file_hash);
683 }
684 if (!empty($link_hash)) {
685 echo t('LINK') . ": " . jirafeau_escape($link_hash);
686 }
687 if (empty($name) && empty($file_hash) && empty($link_hash)) {
688 echo t('LS_FILES');
689 }
690 echo '</legend>';
691 echo '<table>';
692 echo '<tr>';
693 echo '<th></th>';
694 echo '<th>' . t('ACTION') . '</th>';
695 echo '</tr>';
696
697 /* Get all links files. */
698 $stack = array(VAR_LINKS);
699 while (($d = array_shift($stack)) && $d != null) {
700 $dir = scandir($d);
701 foreach ($dir as $node) {
702 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
703 preg_match('/\.tmp/i', "$node")) {
704 continue;
705 }
706 if (is_dir($d . $node)) {
707 /* Push new found directory. */
708 $stack[] = $d . $node . '/';
709 } elseif (is_file($d . $node)) {
710 /* Read link information. */
711 $l = jirafeau_get_link($node);
712 if (!count($l)) {
713 continue;
714 }
715 $ld = jirafeau_get_download_stats($node);
716
717 /* Filter. */
718 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
719 continue;
720 }
721 if (!empty($file_hash) && $file_hash != $l['hash']) {
722 continue;
723 }
724 if (!empty($link_hash) && $link_hash != $node) {
725 continue;
726 }
727 /* Print link information. */
728 echo '<tr>';
729 echo '<td>' .
730 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
731 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
732 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
733 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
734 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
735 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ? 'Yes' : 'No') . '<br/>';
736 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
737 if (strlen($l['ip']) > 0) {
738 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
739 }
740 echo t('DOWNLOAD_COUNT') . ': ' . $ld['count'] . '<br/>';
741 if ($ld['count'] > 0) {
742 echo t('DOWNLOAD_DATE') . ': ' . jirafeau_get_datetimefield($ld['date']) . '<br/>';
743 echo t('DOWNLOAD_IP') . ': ' . $ld['ip'] . '<br/>';
744 }
745 echo '</td><td>';
746 echo '<form method="post">' .
747 '<input type = "hidden" name = "action" value = "download"/>' .
748 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
749 jirafeau_admin_csrf_field() .
750 '<input type = "submit" value = "' . t('DL') . '" />' .
751 '</form>' .
752 '<form method="post">' .
753 '<input type = "hidden" name = "action" value = "delete_link"/>' .
754 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
755 jirafeau_admin_csrf_field() .
756 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
757 '</form>' .
758 '<form method="post">' .
759 '<input type = "hidden" name = "action" value = "delete_file"/>' .
760 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
761 jirafeau_admin_csrf_field() .
762 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
763 '</form>' .
764 '</td>';
765 echo '</tr>';
766 }
767 }
768 }
769 echo '</table></fieldset>';
770 }
771
772 /**
773 * Clean expired files.
774 * @return number of cleaned files.
775 */
776 function jirafeau_admin_clean()
777 {
778 $count = 0;
779 /* Get all links files. */
780 $stack = array(VAR_LINKS);
781 while (($d = array_shift($stack)) && $d != null) {
782 $dir = scandir($d);
783
784 foreach ($dir as $node) {
785 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
786 preg_match('/\.tmp/i', "$node")) {
787 continue;
788 }
789
790 if (is_dir($d . $node)) {
791 /* Push new found directory. */
792 $stack[] = $d . $node . '/';
793 } elseif (is_file($d . $node)) {
794 /* Read link information. */
795 $l = jirafeau_get_link(basename($node));
796 if (!count($l)) {
797 continue;
798 }
799 $p = s2p($l['hash']);
800 if ($l['time'] > 0 && $l['time'] < time() || // expired
801 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
802 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
803 jirafeau_delete_link($node);
804 $count++;
805 }
806 }
807 }
808 }
809 return $count;
810 }
811
812
813 /**
814 * Clean old async transfers.
815 * @return number of cleaned files.
816 */
817 function jirafeau_admin_clean_async()
818 {
819 $count = 0;
820 /* Get all links files. */
821 $stack = array(VAR_ASYNC);
822 while (($d = array_shift($stack)) && $d != null) {
823 $dir = scandir($d);
824
825 foreach ($dir as $node) {
826 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
827 preg_match('/\.tmp/i', "$node")) {
828 continue;
829 }
830
831 if (is_dir($d . $node)) {
832 /* Push new found directory. */
833 $stack[] = $d . $node . '/';
834 } elseif (is_file($d . $node)) {
835 /* Read async information. */
836 $a = jirafeau_get_async_ref(basename($node));
837 if (!count($a)) {
838 continue;
839 }
840 /* Delete transfers older than 1 hour. */
841 if (time() - $a['last_edited'] > 3600) {
842 jirafeau_async_delete(basename($node));
843 $count++;
844 }
845 }
846 }
847 }
848 return $count;
849 }
850
851 /**
852 * Better strval function for debug purposes
853 */
854 function jirafeau_strval($value)
855 {
856 if (gettype($value) == "boolean") {
857 return $value ? 'true' : 'false';
858 }
859 return strval($value);
860 }
861
862 /**
863 * Show file/folder permissions
864 */
865 function jirafeau_fileperms($path)
866 {
867 $out = substr(sprintf("%o", @fileperms($path)), -4) . ", ";
868 $out .= "read " . (is_readable($path) ? "OK" : "KO") . ", ";
869 $out .= "write " . (is_writable($path) ? "OK" : "KO");
870 return $out;
871 }
872
873 /**
874 * Show some useful informations for bug reporting.
875 */
876 function jirafeau_admin_bug_report($cfg)
877 {
878 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
879 $out .= "If you have a problem related to Jirafeau, please <a href='https://gitlab.com/mojo42/Jirafeau/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>";
880
881 $out .= "# Jirafeau<br/>";
882 $out .= "- version: " . JIRAFEAU_VERSION . "<br/>";
883 $jirafeau_options = [
884 'debug',
885 'file_hash',
886 'litespeed_workaround',
887 'store_uploader_ip',
888 'installation_done',
889 'enable_crypt',
890 'preview',
891 'maximal_upload_size',
892 'store_uploader_ip',
893 'max_upload_chunk_size_bytes'
894 ];
895 foreach ($jirafeau_options as &$o) {
896 $v = $cfg[$o];
897 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
898 }
899 $out .= "<br/>";
900
901 $out .= "# PHP options<br/>";
902 $out .= "- php version: " . phpversion() . "<br/>";
903 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
904 $php_options = [
905 'post_max_size',
906 'upload_max_filesize',
907 'safe_mode',
908 'max_execution_time',
909 'max_input_time'
910 ];
911 foreach ($php_options as &$o) {
912 $v = ini_get($o);
913 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
914 }
915 $out .= "- can set_time_limit: " . (set_time_limit(0) ? "yes" : "no") . "<br/>";
916 $out .= "<br/>";
917
918 $out .= "# File permissions<br/>";
919 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
920 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES) . "<br/>";
921 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS) . "<br/>";
922 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC) . "<br/>";
923 $out .= "<br/>";
924
925 $out .= "# Server details<br/>";
926 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
927 $out .= "<br/>";
928
929 $out .= "# OS details<br/>";
930 $out .= "- OS: " . php_uname() . "<br/>";
931 $out .= "<br/>";
932
933 $out .= "# Browser details<br/>";
934 $out .= "<script type='text/javascript' lang='Javascript'>
935 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
936 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
937 document.write('- user agent: ' + navigator.userAgent + '<br/>');
938 // @license-end
939 </script>";
940 $out .= "<br/>";
941
942 $out .= "# Memory<br/>";
943 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
944
945 $out .= "</code></fieldset>";
946 return $out;
947 }
948
949 /**
950 * Read async transfer information
951 * @return array containing information.
952 */
953 function jirafeau_get_async_ref($ref)
954 {
955 $out = array();
956 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
957
958 if (!file_exists($refinfos)) {
959 return $out;
960 }
961
962 $c = file($refinfos);
963 $out['file_name'] = trim($c[0]);
964 $out['mime_type'] = trim($c[1]);
965 $out['key'] = trim($c[2], NL);
966 $out['time'] = trim($c[3]);
967 $out['onetime'] = trim($c[4]);
968 $out['ip'] = trim($c[5]);
969 $out['last_edited'] = trim($c[6]);
970 $out['next_code'] = trim($c[7]);
971 return $out;
972 }
973
974 /**
975 * Delete async transfer information
976 */
977 function jirafeau_async_delete($ref)
978 {
979 $p = s2p("$ref");
980 if (file_exists(VAR_ASYNC . $p . $ref)) {
981 unlink(VAR_ASYNC . $p . $ref);
982 }
983 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
984 unlink(VAR_ASYNC . $p . $ref . '_data');
985 }
986 $parse = VAR_ASYNC . $p;
987 $scan = array();
988 while (file_exists($parse)
989 && ($scan = scandir($parse))
990 && count($scan) == 2 // '.' and '..' folders => empty.
991 && basename($parse) != basename(VAR_ASYNC)) {
992 rmdir($parse);
993 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
994 }
995 }
996
997 /**
998 * Init a new asynchronous upload.
999 * @param $filename Name of the file to send
1000 * @param $one_time One time upload parameter
1001 * @param $key eventual password (or blank)
1002 * @param $time time limit
1003 * @param $ip ip address of the client
1004 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1005 */
1006 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1007 {
1008 /* Create temporary folder. */
1009 $ref;
1010 $p;
1011 $code = jirafeau_gen_random(4);
1012 do {
1013 $ref = jirafeau_gen_random(32);
1014 $p = VAR_ASYNC . s2p($ref);
1015 } while (file_exists($p));
1016 @mkdir($p, 0755, true);
1017 if (!file_exists($p)) {
1018 return 'Error: cannot create async folder.';
1019 }
1020
1021 /* touch empty data file */
1022 $w_path = $p . $ref . '_data';
1023 touch($w_path);
1024
1025 /* md5 password or empty */
1026 $password = '';
1027 if (!empty($key)) {
1028 $password = md5($key);
1029 }
1030
1031 /* Store information. */
1032 $p .= $ref;
1033 $handle = fopen($p, 'w');
1034 fwrite(
1035 $handle,
1036 str_replace(NL, '', trim($filename)) . NL .
1037 str_replace(NL, '', trim($type)) . NL . $password . NL .
1038 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
1039 time() . NL . $code . NL
1040 );
1041 fclose($handle);
1042
1043 return $ref . NL . $code ;
1044 }
1045
1046 /**
1047 * Append a piece of file on the asynchronous upload.
1048 * @param $ref asynchronous upload reference
1049 * @param $file piece of data
1050 * @param $code client code for this operation
1051 * @param $max_file_size maximum allowed file size
1052 * @return a string containing a next code to use or a string starting with 'Error'
1053 */
1054 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1055 {
1056 /* Get async infos. */
1057 $a = jirafeau_get_async_ref($ref);
1058
1059 /* Check some errors. */
1060 if (count($a) == 0) {
1061 return "Error: cannot find transfer";
1062 }
1063 if ($a['next_code'] != "$code") {
1064 return "Error: bad transfer code";
1065 }
1066 if ($data['error'] != UPLOAD_ERR_OK) {
1067 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1068 $data_details = print_r($data, true);
1069 return "Error: upload error: {$data_details}";
1070 }
1071 if (empty($data['tmp_name'])) {
1072 return "Error: missing tmp_name";
1073 }
1074 if (!is_uploaded_file($data['tmp_name'])) {
1075 return "Error: tmp_name may not be uploaded";
1076 }
1077
1078 $p = s2p($ref);
1079
1080 /* File path. */
1081 $r_path = $data['tmp_name'];
1082 $w_path = VAR_ASYNC . $p . $ref . '_data';
1083
1084 /* Check that file size is not above upload limit. */
1085 if ($max_file_size > 0 &&
1086 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
1087 jirafeau_async_delete($ref);
1088 return "Error: file size is above upload limit";
1089 }
1090
1091 /* Concatenate data. */
1092 $r = fopen($r_path, 'r');
1093 $w = fopen($w_path, 'a');
1094 while (!feof($r)) {
1095 if (fwrite($w, fread($r, 1024)) === false) {
1096 fclose($r);
1097 fclose($w);
1098 jirafeau_async_delete($ref);
1099 return "Error: cannot write file";
1100 }
1101 }
1102 fclose($r);
1103 fclose($w);
1104 unlink($r_path);
1105
1106 /* Update async file. */
1107 $code = jirafeau_gen_random(4);
1108 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
1109 fwrite(
1110 $handle,
1111 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
1112 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
1113 time() . NL . $code . NL
1114 );
1115 fclose($handle);
1116 return $code;
1117 }
1118
1119 /**
1120 * Finalize an asynchronous upload.
1121 * @param $ref asynchronous upload reference
1122 * @param $code client code for this operation
1123 * @param $crypt boolean asking to crypt or not
1124 * @param $link_name_length link name length
1125 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1126 */
1127 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1128 {
1129 /* Get async infos. */
1130 $a = jirafeau_get_async_ref($ref);
1131 if (count($a) == 0
1132 || $a['next_code'] != "$code") {
1133 return "Error: bad code for ending transfer";
1134 }
1135
1136 /* Generate link infos. */
1137 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
1138 if (!file_exists($p)) {
1139 return "Error: referenced file does not exist";
1140 }
1141
1142 $crypted = false;
1143 $crypt_key = '';
1144 if ($crypt == true && extension_loaded('mcrypt') == true) {
1145 $crypt_key = jirafeau_encrypt_file($p, $p);
1146 if (strlen($crypt_key) > 0) {
1147 $crypted = true;
1148 }
1149 }
1150
1151 $hash = jirafeau_hash_file($file_hash_method, $p);
1152 $size = filesize($p);
1153 $np = s2p($hash);
1154 $delete_link_code = jirafeau_gen_random(5);
1155
1156 /* File already exist ? */
1157 if (!file_exists(VAR_FILES . $np)) {
1158 @mkdir(VAR_FILES . $np, 0755, true);
1159 }
1160 if (!file_exists(VAR_FILES . $np . $hash)) {
1161 rename($p, VAR_FILES . $np . $hash);
1162 }
1163
1164 /* Increment or create count file. */
1165 $counter = 0;
1166 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
1167 $content = file(VAR_FILES . $np . $hash. '_count');
1168 $counter = trim($content[0]);
1169 }
1170 $counter++;
1171 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
1172 fwrite($handle, $counter);
1173 fclose($handle);
1174
1175 /* Create link. */
1176 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
1177 $handle = fopen($link_tmp_name, 'w');
1178 fwrite(
1179 $handle,
1180 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
1181 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
1182 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O')
1183 );
1184 fclose($handle);
1185 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1186 $l = s2p("$hash_link");
1187 if (!@mkdir(VAR_LINKS . $l, 0755, true)) {
1188 return "Error: cannot create folder in LINKS";
1189 }
1190 if (!rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
1191 return "Error: cannot rename file in LINKS";
1192 }
1193
1194 /* Clean async upload. */
1195 jirafeau_async_delete($ref);
1196 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1197 }
1198
1199 function jirafeau_crypt_create_iv($base, $size)
1200 {
1201 $iv = '';
1202 while (strlen($iv) < $size) {
1203 $iv = $iv . $base;
1204 }
1205 $iv = substr($iv, 0, $size);
1206 return $iv;
1207 }
1208
1209 /**
1210 * Crypt file and returns decrypt key.
1211 * @param $fp_src file path to the file to crypt.
1212 * @param $fp_dst file path to the file to write crypted file (could be the same).
1213 * @return decrypt key composed of the key and the iv separated by a point ('.')
1214 */
1215 function jirafeau_encrypt_file($fp_src, $fp_dst)
1216 {
1217 $fs = filesize($fp_src);
1218 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true)) {
1219 return '';
1220 }
1221
1222 /* Prepare module. */
1223 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1224 /* Generate key. */
1225 $crypt_key = jirafeau_gen_random(10);
1226 $hash_key = md5($crypt_key);
1227 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1228 /* Init module. */
1229 mcrypt_generic_init($m, $hash_key, $iv);
1230 /* Crypt file. */
1231 $r = fopen($fp_src, 'r');
1232 $w = fopen($fp_dst, 'c');
1233 while (!feof($r)) {
1234 $to_enc = fread($r, 1024);
1235 if (strlen($to_enc) > 0) {
1236 $enc = mcrypt_generic($m, $to_enc);
1237 if (fwrite($w, $enc) === false) {
1238 return '';
1239 }
1240 }
1241 }
1242 fclose($r);
1243 fclose($w);
1244 /* Cleanup. */
1245 mcrypt_generic_deinit($m);
1246 mcrypt_module_close($m);
1247 return $crypt_key;
1248 }
1249
1250 /**
1251 * Decrypt file.
1252 * @param $fp_src file path to the file to decrypt.
1253 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1254 * @param $k string composed of the key and the iv separated by a point ('.')
1255 * @return key used to decrypt. a string of length 0 is returned if failed.
1256 */
1257 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1258 {
1259 $fs = filesize($fp_src);
1260 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1261 return false;
1262 }
1263
1264 /* Init module */
1265 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1266 /* Extract key and iv. */
1267 $crypt_key = $k;
1268 $hash_key = md5($crypt_key);
1269 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1270 /* Decrypt file. */
1271 $r = fopen($fp_src, 'r');
1272 $w = fopen($fp_dst, 'c');
1273 while (!feof($r)) {
1274 $dec = mdecrypt_generic($m, fread($r, 1024));
1275 if (fwrite($w, $dec) === false) {
1276 return false;
1277 }
1278 }
1279 fclose($r);
1280 fclose($w);
1281 /* Cleanup. */
1282 mcrypt_generic_deinit($m);
1283 mcrypt_module_close($m);
1284 return true;
1285 }
1286
1287 /**
1288 * Check if Jirafeau is password protected for visitors.
1289 * @return true if Jirafeau is password protected, false otherwise.
1290 */
1291 function jirafeau_has_upload_password($cfg)
1292 {
1293 return count($cfg['upload_password']) > 0;
1294 }
1295
1296 /**
1297 * Challenge password for a visitor.
1298 * @param $password password to be challenged
1299 * @return true if password is valid, false otherwise.
1300 */
1301 function jirafeau_challenge_upload_password($cfg, $password)
1302 {
1303 if (!jirafeau_has_upload_password($cfg)) {
1304 return false;
1305 }
1306 foreach ($cfg['upload_password'] as $p) {
1307 if ($password == $p) {
1308 return true;
1309 }
1310 }
1311 return false;
1312 }
1313
1314 /**
1315 * Test if the given IP is whitelisted by the given list.
1316 *
1317 * @param $allowedIpList array of allowed IPs
1318 * @param $challengedIp IP to be challenged
1319 * @return true if IP is authorized, false otherwise.
1320 */
1321 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1322 {
1323 foreach ($allowedIpList as $i) {
1324 if ($i == $challengedIp) {
1325 return true;
1326 }
1327 // CIDR test for IPv4 only.
1328 if (strpos($i, '/') !== false) {
1329 list($subnet, $mask) = explode('/', $i);
1330 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1331 return true;
1332 }
1333 }
1334 }
1335 return false;
1336 }
1337
1338 /**
1339 * Check if Jirafeau has a restriction on the IP address for uploading.
1340 * @return true if uploading is IP restricted, false otherwise.
1341 */
1342 function jirafeau_upload_has_ip_restriction($cfg)
1343 {
1344 return count($cfg['upload_ip']) > 0;
1345 }
1346
1347 /**
1348 * Test if visitor's IP is authorized to upload at all.
1349 *
1350 * @param $cfg configuration
1351 * @param $challengedIp IP to be challenged
1352 * @return true if IP is authorized, false otherwise.
1353 */
1354 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1355 {
1356 // If no IP address have been listed, allow upload from any IP
1357 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1358 return true;
1359 }
1360 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1361 }
1362
1363 /**
1364 * Test if visitor's IP is authorized to upload without a password.
1365 *
1366 * @param $cfg configuration
1367 * @param $challengedIp IP to be challenged
1368 * @return true if IP is authorized, false otherwise.
1369 */
1370 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1371 {
1372 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1373 }
1374
1375 /**
1376 * Test if visitor's IP is authorized or password is supplied and authorized
1377 * @param $ip IP to be challenged
1378 * @param $password password to be challenged
1379 * @return true if access is valid, false otherwise.
1380 */
1381 function jirafeau_challenge_upload($cfg, $ip, $password)
1382 {
1383 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1384 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1385 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1386 }
1387
1388 /**
1389 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1390 * @return true if admin interface is IP restricted, false otherwise.
1391 */
1392 function jirafeau_admin_has_ip_restriction($cfg)
1393 {
1394 return count($cfg['admin_ip']) > 0;
1395 }
1396
1397 /**
1398 * Test if visitor's IP is authorized to access the admin interface.
1399 *
1400 * @param $cfg configuration
1401 * @param $challengedIp IP to be challenged
1402 * @return true if IP is authorized, false otherwise.
1403 */
1404 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1405 {
1406 // If no IP address have been listed, allow upload from any IP
1407 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1408 return true;
1409 }
1410 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1411 }
1412
1413 /** Tell if we have some HTTP headers generated by a proxy */
1414 function has_http_forwarded()
1415 {
1416 return
1417 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1418 !empty($_SERVER['http_X_forwarded_for']);
1419 }
1420
1421 /**
1422 * Generate IP list from HTTP headers generated by a proxy
1423 * @return array of IP strings
1424 */
1425 function get_ip_list_http_forwarded()
1426 {
1427 $ip_list = array();
1428 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1429 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1430 if ($l === false) {
1431 return array();
1432 }
1433 foreach ($l as $ip) {
1434 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1435 }
1436 }
1437 if (!empty($_SERVER['http_X_forwarded_for'])) {
1438 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1439 foreach ($l as $ip) {
1440 // Separate IP from port
1441 $ipa = explode(':', $ip);
1442 if ($ipa === false) {
1443 continue;
1444 }
1445 $ip = $ipa[0];
1446 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1447 }
1448 }
1449 return $ip_list;
1450 }
1451
1452 /**
1453 * Get the ip address of the client from REMOTE_ADDR
1454 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1455 * @returns the client ip address
1456 */
1457 function get_ip_address($cfg)
1458 {
1459 $remote = $_SERVER['REMOTE_ADDR'];
1460 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1461 return $remote;
1462 }
1463
1464 $ip_list = get_ip_list_http_forwarded();
1465 if (count($ip_list) == 0) {
1466 return $remote;
1467 }
1468
1469 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1470 if ($remote != $proxy_ip) {
1471 continue;
1472 }
1473 // Take the last IP (the one which has been set by the defined proxy).
1474 return end($ip_list);
1475 }
1476 return $remote;
1477 }
1478
1479 /**
1480 * Convert hexadecimal string to base64
1481 */
1482 function hex_to_base64($hex)
1483 {
1484 $b = '';
1485 foreach (str_split($hex, 2) as $pair) {
1486 $b .= chr(hexdec($pair));
1487 }
1488 return base64_encode($b);
1489 }
1490
1491 /**
1492 * Replace markers in templates.
1493 *
1494 * Available markers have the scheme "###MARKERNAME###".
1495 *
1496 * @param $content string Template text with markers
1497 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1498 * @return Template with replaced markers
1499 */
1500 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1501 {
1502 $patterns = array(
1503 '/###ORGANISATION###/',
1504 '/###CONTACTPERSON###/',
1505 '/###WEBROOT###/'
1506 );
1507 $replacements = array(
1508 $GLOBALS['cfg']['organisation'],
1509 $GLOBALS['cfg']['contactperson'],
1510 $GLOBALS['cfg']['web_root']
1511 );
1512 $content = preg_replace($patterns, $replacements, $content);
1513
1514 if (true === $htmllinebreaks) {
1515 $content = nl2br($content);
1516 }
1517
1518 return $content;
1519 }
1520
1521 function jirafeau_escape($string)
1522 {
1523 return htmlspecialchars($string, ENT_QUOTES);
1524 }
1525
1526 function jirafeau_admin_session_start()
1527 {
1528 $_SESSION['admin_auth'] = true;
1529 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1530 }
1531
1532 function jirafeau_session_end()
1533 {
1534 $_SESSION = array();
1535 session_destroy();
1536 }
1537
1538 function jirafeau_admin_session_logged()
1539 {
1540 return isset($_SESSION['admin_auth']) &&
1541 isset($_SESSION['admin_csrf']) &&
1542 isset($_POST['admin_csrf']) &&
1543 $_SESSION['admin_auth'] === true &&
1544 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1545 }
1546
1547 function jirafeau_admin_csrf_field()
1548 {
1549 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1550 }
1551
1552 function jirafeau_user_session_start()
1553 {
1554 $_SESSION['user_auth'] = true;
1555 }
1556
1557 function jirafeau_user_session_logged()
1558 {
1559 return isset($_SESSION['user_auth']) &&
1560 $_SESSION['user_auth'] === true;
1561 }
1562
1563 function jirafeau_dir_size($dir)
1564 {
1565 $size = 0;
1566 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $entry) {
1567 $size += is_file($entry) ? filesize($entry) : jirafeau_dir_size($entry);
1568 }
1569 return $size;
1570 }
1571
1572 function jirafeau_export_cfg($cfg)
1573 {
1574 $content = '<?php' . NL;
1575 $content .= '/* This file was generated by the install process. ' .
1576 'You can edit it. Please see config.original.php to understand the ' .
1577 'configuration items. */' . NL;
1578 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1579
1580 $fileWrite = file_put_contents(JIRAFEAU_CFG, $content);
1581
1582 if (false === $fileWrite) {
1583 jirafeau_fatal_error(t('Can not write local configuration file'));
1584 }
1585 }
1586
1587 function jirafeau_mkdir($path)
1588 {
1589 return !(!file_exists($path) && !@mkdir($path, 0755));
1590 }
1591
1592 /**
1593 * Returns true whether the path is writable or we manage to make it
1594 * so, which essentially is the same thing.
1595 * @param $path is the file or directory to be tested.
1596 * @return true if $path is writable.
1597 */
1598 function jirafeau_is_writable($path)
1599 {
1600 /* "@" gets rid of error messages. */
1601 return is_writable($path) || @chmod($path, 0777);
1602 }
1603
1604 function jirafeau_check_var_dir($path)
1605 {
1606 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1607 $mkdir_str2 = t('MANUAL_CREATE');
1608 $write_str1 = t('DIR_NOT_W') . ':';
1609 $write_str2 = t('You should give the write permission to the web server on ' .
1610 'this directory.');
1611 $solution_str = t('HERE_SOLUTION') . ':';
1612
1613 if (!jirafeau_mkdir($path) || !jirafeau_is_writable($path)) {
1614 return array('has_error' => true,
1615 'why' => $mkdir_str1 . '<br /><code>' .
1616 $path . '</code><br />' . $solution_str .
1617 '<br />' . $mkdir_str2);
1618 }
1619
1620 foreach (array('files', 'links', 'async') as $subdir) {
1621 $subpath = $path.$subdir;
1622
1623 if (!jirafeau_mkdir($subpath) || !jirafeau_is_writable($subpath)) {
1624 return array('has_error' => true,
1625 'why' => $mkdir_str1 . '<br /><code>' .
1626 $subpath . '</code><br />' . $solution_str .
1627 '<br />' . $mkdir_str2);
1628 }
1629 }
1630
1631 return array('has_error' => false, 'why' => '');
1632 }
1633
1634 function jirafeau_add_ending_slash($path)
1635 {
1636 return $path . ((substr($path, -1) == '/') ? '' : '/');
1637 }
1638
1639 function jirafeau_default_web_root()
1640 {
1641 return $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1642 }
1643
1644 function jirafeau_get_download_stats($hash)
1645 {
1646 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1647
1648 if (!file_exists($filename)) {
1649 return array('count'=>0);
1650 }
1651
1652 $c = file($filename);
1653 $data['count'] = trim($c[0]);
1654 $data['date'] = trim($c[1]);
1655 $data['ip'] = trim($c[2]);
1656
1657 return $data;
1658 }
1659
1660 function jirafeau_write_download_stats($hash, $ip)
1661 {
1662 $data = jirafeau_get_download_stats($hash);
1663 $count = $data['count'];
1664 $count++;
1665
1666 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1667
1668 $handle = fopen($filename, 'w');
1669 fwrite($handle, $count . NL . time() . NL . $ip);
1670 fclose($handle);
1671 }

patrick-canterino.de