]> git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
805b958723aa6565148c397ccf5849b2709abbd2
[jirafeau_mojo42.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('sodium') == true)) {
458 error_log("PHP extension sodium not loaded, won't encrypt in Jirafeau");
459 }
460 if ($crypt == true && extension_loaded('sodium') == true) {
461 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name'].'crypt');
462 if (strlen($crypt_key) > 0) {
463 if (rename($file['tmp_name'].'crypt', $file['tmp_name']) === true) {
464 $crypted = true;
465 }
466 }
467 }
468
469 /* file information */
470 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
471 $name = str_replace(NL, '', trim($file['name']));
472 $mime_type = $file['type'];
473 $size = $file['size'];
474
475 /* does file already exist ? */
476 $rc = false;
477 $p = s2p("$hash");
478 if (file_exists(VAR_FILES . $p . $hash)) {
479 $rc = unlink($file['tmp_name']);
480 } elseif ((file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true))
481 && move_uploaded_file($file['tmp_name'], VAR_FILES . $p . $hash)) {
482 $rc = true;
483 }
484 if (!$rc) {
485 return (array(
486 'error' =>
487 array('has_error' => true,
488 'why' => t('INTERNAL_ERROR_DEL')),
489 'link' =>'',
490 'delete_link' => ''));
491 }
492
493 /* Increment or create count file. */
494 $counter = 0;
495 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
496 $content = file(VAR_FILES . $p . $hash. '_count');
497 $counter = trim($content[0]);
498 }
499 $counter++;
500 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
501 fwrite($handle, $counter);
502 fclose($handle);
503
504 /* Create delete code. */
505 $delete_link_code = jirafeau_gen_random(5);
506
507 /* hash password or empty. */
508 $password = '';
509 if (!empty($key)) {
510 $password = md5($key);
511 }
512
513 /* create link file */
514 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
515 $handle = fopen($link_tmp_name, 'w');
516 fwrite(
517 $handle,
518 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
519 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
520 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C2' : 'O')
521 );
522 fclose($handle);
523 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
524 $l = s2p("$hash_link");
525 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
526 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
527 if (file_exists($link_tmp_name)) {
528 unlink($link_tmp_name);
529 }
530
531 $counter--;
532 if ($counter >= 1) {
533 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
534 fwrite($handle, $counter);
535 fclose($handle);
536 } else {
537 jirafeau_clean_rm_file($hash_link);
538 }
539 return array(
540 'error' =>
541 array('has_error' => true,
542 'why' => t('Internal error during file creation. ')),
543 'link' =>'',
544 'delete_link' => '');
545 }
546 return array( 'error' => $noerr,
547 'link' => $hash_link,
548 'delete_link' => $delete_link_code,
549 'crypt_key' => $crypt_key);
550 }
551
552 /**
553 * Tells if a mime-type is viewable in a browser
554 * @param $mime the mime type
555 * @returns a boolean telling if a mime type is viewable
556 */
557 function jirafeau_is_viewable($mime)
558 {
559 if (!empty($mime)) {
560 $viewable = array('image', 'video', 'audio');
561 $decomposed = explode('/', $mime);
562 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
563 return true;
564 }
565 $viewable = array('text/plain');
566 if (in_array($mime, $viewable)) {
567 return true;
568 }
569 }
570 return false;
571 }
572
573 // Error handling functions.
574 //! Global array that contains all registered errors.
575 $error_list = array();
576
577 /**
578 * Adds an error to the list of errors.
579 * @param $title the error's title
580 * @param $description is a human-friendly description of the problem.
581 */
582 function add_error($title, $description)
583 {
584 global $error_list;
585 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
586 }
587
588 /**
589 * Informs whether any error has been registered yet.
590 * @return true if there are errors.
591 */
592 function has_error()
593 {
594 global $error_list;
595 return !empty($error_list);
596 }
597
598 /**
599 * Displays all the errors.
600 */
601 function show_errors()
602 {
603 if (has_error()) {
604 global $error_list;
605 echo '<div class="error">';
606 foreach ($error_list as $error) {
607 echo $error;
608 }
609 echo '</div>';
610 }
611 }
612
613 function check_errors($cfg)
614 {
615 if (!($cfg['installation_done'] === true)) {
616 if (file_exists(JIRAFEAU_ROOT . 'install.php')) {
617 header('Location: install.php');
618 exit;
619 } else {
620 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
621 }
622 }
623
624 if (!is_writable(VAR_FILES)) {
625 add_error(t('FILE_DIR_W'), VAR_FILES);
626 }
627
628 if (!is_writable(VAR_LINKS)) {
629 add_error(t('LINK_DIR_W'), VAR_LINKS);
630 }
631
632 if (!is_writable(VAR_ASYNC)) {
633 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
634 }
635
636 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
637 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
638 }
639
640 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
641 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
642 }
643 }
644
645 /**
646 * Read link information
647 * @return array containing information.
648 */
649 function jirafeau_get_link($hash)
650 {
651 $out = array();
652 $link = VAR_LINKS . s2p("$hash") . $hash;
653
654 if (!file_exists($link)) {
655 return $out;
656 }
657
658 $c = file($link);
659 $out['file_name'] = trim($c[0]);
660 $out['mime_type'] = trim($c[1]);
661 $out['file_size'] = trim($c[2]);
662 $out['key'] = trim($c[3], NL);
663 $out['time'] = trim($c[4]);
664 $out['hash'] = trim($c[5]);
665 $out['onetime'] = trim($c[6]);
666 $out['upload_date'] = trim($c[7]);
667 $out['ip'] = trim($c[8]);
668 $out['link_code'] = trim($c[9]);
669 $out['crypted'] = trim($c[10]) == 'C2';
670 $out['crypted_legacy'] = trim($c[10]) == 'C';
671
672 return $out;
673 }
674
675 /**
676 * List files in admin interface.
677 */
678 function jirafeau_admin_list($name, $file_hash, $link_hash)
679 {
680 echo '<fieldset><legend>';
681 if (!empty($name)) {
682 echo t('FILENAME') . ": " . jirafeau_escape($name);
683 }
684 if (!empty($file_hash)) {
685 echo t('FILE') . ": " . jirafeau_escape($file_hash);
686 }
687 if (!empty($link_hash)) {
688 echo t('LINK') . ": " . jirafeau_escape($link_hash);
689 }
690 if (empty($name) && empty($file_hash) && empty($link_hash)) {
691 echo t('LS_FILES');
692 }
693 echo '</legend>';
694 echo '<table>';
695 echo '<tr>';
696 echo '<th></th>';
697 echo '<th>' . t('ACTION') . '</th>';
698 echo '</tr>';
699
700 /* Get all links files. */
701 $stack = array(VAR_LINKS);
702 while (($d = array_shift($stack)) && $d != null) {
703 $dir = scandir($d);
704 foreach ($dir as $node) {
705 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
706 preg_match('/\.tmp/i', "$node")) {
707 continue;
708 }
709 if (is_dir($d . $node)) {
710 /* Push new found directory. */
711 $stack[] = $d . $node . '/';
712 } elseif (is_file($d . $node)) {
713 /* Read link information. */
714 $l = jirafeau_get_link($node);
715 if (!count($l)) {
716 continue;
717 }
718 $ld = jirafeau_get_download_stats($node);
719
720 /* Filter. */
721 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
722 continue;
723 }
724 if (!empty($file_hash) && $file_hash != $l['hash']) {
725 continue;
726 }
727 if (!empty($link_hash) && $link_hash != $node) {
728 continue;
729 }
730 /* Print link information. */
731 echo '<tr>';
732 echo '<td>' .
733 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
734 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
735 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
736 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
737 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
738 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ? 'Yes' : 'No') . '<br/>';
739 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
740 if (strlen($l['ip']) > 0) {
741 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
742 }
743 echo t('DOWNLOAD_COUNT') . ': ' . $ld['count'] . '<br/>';
744 if ($ld['count'] > 0) {
745 echo t('DOWNLOAD_DATE') . ': ' . jirafeau_get_datetimefield($ld['date']) . '<br/>';
746 echo t('DOWNLOAD_IP') . ': ' . $ld['ip'] . '<br/>';
747 }
748 echo '</td><td>';
749 echo '<form method="post">' .
750 '<input type = "hidden" name = "action" value = "download"/>' .
751 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
752 jirafeau_admin_csrf_field() .
753 '<input type = "submit" value = "' . t('DL') . '" />' .
754 '</form>' .
755 '<form method="post">' .
756 '<input type = "hidden" name = "action" value = "delete_link"/>' .
757 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
758 jirafeau_admin_csrf_field() .
759 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
760 '</form>' .
761 '<form method="post">' .
762 '<input type = "hidden" name = "action" value = "delete_file"/>' .
763 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
764 jirafeau_admin_csrf_field() .
765 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
766 '</form>' .
767 '</td>';
768 echo '</tr>';
769 }
770 }
771 }
772 echo '</table></fieldset>';
773 }
774
775 /**
776 * Clean expired files.
777 * @return number of cleaned files.
778 */
779 function jirafeau_admin_clean()
780 {
781 $count = 0;
782 /* Get all links files. */
783 $stack = array(VAR_LINKS);
784 while (($d = array_shift($stack)) && $d != null) {
785 $dir = scandir($d);
786
787 foreach ($dir as $node) {
788 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
789 preg_match('/\.tmp/i', "$node")) {
790 continue;
791 }
792
793 if (is_dir($d . $node)) {
794 /* Push new found directory. */
795 $stack[] = $d . $node . '/';
796 } elseif (is_file($d . $node)) {
797 /* Read link information. */
798 $l = jirafeau_get_link(basename($node));
799 if (!count($l)) {
800 continue;
801 }
802 $p = s2p($l['hash']);
803 if ($l['time'] > 0 && $l['time'] < time() || // expired
804 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
805 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
806 jirafeau_delete_link($node);
807 $count++;
808 }
809 }
810 }
811 }
812 return $count;
813 }
814
815
816 /**
817 * Clean old async transfers.
818 * @return number of cleaned files.
819 */
820 function jirafeau_admin_clean_async()
821 {
822 $count = 0;
823 /* Get all links files. */
824 $stack = array(VAR_ASYNC);
825 while (($d = array_shift($stack)) && $d != null) {
826 $dir = scandir($d);
827
828 foreach ($dir as $node) {
829 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
830 preg_match('/\.tmp/i', "$node")) {
831 continue;
832 }
833
834 if (is_dir($d . $node)) {
835 /* Push new found directory. */
836 $stack[] = $d . $node . '/';
837 } elseif (is_file($d . $node)) {
838 /* Read async information. */
839 $a = jirafeau_get_async_ref(basename($node));
840 if (!count($a)) {
841 continue;
842 }
843 /* Delete transfers older than 1 hour. */
844 if (time() - $a['last_edited'] > 3600) {
845 jirafeau_async_delete(basename($node));
846 $count++;
847 }
848 }
849 }
850 }
851 return $count;
852 }
853
854 /**
855 * Better strval function for debug purposes
856 */
857 function jirafeau_strval($value)
858 {
859 if (gettype($value) == "boolean") {
860 return $value ? 'true' : 'false';
861 }
862 return strval($value);
863 }
864
865 /**
866 * Show file/folder permissions
867 */
868 function jirafeau_fileperms($path)
869 {
870 $out = substr(sprintf("%o", @fileperms($path)), -4) . ", ";
871 $out .= "read " . (is_readable($path) ? "OK" : "KO") . ", ";
872 $out .= "write " . (is_writable($path) ? "OK" : "KO");
873 return $out;
874 }
875
876 /**
877 * Show some useful informations for bug reporting.
878 */
879 function jirafeau_admin_bug_report($cfg)
880 {
881 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
882 $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>";
883
884 $out .= "# Jirafeau<br/>";
885 $out .= "- version: " . JIRAFEAU_VERSION . "<br/>";
886 $jirafeau_options = [
887 'debug',
888 'file_hash',
889 'litespeed_workaround',
890 'store_uploader_ip',
891 'installation_done',
892 'enable_crypt',
893 'preview',
894 'maximal_upload_size',
895 'store_uploader_ip',
896 'max_upload_chunk_size_bytes'
897 ];
898 foreach ($jirafeau_options as &$o) {
899 $v = $cfg[$o];
900 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
901 }
902 $out .= "<br/>";
903
904 $out .= "# PHP options<br/>";
905 $out .= "- php version: " . phpversion() . "<br/>";
906 $out .= "- sodium version: " . phpversion('sodium') . "<br/>";
907 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
908 $php_options = [
909 'post_max_size',
910 'upload_max_filesize',
911 'safe_mode',
912 'max_execution_time',
913 'max_input_time'
914 ];
915 foreach ($php_options as &$o) {
916 $v = ini_get($o);
917 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
918 }
919 $out .= "- can set_time_limit: " . (set_time_limit(0) ? "yes" : "no") . "<br/>";
920 $out .= "<br/>";
921
922 $out .= "# File permissions<br/>";
923 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
924 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES) . "<br/>";
925 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS) . "<br/>";
926 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC) . "<br/>";
927 $out .= "<br/>";
928
929 $out .= "# Server details<br/>";
930 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
931 $out .= "<br/>";
932
933 $out .= "# OS details<br/>";
934 $out .= "- OS: " . php_uname() . "<br/>";
935 $out .= "<br/>";
936
937 $out .= "# Browser details<br/>";
938 $out .= "<script type='text/javascript' lang='Javascript'>
939 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
940 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
941 document.write('- user agent: ' + navigator.userAgent + '<br/>');
942 // @license-end
943 </script>";
944 $out .= "<br/>";
945
946 $out .= "# Memory<br/>";
947 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
948
949 $out .= "</code></fieldset>";
950 return $out;
951 }
952
953 /**
954 * Read async transfer information
955 * @return array containing information.
956 */
957 function jirafeau_get_async_ref($ref)
958 {
959 $out = array();
960 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
961
962 if (!file_exists($refinfos)) {
963 return $out;
964 }
965
966 $c = file($refinfos);
967 $out['file_name'] = trim($c[0]);
968 $out['mime_type'] = trim($c[1]);
969 $out['key'] = trim($c[2], NL);
970 $out['time'] = trim($c[3]);
971 $out['onetime'] = trim($c[4]);
972 $out['ip'] = trim($c[5]);
973 $out['last_edited'] = trim($c[6]);
974 $out['next_code'] = trim($c[7]);
975 return $out;
976 }
977
978 /**
979 * Delete async transfer information
980 */
981 function jirafeau_async_delete($ref)
982 {
983 $p = s2p("$ref");
984 if (file_exists(VAR_ASYNC . $p . $ref)) {
985 unlink(VAR_ASYNC . $p . $ref);
986 }
987 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
988 unlink(VAR_ASYNC . $p . $ref . '_data');
989 }
990 $parse = VAR_ASYNC . $p;
991 $scan = array();
992 while (file_exists($parse)
993 && ($scan = scandir($parse))
994 && count($scan) == 2 // '.' and '..' folders => empty.
995 && basename($parse) != basename(VAR_ASYNC)) {
996 rmdir($parse);
997 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
998 }
999 }
1000
1001 /**
1002 * Init a new asynchronous upload.
1003 * @param $filename Name of the file to send
1004 * @param $one_time One time upload parameter
1005 * @param $key eventual password (or blank)
1006 * @param $time time limit
1007 * @param $ip ip address of the client
1008 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1009 */
1010 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1011 {
1012 /* Create temporary folder. */
1013 $ref;
1014 $p;
1015 $code = jirafeau_gen_random(4);
1016 do {
1017 $ref = jirafeau_gen_random(32);
1018 $p = VAR_ASYNC . s2p($ref);
1019 } while (file_exists($p));
1020 @mkdir($p, 0755, true);
1021 if (!file_exists($p)) {
1022 return 'Error: cannot create async folder.';
1023 }
1024
1025 /* touch empty data file */
1026 $w_path = $p . $ref . '_data';
1027 touch($w_path);
1028
1029 /* md5 password or empty */
1030 $password = '';
1031 if (!empty($key)) {
1032 $password = md5($key);
1033 }
1034
1035 /* Store information. */
1036 $p .= $ref;
1037 $handle = fopen($p, 'w');
1038 fwrite(
1039 $handle,
1040 str_replace(NL, '', trim($filename)) . NL .
1041 str_replace(NL, '', trim($type)) . NL . $password . NL .
1042 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
1043 time() . NL . $code . NL
1044 );
1045 fclose($handle);
1046
1047 return $ref . NL . $code ;
1048 }
1049
1050 /**
1051 * Append a piece of file on the asynchronous upload.
1052 * @param $ref asynchronous upload reference
1053 * @param $file piece of data
1054 * @param $code client code for this operation
1055 * @param $max_file_size maximum allowed file size
1056 * @return a string containing a next code to use or a string starting with 'Error'
1057 */
1058 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1059 {
1060 /* Get async infos. */
1061 $a = jirafeau_get_async_ref($ref);
1062
1063 /* Check some errors. */
1064 if (count($a) == 0) {
1065 return "Error: cannot find transfer";
1066 }
1067 if ($a['next_code'] != "$code") {
1068 return "Error: bad transfer code";
1069 }
1070 if ($data['error'] != UPLOAD_ERR_OK) {
1071 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1072 $data_details = print_r($data, true);
1073 return "Error: upload error: {$data_details}";
1074 }
1075 if (empty($data['tmp_name'])) {
1076 return "Error: missing tmp_name";
1077 }
1078 if (!is_uploaded_file($data['tmp_name'])) {
1079 return "Error: tmp_name may not be uploaded";
1080 }
1081
1082 $p = s2p($ref);
1083
1084 /* File path. */
1085 $r_path = $data['tmp_name'];
1086 $w_path = VAR_ASYNC . $p . $ref . '_data';
1087
1088 /* Check that file size is not above upload limit. */
1089 if ($max_file_size > 0 &&
1090 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
1091 jirafeau_async_delete($ref);
1092 return "Error: file size is above upload limit";
1093 }
1094
1095 /* Concatenate data. */
1096 $r = fopen($r_path, 'r');
1097 $w = fopen($w_path, 'a');
1098 while (!feof($r)) {
1099 if (fwrite($w, fread($r, 1024)) === false) {
1100 fclose($r);
1101 fclose($w);
1102 jirafeau_async_delete($ref);
1103 return "Error: cannot write file";
1104 }
1105 }
1106 fclose($r);
1107 fclose($w);
1108 unlink($r_path);
1109
1110 /* Update async file. */
1111 $code = jirafeau_gen_random(4);
1112 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
1113 fwrite(
1114 $handle,
1115 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
1116 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
1117 time() . NL . $code . NL
1118 );
1119 fclose($handle);
1120 return $code;
1121 }
1122
1123 /**
1124 * Finalize an asynchronous upload.
1125 * @param $ref asynchronous upload reference
1126 * @param $code client code for this operation
1127 * @param $crypt boolean asking to crypt or not
1128 * @param $link_name_length link name length
1129 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1130 */
1131 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1132 {
1133 /* Get async infos. */
1134 $a = jirafeau_get_async_ref($ref);
1135 if (count($a) == 0
1136 || $a['next_code'] != "$code") {
1137 return "Error: bad code for ending transfer";
1138 }
1139
1140 /* Generate link infos. */
1141 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
1142 if (!file_exists($p)) {
1143 return "Error: referenced file does not exist";
1144 }
1145
1146 $crypted = false;
1147 $crypt_key = '';
1148 if ($crypt == true && extension_loaded('sodium') == true) {
1149 $crypt_key = jirafeau_encrypt_file($p, $p.'.crypt');
1150 if (strlen($crypt_key) > 0) {
1151 if (rename($p.'.crypt', $p) === true) {
1152 $crypted = true;
1153 }
1154 }
1155 }
1156
1157 $hash = jirafeau_hash_file($file_hash_method, $p);
1158 $size = filesize($p);
1159 $np = s2p($hash);
1160 $delete_link_code = jirafeau_gen_random(5);
1161
1162 /* File already exist ? */
1163 if (!file_exists(VAR_FILES . $np)) {
1164 @mkdir(VAR_FILES . $np, 0755, true);
1165 }
1166 if (!file_exists(VAR_FILES . $np . $hash)) {
1167 rename($p, VAR_FILES . $np . $hash);
1168 }
1169
1170 /* Increment or create count file. */
1171 $counter = 0;
1172 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
1173 $content = file(VAR_FILES . $np . $hash. '_count');
1174 $counter = trim($content[0]);
1175 }
1176 $counter++;
1177 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
1178 fwrite($handle, $counter);
1179 fclose($handle);
1180
1181 /* Create link. */
1182 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
1183 $handle = fopen($link_tmp_name, 'w');
1184 fwrite(
1185 $handle,
1186 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
1187 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
1188 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C2' : 'O')
1189 );
1190 fclose($handle);
1191 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1192 $l = s2p("$hash_link");
1193 if (!@mkdir(VAR_LINKS . $l, 0755, true)) {
1194 return "Error: cannot create folder in LINKS";
1195 }
1196 if (!rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
1197 return "Error: cannot rename file in LINKS";
1198 }
1199
1200 /* Clean async upload. */
1201 jirafeau_async_delete($ref);
1202 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1203 }
1204
1205 function jirafeau_crypt_create_iv($base, $size)
1206 {
1207 $iv = '';
1208 while (strlen($iv) < $size) {
1209 $iv = $iv . $base;
1210 }
1211 $iv = substr($iv, 0, $size);
1212 return $iv;
1213 }
1214
1215 /**
1216 * Crypt file and returns decrypt key.
1217 * @param $fp_src file path to the file to crypt.
1218 * @param $fp_dst file path to the file to write crypted file (could be the same).
1219 * @return decrypt key composed of the key and the iv separated by a point ('.')
1220 */
1221 function jirafeau_encrypt_file($fp_src, $fp_dst)
1222 {
1223 $fs = filesize($fp_src);
1224 if ($fs === false || $fs == 0 || !(extension_loaded('sodium') == true)) {
1225 return '';
1226 }
1227
1228 /* Generate key. */
1229 $crypt_key = bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES / 2));
1230 /* Init module. */
1231 [$crypt_state, $crypt_header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($crypt_key);
1232 /* Crypt file. */
1233 $r = fopen($fp_src, 'rb');
1234 $w = fopen($fp_dst, 'wb');
1235 fwrite($w, $crypt_header);
1236
1237 for ($i = 0; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE) {
1238 $to_enc = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE);
1239 $enc = sodium_crypto_secretstream_xchacha20poly1305_push($crypt_state, $to_enc);
1240
1241 if (fwrite($w, $enc) === false) {
1242 return '';
1243 }
1244 }
1245
1246 fclose($r);
1247 fclose($w);
1248
1249 /* Cleanup. */
1250 sodium_memzero($crypt_state);
1251
1252 return $crypt_key;
1253 }
1254
1255 /**
1256 * Decrypt file.
1257 * @param $fp_src file path to the file to decrypt.
1258 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1259 * @param $k string composed of the key and the iv separated by a point ('.')
1260 * @return key used to decrypt. a string of length 0 is returned if failed.
1261 */
1262 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1263 {
1264 $fs = filesize($fp_src);
1265 if ($fs === false || $fs == 0 || extension_loaded('sodium') == false) {
1266 return false;
1267 }
1268
1269 /* Decrypt file. */
1270 $r = fopen(VAR_FILES . $p . $link['hash'], 'rb');
1271
1272 $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);
1273
1274 /* Init module. */
1275 $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $crypt_key);
1276
1277 /* Decrypt file. */
1278
1279 for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES) {
1280 $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
1281 [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
1282 echo $dec;
1283 }
1284
1285 fclose($r);
1286
1287 /* Cleanup. */
1288 sodium_memzero($crypt_state);
1289
1290 return true;
1291 }
1292
1293 /**
1294 * Decrypt file.
1295 * @param $fp_src file path to the file to decrypt.
1296 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1297 * @param $k string composed of the key and the iv separated by a point ('.')
1298 * @return key used to decrypt. a string of length 0 is returned if failed.
1299 */
1300 function jirafeau_decrypt_file_legacy($fp_src, $fp_dst, $k)
1301 {
1302 $fs = filesize($fp_src);
1303 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1304 return false;
1305 }
1306
1307 /* Init module */
1308 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1309 /* Extract key and iv. */
1310 $crypt_key = $k;
1311 $hash_key = md5($crypt_key);
1312 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1313 /* Decrypt file. */
1314 $r = fopen($fp_src, 'r');
1315 $w = fopen($fp_dst, 'c');
1316 while (!feof($r)) {
1317 $dec = mdecrypt_generic($m, fread($r, 1024));
1318 if (fwrite($w, $dec) === false) {
1319 return false;
1320 }
1321 }
1322 fclose($r);
1323 fclose($w);
1324 /* Cleanup. */
1325 mcrypt_generic_deinit($m);
1326 mcrypt_module_close($m);
1327 return true;
1328 }
1329
1330 /**
1331 * Check if Jirafeau is password protected for visitors.
1332 * @return true if Jirafeau is password protected, false otherwise.
1333 */
1334 function jirafeau_has_upload_password($cfg)
1335 {
1336 return count($cfg['upload_password']) > 0;
1337 }
1338
1339 /**
1340 * Challenge password for a visitor.
1341 * @param $password password to be challenged
1342 * @return true if password is valid, false otherwise.
1343 */
1344 function jirafeau_challenge_upload_password($cfg, $password)
1345 {
1346 if (!jirafeau_has_upload_password($cfg)) {
1347 return false;
1348 }
1349 foreach ($cfg['upload_password'] as $p) {
1350 if ($password == $p) {
1351 return true;
1352 }
1353 }
1354 return false;
1355 }
1356
1357 /**
1358 * Test if the given IP is whitelisted by the given list.
1359 *
1360 * @param $allowedIpList array of allowed IPs
1361 * @param $challengedIp IP to be challenged
1362 * @return true if IP is authorized, false otherwise.
1363 */
1364 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1365 {
1366 foreach ($allowedIpList as $i) {
1367 if ($i == $challengedIp) {
1368 return true;
1369 }
1370 // CIDR test for IPv4 only.
1371 if (strpos($i, '/') !== false) {
1372 list($subnet, $mask) = explode('/', $i);
1373 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1374 return true;
1375 }
1376 }
1377 }
1378 return false;
1379 }
1380
1381 /**
1382 * Check if Jirafeau has a restriction on the IP address for uploading.
1383 * @return true if uploading is IP restricted, false otherwise.
1384 */
1385 function jirafeau_upload_has_ip_restriction($cfg)
1386 {
1387 return count($cfg['upload_ip']) > 0;
1388 }
1389
1390 /**
1391 * Test if visitor's IP is authorized to upload at all.
1392 *
1393 * @param $cfg configuration
1394 * @param $challengedIp IP to be challenged
1395 * @return true if IP is authorized, false otherwise.
1396 */
1397 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1398 {
1399 // If no IP address have been listed, allow upload from any IP
1400 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1401 return true;
1402 }
1403 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1404 }
1405
1406 /**
1407 * Test if visitor's IP is authorized to upload without a password.
1408 *
1409 * @param $cfg configuration
1410 * @param $challengedIp IP to be challenged
1411 * @return true if IP is authorized, false otherwise.
1412 */
1413 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1414 {
1415 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1416 }
1417
1418 /**
1419 * Test if visitor's IP is authorized or password is supplied and authorized
1420 * @param $ip IP to be challenged
1421 * @param $password password to be challenged
1422 * @return true if access is valid, false otherwise.
1423 */
1424 function jirafeau_challenge_upload($cfg, $ip, $password)
1425 {
1426 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1427 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1428 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1429 }
1430
1431 /**
1432 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1433 * @return true if admin interface is IP restricted, false otherwise.
1434 */
1435 function jirafeau_admin_has_ip_restriction($cfg)
1436 {
1437 return count($cfg['admin_ip']) > 0;
1438 }
1439
1440 /**
1441 * Test if visitor's IP is authorized to access the admin interface.
1442 *
1443 * @param $cfg configuration
1444 * @param $challengedIp IP to be challenged
1445 * @return true if IP is authorized, false otherwise.
1446 */
1447 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1448 {
1449 // If no IP address have been listed, allow upload from any IP
1450 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1451 return true;
1452 }
1453 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1454 }
1455
1456 /** Tell if we have some HTTP headers generated by a proxy */
1457 function has_http_forwarded()
1458 {
1459 return
1460 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1461 !empty($_SERVER['http_X_forwarded_for']);
1462 }
1463
1464 /**
1465 * Generate IP list from HTTP headers generated by a proxy
1466 * @return array of IP strings
1467 */
1468 function get_ip_list_http_forwarded()
1469 {
1470 $ip_list = array();
1471 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1472 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1473 if ($l === false) {
1474 return array();
1475 }
1476 foreach ($l as $ip) {
1477 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1478 }
1479 }
1480 if (!empty($_SERVER['http_X_forwarded_for'])) {
1481 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1482 foreach ($l as $ip) {
1483 // Separate IP from port
1484 $ipa = explode(':', $ip);
1485 if ($ipa === false) {
1486 continue;
1487 }
1488 $ip = $ipa[0];
1489 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1490 }
1491 }
1492 return $ip_list;
1493 }
1494
1495 /**
1496 * Get the ip address of the client from REMOTE_ADDR
1497 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1498 * @returns the client ip address
1499 */
1500 function get_ip_address($cfg)
1501 {
1502 $remote = $_SERVER['REMOTE_ADDR'];
1503 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1504 return $remote;
1505 }
1506
1507 $ip_list = get_ip_list_http_forwarded();
1508 if (count($ip_list) == 0) {
1509 return $remote;
1510 }
1511
1512 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1513 if ($remote != $proxy_ip) {
1514 continue;
1515 }
1516 // Take the last IP (the one which has been set by the defined proxy).
1517 return end($ip_list);
1518 }
1519 return $remote;
1520 }
1521
1522 /**
1523 * Convert hexadecimal string to base64
1524 */
1525 function hex_to_base64($hex)
1526 {
1527 $b = '';
1528 foreach (str_split($hex, 2) as $pair) {
1529 $b .= chr(hexdec($pair));
1530 }
1531 return base64_encode($b);
1532 }
1533
1534 /**
1535 * Replace markers in templates.
1536 *
1537 * Available markers have the scheme "###MARKERNAME###".
1538 *
1539 * @param $content string Template text with markers
1540 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1541 * @return Template with replaced markers
1542 */
1543 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1544 {
1545 $patterns = array(
1546 '/###ORGANISATION###/',
1547 '/###CONTACTPERSON###/',
1548 '/###WEBROOT###/'
1549 );
1550 $replacements = array(
1551 $GLOBALS['cfg']['organisation'],
1552 $GLOBALS['cfg']['contactperson'],
1553 $GLOBALS['cfg']['web_root']
1554 );
1555 $content = preg_replace($patterns, $replacements, $content);
1556
1557 if (true === $htmllinebreaks) {
1558 $content = nl2br($content);
1559 }
1560
1561 return $content;
1562 }
1563
1564 function jirafeau_escape($string)
1565 {
1566 return htmlspecialchars($string, ENT_QUOTES);
1567 }
1568
1569 function jirafeau_admin_session_start()
1570 {
1571 $_SESSION['admin_auth'] = true;
1572 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1573 }
1574
1575 function jirafeau_session_end()
1576 {
1577 $_SESSION = array();
1578 session_destroy();
1579 }
1580
1581 function jirafeau_admin_session_logged()
1582 {
1583 return isset($_SESSION['admin_auth']) &&
1584 isset($_SESSION['admin_csrf']) &&
1585 isset($_POST['admin_csrf']) &&
1586 $_SESSION['admin_auth'] === true &&
1587 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1588 }
1589
1590 function jirafeau_admin_csrf_field()
1591 {
1592 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1593 }
1594
1595 function jirafeau_user_session_start()
1596 {
1597 $_SESSION['user_auth'] = true;
1598 }
1599
1600 function jirafeau_user_session_logged()
1601 {
1602 return isset($_SESSION['user_auth']) &&
1603 $_SESSION['user_auth'] === true;
1604 }
1605
1606 function jirafeau_dir_size($dir)
1607 {
1608 $size = 0;
1609 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $entry) {
1610 $size += is_file($entry) ? filesize($entry) : jirafeau_dir_size($entry);
1611 }
1612 return $size;
1613 }
1614
1615 function jirafeau_export_cfg($cfg)
1616 {
1617 $content = '<?php' . NL;
1618 $content .= '/* This file was generated by the install process. ' .
1619 'You can edit it. Please see config.original.php to understand the ' .
1620 'configuration items. */' . NL;
1621 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1622
1623 $fileWrite = file_put_contents(JIRAFEAU_CFG, $content);
1624
1625 if (false === $fileWrite) {
1626 jirafeau_fatal_error(t('Can not write local configuration file'));
1627 }
1628 }
1629
1630 function jirafeau_mkdir($path)
1631 {
1632 return !(!file_exists($path) && !@mkdir($path, 0755));
1633 }
1634
1635 /**
1636 * Returns true whether the path is writable or we manage to make it
1637 * so, which essentially is the same thing.
1638 * @param $path is the file or directory to be tested.
1639 * @return true if $path is writable.
1640 */
1641 function jirafeau_is_writable($path)
1642 {
1643 /* "@" gets rid of error messages. */
1644 return is_writable($path) || @chmod($path, 0777);
1645 }
1646
1647 function jirafeau_check_var_dir($path)
1648 {
1649 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1650 $mkdir_str2 = t('MANUAL_CREATE');
1651 $write_str1 = t('DIR_NOT_W') . ':';
1652 $write_str2 = t('You should give the write permission to the web server on ' .
1653 'this directory.');
1654 $solution_str = t('HERE_SOLUTION') . ':';
1655
1656 if (!jirafeau_mkdir($path) || !jirafeau_is_writable($path)) {
1657 return array('has_error' => true,
1658 'why' => $mkdir_str1 . '<br /><code>' .
1659 $path . '</code><br />' . $solution_str .
1660 '<br />' . $mkdir_str2);
1661 }
1662
1663 foreach (array('files', 'links', 'async') as $subdir) {
1664 $subpath = $path.$subdir;
1665
1666 if (!jirafeau_mkdir($subpath) || !jirafeau_is_writable($subpath)) {
1667 return array('has_error' => true,
1668 'why' => $mkdir_str1 . '<br /><code>' .
1669 $subpath . '</code><br />' . $solution_str .
1670 '<br />' . $mkdir_str2);
1671 }
1672 }
1673
1674 return array('has_error' => false, 'why' => '');
1675 }
1676
1677 function jirafeau_add_ending_slash($path)
1678 {
1679 return $path . ((substr($path, -1) == '/') ? '' : '/');
1680 }
1681
1682 function jirafeau_default_web_root()
1683 {
1684 $url_scheme = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
1685 return $url_scheme . $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1686 }
1687
1688 function jirafeau_get_download_stats($hash)
1689 {
1690 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1691
1692 if (!file_exists($filename)) {
1693 return array('count'=>0);
1694 }
1695
1696 $c = file($filename);
1697 $data['count'] = trim($c[0]);
1698 $data['date'] = trim($c[1]);
1699 $data['ip'] = trim($c[2]);
1700
1701 return $data;
1702 }
1703
1704 function jirafeau_write_download_stats($hash, $ip)
1705 {
1706 $data = jirafeau_get_download_stats($hash);
1707 $count = $data['count'];
1708 $count++;
1709
1710 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1711
1712 $handle = fopen($filename, 'w');
1713 fwrite($handle, $count . NL . time() . NL . $ip);
1714 fclose($handle);
1715 }

patrick-canterino.de