]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
Added pipeline for PHP 8.2
[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) 2024 Jirafeau project <https://gitlab.com/jirafeau> (see AUTHORS.md)
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 $ts = date_create('@' . $timestamp);
147 $content = '<span class="datetime" data-datetime="' . date_format($ts, 'Y-m-d H:i') . '">'
148 . date_format($ts, 'Y-m-d H:i') . ' (GMT)</span>';
149
150 return $content;
151 }
152
153 function jirafeau_fatal_error($errorText, $cfg = array())
154 {
155 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
156 require(JIRAFEAU_ROOT . 'lib/template/footer.php');
157 exit;
158 }
159
160 function jirafeau_clean_rm_link($link)
161 {
162 $p = s2p("$link");
163 if (file_exists(VAR_LINKS . $p . $link)) {
164 unlink(VAR_LINKS . $p . $link);
165 }
166 if (file_exists(VAR_LINKS . $p . $link . '_download')) {
167 unlink(VAR_LINKS . $p . $link . '_download');
168 }
169 $parse = VAR_LINKS . $p;
170 $scan = array();
171 while (file_exists($parse)
172 && ($scan = scandir($parse))
173 && count($scan) == 2 // '.' and '..' folders => empty.
174 && basename($parse) != basename(VAR_LINKS)) {
175 rmdir($parse);
176 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
177 }
178 }
179
180 function jirafeau_clean_rm_file($hash)
181 {
182 $p = s2p("$hash");
183 $f = VAR_FILES . $p . $hash;
184 if (file_exists($f) && is_file($f)) {
185 unlink($f);
186 }
187 if (file_exists($f . '_count') && is_file($f . '_count')) {
188 unlink($f . '_count');
189 }
190 $parse = VAR_FILES . $p;
191 $scan = array();
192 while (file_exists($parse)
193 && ($scan = scandir($parse))
194 && count($scan) == 2 // '.' and '..' folders => empty.
195 && basename($parse) != basename(VAR_FILES)) {
196 rmdir($parse);
197 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
198 }
199 }
200
201 /**
202 * transforms a php.ini string representing a value in an integer
203 * @param $value the value from php.ini
204 * @returns an integer for this value
205 */
206 function jirafeau_ini_to_bytes($value)
207 {
208 $modifier = substr($value, -1);
209 $bytes = substr($value, 0, -1);
210 switch (strtoupper($modifier)) {
211 default:
212 return intval($value);
213 break;
214 case 'P':
215 $bytes *= 1024;
216 // no break
217 case 'T':
218 $bytes *= 1024;
219 // no break
220 case 'G':
221 $bytes *= 1024;
222 // no break
223 case 'M':
224 $bytes *= 1024;
225 // no break
226 case 'K':
227 $bytes *= 1024;
228 }
229 return $bytes;
230 }
231
232 /**
233 * gets the maximum upload size according to php.ini
234 * @returns the maximum upload size in bytes
235 */
236 function jirafeau_get_max_upload_size_bytes()
237 {
238 return min(
239 jirafeau_ini_to_bytes(ini_get('post_max_size')),
240 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
241 );
242 }
243
244 /**
245 * gets the maximum upload size according to php.ini
246 * @returns the maximum upload size string
247 */
248 function jirafeau_get_max_upload_size()
249 {
250 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
251 }
252
253 /**
254 * get the maximal upload size for a data chunk in async uploads
255 * @param max_upload_chunk_size_bytes
256 */
257 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
258 {
259 if ($max_upload_chunk_size_bytes == 0) {
260 $size = jirafeau_get_max_upload_size_bytes();
261 // Jirafeau must choose an arbitrary number as PHP config does not give any limit nor $max_upload_chunk_size_bytes
262 if ($size == 0) {
263 return 10000000; // 10MB
264 }
265 return $size;
266 }
267 $size = min(
268 jirafeau_get_max_upload_size_bytes(),
269 $max_upload_chunk_size_bytes
270 );
271 if ($size == 0) {
272 return $max_upload_chunk_size_bytes;
273 }
274 return $size;
275 }
276
277 /**
278 * gets a string explaining the error
279 * @param $code the error code
280 * @returns a string explaining the error
281 */
282 function jirafeau_upload_errstr($code)
283 {
284 switch ($code) {
285 case UPLOAD_ERR_INI_SIZE:
286 case UPLOAD_ERR_FORM_SIZE:
287 return t('Your file exceeds the maximum authorized file size. ');
288
289 case UPLOAD_ERR_PARTIAL:
290 case UPLOAD_ERR_NO_FILE:
291 return
292 t('Your file was not uploaded correctly. You may succeed in retrying. ');
293
294 case UPLOAD_ERR_NO_TMP_DIR:
295 case UPLOAD_ERR_CANT_WRITE:
296 case UPLOAD_ERR_EXTENSION:
297 return t('Internal error. You may not succeed in retrying. ');
298 }
299 return t('Unknown error. ');
300 }
301
302 /** Remove link and it's file
303 * @param $link the link's name (hash)
304 */
305
306 function jirafeau_delete_link($link)
307 {
308 $l = jirafeau_get_link($link);
309 if (!count($l)) {
310 return;
311 }
312
313 jirafeau_clean_rm_link($link);
314
315 $hash = $l['hash'];
316 $p = s2p("$hash");
317
318 $counter = 1;
319 if (file_exists(VAR_FILES . $p . $hash. '_count')) {
320 $content = file(VAR_FILES . $p . $hash. '_count');
321 $counter = trim($content[0]);
322 }
323 $counter--;
324
325 if ($counter >= 1) {
326 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
327 fwrite($handle, $counter);
328 fclose($handle);
329 }
330
331 if ($counter == 0) {
332 jirafeau_clean_rm_file($hash);
333 }
334 }
335
336 /**
337 * Delete a file and it's links.
338 */
339 function jirafeau_delete_file($hash)
340 {
341 $count = 0;
342 /* Get all links files. */
343 $stack = array(VAR_LINKS);
344 while (($d = array_shift($stack)) && $d != null) {
345 $dir = scandir($d);
346
347 foreach ($dir as $node) {
348 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
349 preg_match('/\.tmp/i', "$node")) {
350 continue;
351 }
352
353 if (is_dir($d . $node)) {
354 /* Push new found directory. */
355 $stack[] = $d . $node . '/';
356 } elseif (is_file($d . $node)) {
357 /* Read link informations. */
358 $l = jirafeau_get_link(basename($node));
359 if (!count($l)) {
360 continue;
361 }
362 if ($l['hash'] == $hash) {
363 $count++;
364 jirafeau_delete_link($node);
365 }
366 }
367 }
368 }
369 jirafeau_clean_rm_file($hash);
370 return $count;
371 }
372
373
374 /** hash file's content
375 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
376 * @param $file_path file to hash
377 * @returns hash string
378 */
379 function jirafeau_hash_file($method, $file_path)
380 {
381 switch ($method) {
382 case 'md5_outside':
383 return jirafeau_md5_outside($file_path);
384 case 'md5':
385 return md5_file($file_path);
386 case 'random':
387 return jirafeau_gen_random(32);
388 }
389 return md5_file($file_path);
390 }
391
392 /** hash part of file: start, end and size.
393 * This is a partial file hash, faster but weaker.
394 * @param $file_path file to hash
395 * @returns hash string
396 */
397 function jirafeau_md5_outside($file_path)
398 {
399 $out = false;
400 $handle = fopen($file_path, 'r');
401 if ($handle === false) {
402 return false;
403 }
404 $size = filesize($file_path);
405 if ($size === false) {
406 goto err;
407 }
408 $first = fread($handle, 64);
409 if ($first === false) {
410 goto err;
411 }
412 if (fseek($handle, $size < 64 ? 0 : $size - 64) == -1) {
413 goto err;
414 }
415 $last = fread($handle, 64);
416 if ($last === false) {
417 goto err;
418 }
419 $out = md5($first . $last . $size);
420 err:
421 fclose($handle);
422 return $out;
423 }
424
425 /**
426 * handles an uploaded file
427 * @param $file the file struct given by $_FILE[]
428 * @param $one_time_download is the file a one time download ?
429 * @param $key if not empty, protect the file with this key
430 * @param $time the time of validity of the file
431 * @param $ip uploader's ip
432 * @param $crypt boolean asking to crypt or not
433 * @param $link_name_length size of the link name
434 * @returns an array containing some information
435 * 'error' => information on possible errors
436 * 'link' => the link name of the uploaded file
437 * 'delete_link' => the link code to delete file
438 */
439 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
440 {
441 if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
442 return (array(
443 'error' =>
444 array('has_error' => true,
445 'why' => jirafeau_upload_errstr($file['error'])),
446 'link' => '',
447 'delete_link' => ''));
448 }
449 jirafeau_add_file($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method);
450 }
451
452 /**
453 *
454 * @param bool $crypt_module_enabled
455 * @param string $file_path
456 * @return array [bool, string]
457 */
458 function jirafeau_handle_add_file_encryption($crypt_module_enabled, $file_path)
459 {
460 /* Crypt file if option is enabled. */
461 $crypted = false;
462 $crypt_key = '';
463 if ($crypt_module_enabled == true && !(extension_loaded('sodium') == true)) {
464 error_log("PHP extension sodium not loaded, won't encrypt in Jirafeau");
465 }
466 if ($crypt_module_enabled == true && extension_loaded('sodium') == true) {
467 $crypt_key = jirafeau_encrypt_file($file_path, $file_path.'crypt');
468 if (strlen($crypt_key) > 0) {
469 if (rename($file_path.'crypt', $file_path) === true) {
470 $crypted = true;
471 }
472 }
473 }
474
475 return [$crypted, $crypt_key];
476 }
477
478 /**
479 * adds an uploaded or copy/linked local file
480 * @param $file the file struct given by $_FILE[]
481 * @param $one_time_download is the file a one time download ?
482 * @param $key if not empty, protect the file with this key
483 * @param $time the time of validity of the file
484 * @param $ip uploader's ip
485 * @param $crypt boolean asking to crypt or not
486 * @param $link_name_length size of the link name
487 * @param $is_upload, determines if the file is uploaded or local - it controls which file-functions are used
488 * @return array an array containing some information
489 * 'error' => information on possible errors
490 * 'link' => the link name of the uploaded file
491 * 'delete_link' => the link code to delete file
492 */
493 function jirafeau_add_file($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method, $is_upload = true)
494 {
495 // TODO needs to be adapted
496 $move_operation = $is_upload ? 'move_uploaded_file' : 'symlink';
497
498 /* array representing no error */
499 $noerr = array('has_error' => false, 'why' => '');
500
501 $crypted = false;
502 $crypt_key = '';
503 list($crypted, $crypt_key) = jirafeau_handle_add_file_encryption($crypt, $file['tmp_name']);
504
505 /* file information */
506 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
507 $name = str_replace(NL, '', trim($file['name']));
508 $mime_type = $file['type'];
509 $size = $file['size'];
510
511 /* does file already exist ? */
512 $rc = false;
513 $p = s2p("$hash");
514 if (file_exists(VAR_FILES . $p . $hash)) {
515 $rc = unlink($file['tmp_name']);
516 } elseif (
517 (file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true)) &&
518 $move_operation($file['tmp_name'], VAR_FILES . $p . $hash)) {
519 $rc = true;
520 }
521 if (!$rc) {
522 return (array(
523 'error' =>
524 array('has_error' => true,
525 'why' => t('INTERNAL_ERROR_DEL')),
526 'link' => '',
527 'delete_link' => ''));
528 }
529
530 /* Increment or create count file. */
531 $counter = 0;
532 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
533 $content = file(VAR_FILES . $p . $hash. '_count');
534 $counter = trim($content[0]);
535 }
536 $counter++;
537 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
538 fwrite($handle, $counter);
539 fclose($handle);
540
541 /* Create delete code. */
542 $delete_link_code = jirafeau_gen_random(5);
543
544 /* hash password or empty. */
545 $password = '';
546 if (!empty($key)) {
547 $password = md5($key);
548 }
549
550 /* create link file */
551 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
552 $handle = fopen($link_tmp_name, 'w');
553 fwrite(
554 $handle,
555 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
556 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
557 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O')
558 );
559 fclose($handle);
560 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
561 $l = s2p("$hash_link");
562 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
563 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
564 if (file_exists($link_tmp_name)) {
565 unlink($link_tmp_name);
566 }
567
568 $counter--;
569 if ($counter >= 1) {
570 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
571 fwrite($handle, $counter);
572 fclose($handle);
573 } else {
574 jirafeau_clean_rm_file($hash_link);
575 }
576 return array(
577 'error' =>
578 array('has_error' => true,
579 'why' => t('Internal error during file creation. ')),
580 'link' => '',
581 'delete_link' => '');
582 }
583 return array( 'error' => $noerr,
584 'link' => $hash_link,
585 'delete_link' => $delete_link_code,
586 'crypt_key' => $crypt_key);
587 }
588
589 function jirafeau_admin_list_table($name, $file_hash, $link_hash, $visitor_function = null)
590 {
591 echo '<fieldset><legend>';
592 if (!empty($name)) {
593 echo t('FILENAME') . ": " . jirafeau_escape($name);
594 }
595 if (!empty($file_hash)) {
596 echo t('FILE') . ": " . jirafeau_escape($file_hash);
597 }
598 if (!empty($link_hash)) {
599 echo t('LINK') . ": " . jirafeau_escape($link_hash);
600 }
601 if (empty($name) && empty($file_hash) && empty($link_hash)) {
602 echo t('LS_FILES');
603 }
604 echo '</legend>';
605 echo '<table>';
606 echo '<tr>';
607 echo '<th></th>';
608 echo '<th>' . t('ACTION') . '</th>';
609 echo '</tr>';
610 if ($visitor_function != null) {
611 $visitor_function($name, $file_hash, $link_hash);
612 }
613 echo '</table></fieldset>';
614 }
615
616 /**
617 * Tells if a mime-type is viewable in a browser
618 * @param $mime the mime type
619 * @returns a boolean telling if a mime type is viewable
620 */
621 function jirafeau_is_viewable($mime)
622 {
623 if (!empty($mime)) {
624 $viewable = array('image', 'video', 'audio');
625 $decomposed = explode('/', $mime);
626 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
627 return true;
628 }
629 $viewable = array('text/plain');
630 if (in_array($mime, $viewable)) {
631 return true;
632 }
633 }
634 return false;
635 }
636
637 // Error handling functions.
638 //! Global array that contains all registered errors.
639 $error_list = array();
640
641 /**
642 * Adds an error to the list of errors.
643 * @param $title the error's title
644 * @param $description is a human-friendly description of the problem.
645 */
646 function add_error($title, $description)
647 {
648 global $error_list;
649 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
650 }
651
652 /**
653 * Informs whether any error has been registered yet.
654 * @return true if there are errors.
655 */
656 function has_error()
657 {
658 global $error_list;
659 return !empty($error_list);
660 }
661
662 /**
663 * Displays all the errors.
664 */
665 function show_errors()
666 {
667 if (has_error()) {
668 global $error_list;
669 echo '<div class="error">';
670 foreach ($error_list as $error) {
671 echo $error;
672 }
673 echo '</div>';
674 }
675 }
676
677 function check_errors($cfg)
678 {
679 if (!($cfg['installation_done'] === true)) {
680 if (file_exists(JIRAFEAU_ROOT . 'install.php')) {
681 header('Location: install.php');
682 exit;
683 } else {
684 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
685 }
686 }
687
688 if (!is_writable(VAR_FILES)) {
689 add_error(t('FILE_DIR_W'), VAR_FILES);
690 }
691
692 if (!is_writable(VAR_LINKS)) {
693 add_error(t('LINK_DIR_W'), VAR_LINKS);
694 }
695
696 if (!is_writable(VAR_ASYNC)) {
697 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
698 }
699
700 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
701 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
702 }
703
704 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
705 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
706 }
707 }
708
709 /**
710 * Read link information
711 * @return array containing information.
712 */
713 function jirafeau_get_link($hash)
714 {
715 $out = array();
716 $link = VAR_LINKS . s2p("$hash") . $hash;
717
718 if (!file_exists($link)) {
719 return $out;
720 }
721
722 $c = file($link);
723 $out['file_name'] = trim($c[0]);
724 $out['mime_type'] = trim($c[1]);
725 $out['file_size'] = trim($c[2]);
726 $out['key'] = trim($c[3], NL);
727 $out['time'] = trim($c[4]);
728 $out['hash'] = trim($c[5]);
729 $out['onetime'] = trim($c[6]);
730 $out['upload_date'] = trim($c[7]);
731 $out['ip'] = trim($c[8]);
732 $out['link_code'] = trim($c[9]);
733 $out['crypted'] = trim($c[10]) == 'C2';
734 $out['crypted_legacy'] = trim($c[10]) == 'C';
735
736 return $out;
737 }
738
739 /**
740 * List files in admin interface.
741 */
742 function jirafeau_admin_list($name, $file_hash, $link_hash)
743 {
744 $function = function ($name, $file_hash, $link_hash) {
745 /* Get all links files. */
746 $stack = array(VAR_LINKS);
747 while (($d = array_shift($stack)) && $d != null) {
748 $dir = scandir($d);
749 foreach ($dir as $node) {
750 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
751 preg_match('/\.tmp/i', "$node")) {
752 continue;
753 }
754 if (is_dir($d . $node)) {
755 /* Push new found directory. */
756 $stack[] = $d . $node . '/';
757 } elseif (is_file($d . $node)) {
758 /* Read link information. */
759 $l = jirafeau_get_link($node);
760 if (!count($l)) {
761 continue;
762 }
763
764 /* Filter. */
765 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
766 continue;
767 }
768 if (!empty($file_hash) && $file_hash != $l['hash']) {
769 continue;
770 }
771 if (!empty($link_hash) && $link_hash != $node) {
772 continue;
773 }
774 /* Print link information. */
775 echo '<tr>';
776 echo '<td><strong>';
777
778 if (!$l['crypted'] && !$l['crypted_legacy']) {
779 echo'<a href="f.php?h='. jirafeau_escape($node) .'" title="' .
780 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a>';
781 } else {
782 echo jirafeau_escape($l['file_name']);
783 }
784
785 echo '</strong><br/>';
786
787 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
788 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
789 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
790 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ? t('YES') : t('NO')) . '<br/>';
791 echo t('ENCRYPTED') . ': ' . (($l['crypted'] || $l['crypted_legacy']) ? t('YES') : t('NO')) . '<br/>';
792 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
793 if (strlen($l['ip']) > 0) {
794 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
795 }
796 echo '</td><td>';
797
798 if (!$l['crypted'] && !$l['crypted_legacy']) {
799 echo '<form method="post">' .
800 '<input type = "hidden" name = "action" value = "download"/>' .
801 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
802 jirafeau_admin_csrf_field() .
803 '<input type = "submit" value = "' . t('DL') . '" />' .
804 '</form>';
805 }
806
807 echo '<form method="post">' .
808 '<input type = "hidden" name = "action" value = "delete_link"/>' .
809 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
810 jirafeau_admin_csrf_field() .
811 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
812 '</form>' .
813 '<form method="post">' .
814 '<input type = "hidden" name = "action" value = "delete_file"/>' .
815 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
816 jirafeau_admin_csrf_field() .
817 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
818 '</form>' .
819 '</td>';
820 echo '</tr>';
821 }
822 }
823 }
824 };
825
826 jirafeau_admin_list_table($name, $file_hash, $link_hash, $function);
827 }
828
829 /**
830 * Clean expired files.
831 * @return number of cleaned files.
832 */
833 function jirafeau_admin_clean()
834 {
835 $count = 0;
836 /* Get all links files. */
837 $stack = array(VAR_LINKS);
838 while (($d = array_shift($stack)) && $d != null) {
839 $dir = scandir($d);
840
841 foreach ($dir as $node) {
842 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
843 preg_match('/\.tmp/i', "$node")) {
844 continue;
845 }
846
847 if (is_dir($d . $node)) {
848 /* Push new found directory. */
849 $stack[] = $d . $node . '/';
850 } elseif (is_file($d . $node)) {
851 /* Read link information. */
852 $l = jirafeau_get_link(basename($node));
853 if (!count($l)) {
854 continue;
855 }
856 $p = s2p($l['hash']);
857 if ($l['time'] > 0 && $l['time'] < time() || // expired
858 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
859 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
860 jirafeau_delete_link($node);
861 $count++;
862 }
863 }
864 }
865 }
866 return $count;
867 }
868
869
870 /**
871 * Clean old async transfers.
872 * @return number of cleaned files.
873 */
874 function jirafeau_admin_clean_async()
875 {
876 $count = 0;
877 /* Get all links files. */
878 $stack = array(VAR_ASYNC);
879 while (($d = array_shift($stack)) && $d != null) {
880 $dir = scandir($d);
881
882 foreach ($dir as $node) {
883 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
884 preg_match('/\.tmp/i', "$node")) {
885 continue;
886 }
887
888 if (is_dir($d . $node)) {
889 /* Push new found directory. */
890 $stack[] = $d . $node . '/';
891 } elseif (is_file($d . $node)) {
892 /* Read async information. */
893 $a = jirafeau_get_async_ref(basename($node));
894 if (!count($a)) {
895 continue;
896 }
897 /* Delete transfers older than 1 hour. */
898 if (time() - $a['last_edited'] > 3600) {
899 jirafeau_async_delete(basename($node));
900 $count++;
901 }
902 }
903 }
904 }
905 return $count;
906 }
907
908 /**
909 * Better strval function for debug purposes
910 */
911 function jirafeau_strval($value)
912 {
913 if (gettype($value) == "boolean") {
914 return $value ? 'true' : 'false';
915 }
916 return strval($value);
917 }
918
919 /**
920 * Show file/folder permissions
921 */
922 function jirafeau_fileperms($path)
923 {
924 $out = substr(sprintf("%o", @fileperms($path)), -4) . ", ";
925 $out .= "read " . (is_readable($path) ? "OK" : "KO") . ", ";
926 $out .= "write " . (is_writable($path) ? "OK" : "KO");
927 return $out;
928 }
929
930 /**
931 * Show some useful informations for bug reporting.
932 */
933 function jirafeau_admin_bug_report($cfg)
934 {
935 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
936 $out .= "If you have a problem related to Jirafeau, please <a href='" . JIRAFEAU_WEBSITE . "/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>";
937
938 $out .= "# Jirafeau<br/>";
939 $out .= "- version: " . JIRAFEAU_VERSION . "<br/>";
940 $jirafeau_options = [
941 'debug',
942 'file_hash',
943 'litespeed_workaround',
944 'store_uploader_ip',
945 'installation_done',
946 'enable_crypt',
947 'preview',
948 'maximal_upload_size',
949 'store_uploader_ip',
950 'max_upload_chunk_size_bytes'
951 ];
952 foreach ($jirafeau_options as &$o) {
953 $v = $cfg[$o];
954 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
955 }
956 $out .= "<br/>";
957
958 $out .= "# PHP options<br/>";
959 $out .= "- php version: " . phpversion() . "<br/>";
960 $out .= "- sodium version: " . phpversion('sodium') . "<br/>";
961 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
962 $php_options = [
963 'post_max_size',
964 'upload_max_filesize',
965 'safe_mode',
966 'max_execution_time',
967 'max_input_time'
968 ];
969 foreach ($php_options as &$o) {
970 $v = ini_get($o);
971 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
972 }
973 $out .= "- can set_time_limit: " . (set_time_limit(0) ? "yes" : "no") . "<br/>";
974 $out .= "<br/>";
975
976 $out .= "# File permissions<br/>";
977 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
978 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES) . "<br/>";
979 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS) . "<br/>";
980 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC) . "<br/>";
981 $out .= "<br/>";
982
983 $out .= "# Server details<br/>";
984 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
985 $out .= "<br/>";
986
987 $out .= "# OS details<br/>";
988 $out .= "- OS: " . php_uname() . "<br/>";
989 $out .= "<br/>";
990
991 $out .= "# Browser details<br/>";
992 $out .= "<script type='text/javascript' lang='Javascript'>
993 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
994 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
995 document.write('- user agent: ' + navigator.userAgent + '<br/>');
996 // @license-end
997 </script>";
998 $out .= "<br/>";
999
1000 $out .= "# Memory<br/>";
1001 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
1002
1003 $out .= "</code></fieldset>";
1004 return $out;
1005 }
1006
1007 /**
1008 * Read async transfer information
1009 * @return array containing information.
1010 */
1011 function jirafeau_get_async_ref($ref)
1012 {
1013 $out = array();
1014 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
1015
1016 if (!file_exists($refinfos)) {
1017 return $out;
1018 }
1019
1020 $c = file($refinfos);
1021 $out['file_name'] = trim($c[0]);
1022 $out['mime_type'] = trim($c[1]);
1023 $out['key'] = trim($c[2], NL);
1024 $out['time'] = trim($c[3]);
1025 $out['onetime'] = trim($c[4]);
1026 $out['ip'] = trim($c[5]);
1027 $out['last_edited'] = trim($c[6]);
1028 $out['next_code'] = trim($c[7]);
1029 return $out;
1030 }
1031
1032 /**
1033 * Delete async transfer information
1034 */
1035 function jirafeau_async_delete($ref)
1036 {
1037 $p = s2p("$ref");
1038 if (file_exists(VAR_ASYNC . $p . $ref)) {
1039 unlink(VAR_ASYNC . $p . $ref);
1040 }
1041 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
1042 unlink(VAR_ASYNC . $p . $ref . '_data');
1043 }
1044 $parse = VAR_ASYNC . $p;
1045 $scan = array();
1046 while (file_exists($parse)
1047 && ($scan = scandir($parse))
1048 && count($scan) == 2 // '.' and '..' folders => empty.
1049 && basename($parse) != basename(VAR_ASYNC)) {
1050 rmdir($parse);
1051 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1052 }
1053 }
1054
1055 /**
1056 * Init a new asynchronous upload.
1057 * @param $filename Name of the file to send
1058 * @param $one_time One time upload parameter
1059 * @param $key eventual password (or blank)
1060 * @param $time time limit
1061 * @param $ip ip address of the client
1062 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1063 */
1064 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1065 {
1066 /* Create temporary folder. */
1067 $ref = '';
1068 $p = '';
1069 $code = jirafeau_gen_random(4);
1070 do {
1071 $ref = jirafeau_gen_random(32);
1072 $p = VAR_ASYNC . s2p($ref);
1073 } while (file_exists($p));
1074 @mkdir($p, 0755, true);
1075 if (!file_exists($p)) {
1076 return 'Error: cannot create async folder.';
1077 }
1078
1079 /* touch empty data file */
1080 $w_path = $p . $ref . '_data';
1081 touch($w_path);
1082
1083 /* md5 password or empty */
1084 $password = '';
1085 if (!empty($key)) {
1086 $password = md5($key);
1087 }
1088
1089 /* Store information. */
1090 $p .= $ref;
1091 $handle = fopen($p, 'w');
1092 fwrite(
1093 $handle,
1094 str_replace(NL, '', trim($filename)) . NL .
1095 str_replace(NL, '', trim($type)) . NL . $password . NL .
1096 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
1097 time() . NL . $code . NL
1098 );
1099 fclose($handle);
1100
1101 return $ref . NL . $code ;
1102 }
1103
1104 /**
1105 * Append a piece of file on the asynchronous upload.
1106 * @param $ref asynchronous upload reference
1107 * @param $file piece of data
1108 * @param $code client code for this operation
1109 * @param $max_file_size maximum allowed file size
1110 * @return a string containing a next code to use or a string starting with 'Error'
1111 */
1112 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1113 {
1114 /* Get async infos. */
1115 $a = jirafeau_get_async_ref($ref);
1116
1117 /* Check some errors. */
1118 if (count($a) == 0) {
1119 return "Error: cannot find transfer";
1120 }
1121 if ($a['next_code'] != "$code") {
1122 return "Error: bad transfer code";
1123 }
1124 if ($data['error'] != UPLOAD_ERR_OK) {
1125 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1126 $data_details = print_r($data, true);
1127 return "Error: upload error: {$data_details}";
1128 }
1129 if (empty($data['tmp_name'])) {
1130 return "Error: missing tmp_name";
1131 }
1132 if (!is_uploaded_file($data['tmp_name'])) {
1133 return "Error: tmp_name may not be uploaded";
1134 }
1135
1136 $p = s2p($ref);
1137
1138 /* File path. */
1139 $r_path = $data['tmp_name'];
1140 $w_path = VAR_ASYNC . $p . $ref . '_data';
1141
1142 /* Check that file size is not above upload limit. */
1143 if ($max_file_size > 0 &&
1144 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
1145 jirafeau_async_delete($ref);
1146 return "Error: file size is above upload limit";
1147 }
1148
1149 /* Concatenate data. */
1150 $r = fopen($r_path, 'r');
1151 $w = fopen($w_path, 'a');
1152 while (!feof($r)) {
1153 if (fwrite($w, fread($r, 1024)) === false) {
1154 fclose($r);
1155 fclose($w);
1156 jirafeau_async_delete($ref);
1157 return "Error: cannot write file";
1158 }
1159 }
1160 fclose($r);
1161 fclose($w);
1162 unlink($r_path);
1163
1164 /* Update async file. */
1165 $code = jirafeau_gen_random(4);
1166 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
1167 fwrite(
1168 $handle,
1169 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
1170 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
1171 time() . NL . $code . NL
1172 );
1173 fclose($handle);
1174 return $code;
1175 }
1176
1177 /**
1178 * Finalize an asynchronous upload.
1179 * @param $ref asynchronous upload reference
1180 * @param $code client code for this operation
1181 * @param $crypt boolean asking to crypt or not
1182 * @param $link_name_length link name length
1183 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1184 */
1185 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1186 {
1187 /* Get async infos. */
1188 $a = jirafeau_get_async_ref($ref);
1189 if (count($a) == 0
1190 || $a['next_code'] != "$code") {
1191 return "Error: bad code for ending transfer";
1192 }
1193
1194 /* Generate link infos. */
1195 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
1196 if (!file_exists($p)) {
1197 return "Error: referenced file does not exist";
1198 }
1199
1200 $crypted = false;
1201 $crypt_key = '';
1202 if ($crypt == true && extension_loaded('sodium') == true) {
1203 $crypt_key = jirafeau_encrypt_file($p, $p.'.crypt');
1204 if (strlen($crypt_key) > 0) {
1205 if (rename($p.'.crypt', $p) === true) {
1206 $crypted = true;
1207 }
1208 }
1209 }
1210
1211 $hash = jirafeau_hash_file($file_hash_method, $p);
1212 $size = filesize($p);
1213 $np = s2p($hash);
1214 $delete_link_code = jirafeau_gen_random(5);
1215
1216 /* File already exist ? */
1217 if (!file_exists(VAR_FILES . $np)) {
1218 @mkdir(VAR_FILES . $np, 0755, true);
1219 }
1220 if (!file_exists(VAR_FILES . $np . $hash)) {
1221 rename($p, VAR_FILES . $np . $hash);
1222 }
1223
1224 /* Increment or create count file. */
1225 $counter = 0;
1226 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
1227 $content = file(VAR_FILES . $np . $hash. '_count');
1228 $counter = trim($content[0]);
1229 }
1230 $counter++;
1231 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
1232 fwrite($handle, $counter);
1233 fclose($handle);
1234
1235 /* Create link. */
1236 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
1237 $handle = fopen($link_tmp_name, 'w');
1238 fwrite(
1239 $handle,
1240 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
1241 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
1242 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C2' : 'O')
1243 );
1244 fclose($handle);
1245 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1246 $l = s2p("$hash_link");
1247 if (!@mkdir(VAR_LINKS . $l, 0755, true)) {
1248 return "Error: cannot create folder in LINKS";
1249 }
1250 if (!rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
1251 return "Error: cannot rename file in LINKS";
1252 }
1253
1254 /* Clean async upload. */
1255 jirafeau_async_delete($ref);
1256 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1257 }
1258
1259 function jirafeau_crypt_create_iv($base, $size)
1260 {
1261 $iv = '';
1262 while (strlen($iv) < $size) {
1263 $iv = $iv . $base;
1264 }
1265 $iv = substr($iv, 0, $size);
1266 return $iv;
1267 }
1268
1269 /**
1270 * Crypt file using Sodium and returns decrypt key.
1271 * @param $fp_src file path to the file to crypt.
1272 * @param $fp_dst file path to the file to write crypted file (must not be the same).
1273 * @return key used to encrypt the file
1274 */
1275 function jirafeau_encrypt_file($fp_src, $fp_dst)
1276 {
1277 $fs = filesize($fp_src);
1278 if ($fs === false || $fs == 0 || extension_loaded('sodium') == false || $fp_src == $fp_dst) {
1279 return '';
1280 }
1281
1282 /* Generate key. */
1283 $crypt_key = bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES / 2));
1284 /* Init module. */
1285 [$crypt_state, $crypt_header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($crypt_key);
1286 /* Crypt file. */
1287 $r = fopen($fp_src, 'rb');
1288 $w = fopen($fp_dst, 'wb');
1289 fwrite($w, $crypt_header);
1290
1291 for ($i = 0; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE) {
1292 $to_enc = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE);
1293 $enc = sodium_crypto_secretstream_xchacha20poly1305_push($crypt_state, $to_enc);
1294
1295 if (fwrite($w, $enc) === false) {
1296 return '';
1297 }
1298 }
1299
1300 fclose($r);
1301 fclose($w);
1302
1303 /* Cleanup. */
1304 sodium_memzero($crypt_state);
1305
1306 return $crypt_key;
1307 }
1308
1309 /**
1310 * Decrypt file using Sodium.
1311 * @param $fp_src file path to the file to decrypt.
1312 * @param $fp_dst file path to the file to write decrypted file (must not be the same).
1313 * @param $k decryption key
1314 * @return true if decryption succeeded, false otherwise
1315 */
1316 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1317 {
1318 $fs = filesize($fp_src);
1319 if ($fs === false || $fs == 0 || extension_loaded('sodium') == false || $fp_src == $fp_dst) {
1320 return false;
1321 }
1322
1323 /* Decrypt file. */
1324 $r = fopen($fp_src, 'rb');
1325 $w = fopen($fp_dst, 'wb');
1326
1327 $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);
1328
1329 /* Init module. */
1330 $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $k);
1331
1332 /* Decrypt file. */
1333
1334 for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES) {
1335 $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
1336 [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
1337
1338 if (fwrite($w, $dec) === false) {
1339 return false;
1340 }
1341 }
1342
1343 fclose($r);
1344 fclose($w);
1345
1346 /* Cleanup. */
1347 sodium_memzero($crypt_state);
1348
1349 return true;
1350 }
1351
1352 /**
1353 * Decrypt file using mcrypt.
1354 * @param $fp_src file path to the file to decrypt.
1355 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1356 * @param $k string composed of the key and the iv separated by a point ('.')
1357 * @return true if decryption succeeded, false otherwise
1358 */
1359 function jirafeau_decrypt_file_legacy($fp_src, $fp_dst, $k)
1360 {
1361 $fs = filesize($fp_src);
1362 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1363 return false;
1364 }
1365
1366 /* Init module */
1367 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1368 /* Extract key and iv. */
1369 $crypt_key = $k;
1370 $hash_key = md5($crypt_key);
1371 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1372 /* Init module. */
1373 mcrypt_generic_init($m, $hash_key, $iv);
1374 /* Decrypt file. */
1375 $r = fopen($fp_src, 'r');
1376 $w = fopen($fp_dst, 'c');
1377 while (!feof($r)) {
1378 $dec = mdecrypt_generic($m, fread($r, 1024));
1379 if (fwrite($w, $dec) === false) {
1380 return false;
1381 }
1382 }
1383 fclose($r);
1384 fclose($w);
1385 /* Cleanup. */
1386 mcrypt_generic_deinit($m);
1387 mcrypt_module_close($m);
1388 return true;
1389 }
1390
1391 /**
1392 * Check if Jirafeau is password protected for visitors.
1393 * @return true if Jirafeau is password protected, false otherwise.
1394 */
1395 function jirafeau_has_upload_password($cfg)
1396 {
1397 return count($cfg['upload_password']) > 0;
1398 }
1399
1400 /**
1401 * Challenge password for a visitor.
1402 * @param $password password to be challenged
1403 * @return true if password is valid, false otherwise.
1404 */
1405 function jirafeau_challenge_upload_password($cfg, $password)
1406 {
1407 if (!jirafeau_has_upload_password($cfg)) {
1408 return false;
1409 }
1410 foreach ($cfg['upload_password'] as $p) {
1411 if ($password == $p) {
1412 return true;
1413 }
1414 }
1415 return false;
1416 }
1417
1418 /**
1419 * Test if the given IP is whitelisted by the given list.
1420 *
1421 * @param $allowedIpList array of allowed IPs
1422 * @param $challengedIp IP to be challenged
1423 * @return true if IP is authorized, false otherwise.
1424 */
1425 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1426 {
1427 foreach ($allowedIpList as $i) {
1428 if ($i == $challengedIp) {
1429 return true;
1430 }
1431 // CIDR test for IPv4 only.
1432 if (strpos($i, '/') !== false) {
1433 list($subnet, $mask) = explode('/', $i);
1434 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1435 return true;
1436 }
1437 }
1438 }
1439 return false;
1440 }
1441
1442 /**
1443 * Check if Jirafeau has a restriction on the IP address for uploading.
1444 * @return true if uploading is IP restricted, false otherwise.
1445 */
1446 function jirafeau_upload_has_ip_restriction($cfg)
1447 {
1448 return count($cfg['upload_ip']) > 0;
1449 }
1450
1451 /**
1452 * Test if visitor's IP is authorized to upload at all.
1453 *
1454 * @param $cfg configuration
1455 * @param $challengedIp IP to be challenged
1456 * @return true if IP is authorized, false otherwise.
1457 */
1458 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1459 {
1460 // If no IP address have been listed, allow upload from any IP
1461 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1462 return true;
1463 }
1464 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1465 }
1466
1467 /**
1468 * Test if visitor's IP is authorized to upload without a password.
1469 *
1470 * @param $cfg configuration
1471 * @param $challengedIp IP to be challenged
1472 * @return true if IP is authorized, false otherwise.
1473 */
1474 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1475 {
1476 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1477 }
1478
1479 /**
1480 * Test if visitor's IP is authorized or password is supplied and authorized
1481 * @param $ip IP to be challenged
1482 * @param $password password to be challenged
1483 * @return true if access is valid, false otherwise.
1484 */
1485 function jirafeau_challenge_upload($cfg, $ip, $password)
1486 {
1487 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1488 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1489 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1490 }
1491
1492 /**
1493 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1494 * @return true if admin interface is IP restricted, false otherwise.
1495 */
1496 function jirafeau_admin_has_ip_restriction($cfg)
1497 {
1498 return count($cfg['admin_ip']) > 0;
1499 }
1500
1501 /**
1502 * Test if visitor's IP is authorized to access the admin interface.
1503 *
1504 * @param $cfg configuration
1505 * @param $challengedIp IP to be challenged
1506 * @return true if IP is authorized, false otherwise.
1507 */
1508 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1509 {
1510 // If no IP address have been listed, allow upload from any IP
1511 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1512 return true;
1513 }
1514 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1515 }
1516
1517 /** Tell if we have some HTTP headers generated by a proxy */
1518 function has_http_forwarded()
1519 {
1520 return
1521 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1522 !empty($_SERVER['http_X_forwarded_for']);
1523 }
1524
1525 /**
1526 * Generate IP list from HTTP headers generated by a proxy
1527 * @return array of IP strings
1528 */
1529 function get_ip_list_http_forwarded()
1530 {
1531 $ip_list = array();
1532 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1533 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1534 if ($l === false) {
1535 return array();
1536 }
1537 foreach ($l as $ip) {
1538 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1539 }
1540 }
1541 if (!empty($_SERVER['http_X_forwarded_for'])) {
1542 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1543 foreach ($l as $ip) {
1544 // Separate IP from port
1545 $ipa = explode(':', $ip);
1546 if ($ipa === false) {
1547 continue;
1548 }
1549 $ip = $ipa[0];
1550 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1551 }
1552 }
1553 return $ip_list;
1554 }
1555
1556 /**
1557 * Get the ip address of the client from REMOTE_ADDR
1558 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1559 * @returns the client ip address
1560 */
1561 function get_ip_address($cfg)
1562 {
1563 $remote = $_SERVER['REMOTE_ADDR'];
1564 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1565 return $remote;
1566 }
1567
1568 $ip_list = get_ip_list_http_forwarded();
1569 if (count($ip_list) == 0) {
1570 return $remote;
1571 }
1572
1573 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1574 if ($remote != $proxy_ip) {
1575 continue;
1576 }
1577 // Take the last IP (the one which has been set by the defined proxy).
1578 return end($ip_list);
1579 }
1580 return $remote;
1581 }
1582
1583 /**
1584 * Convert hexadecimal string to base64
1585 */
1586 function hex_to_base64($hex)
1587 {
1588 $b = '';
1589 foreach (str_split($hex, 2) as $pair) {
1590 $b .= chr(hexdec($pair));
1591 }
1592 return base64_encode($b);
1593 }
1594
1595 /**
1596 * Replace markers in templates.
1597 *
1598 * Available markers have the scheme "###MARKERNAME###".
1599 *
1600 * @param $content string Template text with markers
1601 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1602 * @return Template with replaced markers
1603 */
1604 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1605 {
1606 $patterns = array(
1607 '/###ORGANISATION###/',
1608 '/###CONTACTPERSON###/',
1609 '/###WEBROOT###/'
1610 );
1611 $replacements = array(
1612 $GLOBALS['cfg']['organisation'],
1613 $GLOBALS['cfg']['contactperson'],
1614 $GLOBALS['cfg']['web_root']
1615 );
1616 $content = preg_replace($patterns, $replacements, $content);
1617
1618 if (true === $htmllinebreaks) {
1619 $content = nl2br($content);
1620 }
1621
1622 return $content;
1623 }
1624
1625 function jirafeau_escape($string)
1626 {
1627 return htmlspecialchars($string, ENT_QUOTES);
1628 }
1629
1630 function jirafeau_admin_session_start()
1631 {
1632 $_SESSION['admin_auth'] = true;
1633 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1634 }
1635
1636 function jirafeau_session_end()
1637 {
1638 $_SESSION = array();
1639 session_destroy();
1640 }
1641
1642 function jirafeau_admin_session_logged()
1643 {
1644 return isset($_SESSION['admin_auth']) &&
1645 isset($_SESSION['admin_csrf']) &&
1646 isset($_POST['admin_csrf']) &&
1647 $_SESSION['admin_auth'] === true &&
1648 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1649 }
1650
1651 function jirafeau_admin_csrf_field()
1652 {
1653 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1654 }
1655
1656 function jirafeau_user_session_start()
1657 {
1658 $_SESSION['user_auth'] = true;
1659 }
1660
1661 function jirafeau_user_session_logged()
1662 {
1663 return isset($_SESSION['user_auth']) &&
1664 $_SESSION['user_auth'] === true;
1665 }
1666
1667 function jirafeau_dir_size($dir)
1668 {
1669 $size = 0;
1670 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $entry) {
1671 $size += is_file($entry) ? filesize($entry) : jirafeau_dir_size($entry);
1672 }
1673 return $size;
1674 }
1675
1676 function jirafeau_export_cfg($cfg)
1677 {
1678 $content = '<?php' . NL;
1679 $content .= '/* This file was generated by the install process. ' .
1680 'You can edit it. Please see config.original.php to understand the ' .
1681 'configuration items. */' . NL;
1682 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1683
1684 $fileWrite = file_put_contents(JIRAFEAU_CFG, $content);
1685
1686 if (false === $fileWrite) {
1687 jirafeau_fatal_error(t('Can not write local configuration file'));
1688 }
1689 }
1690
1691 function jirafeau_mkdir($path)
1692 {
1693 return !(!file_exists($path) && !@mkdir($path, 0755));
1694 }
1695
1696 /**
1697 * Returns true whether the path is writable or we manage to make it
1698 * so, which essentially is the same thing.
1699 * @param $path is the file or directory to be tested.
1700 * @return true if $path is writable.
1701 */
1702 function jirafeau_is_writable($path)
1703 {
1704 /* "@" gets rid of error messages. */
1705 return is_writable($path) || @chmod($path, 0777);
1706 }
1707
1708 function jirafeau_check_var_dir($path)
1709 {
1710 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1711 $mkdir_str2 = t('MANUAL_CREATE');
1712 $write_str1 = t('DIR_NOT_W') . ':';
1713 $write_str2 = t('You should give the write permission to the web server on ' .
1714 'this directory.');
1715 $solution_str = t('HERE_SOLUTION') . ':';
1716
1717 if (!jirafeau_mkdir($path) || !jirafeau_is_writable($path)) {
1718 return array('has_error' => true,
1719 'why' => $mkdir_str1 . '<br /><code>' .
1720 $path . '</code><br />' . $solution_str .
1721 '<br />' . $mkdir_str2);
1722 }
1723
1724 foreach (array('files', 'links', 'async') as $subdir) {
1725 $subpath = $path.$subdir;
1726
1727 if (!jirafeau_mkdir($subpath) || !jirafeau_is_writable($subpath)) {
1728 return array('has_error' => true,
1729 'why' => $mkdir_str1 . '<br /><code>' .
1730 $subpath . '</code><br />' . $solution_str .
1731 '<br />' . $mkdir_str2);
1732 }
1733 }
1734
1735 return array('has_error' => false, 'why' => '');
1736 }
1737
1738 function jirafeau_add_ending_slash($path)
1739 {
1740 return $path . ((substr($path, -1) == '/') ? '' : '/');
1741 }
1742
1743 function jirafeau_default_web_root()
1744 {
1745 $url_scheme = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
1746 return $url_scheme . $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1747 }
1748
1749 function jirafeau_get_download_stats($hash)
1750 {
1751 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1752
1753 if (!file_exists($filename)) {
1754 return array('count' => 0);
1755 }
1756
1757 $c = file($filename);
1758 $data['count'] = trim($c[0]);
1759 $data['date'] = trim($c[1]);
1760 $data['ip'] = trim($c[2]);
1761
1762 return $data;
1763 }
1764
1765 function jirafeau_write_download_stats($hash, $ip)
1766 {
1767 $data = jirafeau_get_download_stats($hash);
1768 $count = $data['count'];
1769 $count++;
1770
1771 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1772
1773 $handle = fopen($filename, 'w');
1774 fwrite($handle, $count . NL . time() . NL . $ip);
1775 fclose($handle);
1776 }
1777
1778 function jirafeau_create_upload_finished_box($preview = true)
1779 {
1780 ?>
1781
1782 <div id="upload_finished">
1783 <p><?php echo t('FILE_UP') ?></p>
1784
1785 <div id="upload_finished_download_page">
1786 <p>
1787 <a id="upload_link" href=""><?php echo t('DL_PAGE') ?></a>
1788 <a id="upload_link_email" href=""><img id="upload_image_email"/></a>
1789 </p><p>
1790 <code id=upload_link_text></code>
1791 <button id="upload_link_button">&#128203;</button>
1792 </p>
1793 </div>
1794
1795 <?php
1796 if ($preview == true) { ?>
1797 <div id="upload_finished_preview">
1798 <p>
1799 <a id="preview_link" href=""><?php echo t('VIEW_LINK') ?></a>
1800 </p><p>
1801 <code id=preview_link_text></code>
1802 <button id="preview_link_button">&#128203;</button>
1803 </p>
1804 </div>
1805 <?php
1806 }
1807 ?>
1808
1809 <div id="upload_direct_download">
1810 <p>
1811 <a id="direct_link" href=""><?php echo t('DIRECT_DL') ?></a>
1812 </p><p>
1813 <code id=direct_link_text></code>
1814 <button id="direct_link_button">&#128203;</button>
1815 </p>
1816 </div>
1817
1818 <div id="upload_delete">
1819 <p>
1820 <a id="delete_link" href=""><?php echo t('DELETE_LINK') ?></a>
1821 </p><p>
1822 <code id=delete_link_text></code>
1823 <button id="delete_link_button">&#128203;</button>
1824 </p>
1825 </div>
1826
1827 <div id="upload_validity">
1828 <p><?php echo t('VALID_UNTIL'); ?>:</p>
1829 <p id="date"></p>
1830 </div>
1831 </div>
1832 <?php
1833 }
1834
1835 function jirafeau_get_expiration_time_options()
1836 {
1837 return array(
1838 array(
1839 'value' => 'minute',
1840 'label' => '1_MIN'
1841 ),
1842 array(
1843 'value' => 'hour',
1844 'label' => '1_H'
1845 ),
1846 array(
1847 'value' => 'day',
1848 'label' => '1_D'
1849 ),
1850 array(
1851 'value' => 'week',
1852 'label' => '1_W'
1853 ),
1854 array(
1855 'value' => 'fortnight',
1856 'label' => '2_W'
1857 ),
1858 array(
1859 'value' => 'month',
1860 'label' => '1_M'
1861 ),
1862 array(
1863 'value' => 'quarter',
1864 'label' => '1_Q'
1865 ),
1866 array(
1867 'value' => 'year',
1868 'label' => '1_Y'
1869 ),
1870 array(
1871 'value' => 'none',
1872 'label' => 'NONE'
1873 )
1874 );
1875 }
1876
1877 /**
1878 *
1879 * creates the time selection field
1880 * @param mixed $cfg
1881 * @return void
1882 */
1883 function jirafeau_create_selection_array($cfg)
1884 {
1885 echo '<select name="time" id="select_time">';
1886
1887 $expirationTimeOptions = jirafeau_get_expiration_time_options();
1888
1889 foreach ($expirationTimeOptions as $expirationTimeOption) {
1890 $selected = ($expirationTimeOption['value'] === $cfg['availability_default']) ? 'selected="selected"' : '';
1891 if (true === $cfg['availabilities'][$expirationTimeOption['value']]) {
1892 echo '<option value="' . $expirationTimeOption['value'] . '" ' .
1893 $selected . '>' . t($expirationTimeOption['label']) . '</option>';
1894 }
1895 }
1896
1897 echo '</select>';
1898 }
1899
1900 function jirafeau_datestr_to_int($time_str)
1901 {
1902 $time = time();
1903 switch ($time_str) {
1904 case 'minute':
1905 $time += JIRAFEAU_MINUTE;
1906 break;
1907 case 'hour':
1908 $time += JIRAFEAU_HOUR;
1909 break;
1910 case 'day':
1911 $time += JIRAFEAU_DAY;
1912 break;
1913 case 'week':
1914 $time += JIRAFEAU_WEEK;
1915 break;
1916 case 'fortnight':
1917 $time += JIRAFEAU_FORTNIGHT;
1918 break;
1919 case 'month':
1920 $time += JIRAFEAU_MONTH;
1921 break;
1922 case 'quarter':
1923 $time += JIRAFEAU_QUARTER;
1924 break;
1925 case 'year':
1926 $time += JIRAFEAU_YEAR;
1927 break;
1928 default:
1929 $time = JIRAFEAU_INFINITY;
1930 break;
1931 }
1932 return $time;
1933 }
1934
1935
1936
1937
1938 /**
1939 * links or copy a local file
1940 * TODO: boolean in config for linking
1941 * @param string $filepath
1942 * @param $one_time_download is the file a one time download?
1943 * @param $key if not empty, protect the file with this key
1944 * @param $time the time of validity of the file
1945 * @param $ip uploader's ip
1946 * @param $crypt boolean asking to crypt or not
1947 * @param $link_name_length size of the link name
1948 * @returns an array containing some information
1949 * 'error' => information on possible errors
1950 * 'link' => the link name of the uploaded file
1951 * 'delete_link' => the link code to delete file
1952 */
1953 function jirafeau_copy_local_file($local_file_path, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
1954 {
1955 if (!file_exists($local_file_path)) {
1956 return (array(
1957 'error' =>
1958 array('has_error' => true,
1959 'why' => t('INTERNAL_ERROR_FILE_NOT_EXIST')),
1960 'link' => '',
1961 'delete_link' => ''));
1962 }
1963 if (
1964 // sanity check if file can be opened
1965 $file = fopen($local_file_path, 'r')
1966 ) {
1967 // close file pointer - it's not needed here
1968 fclose($file);
1969 $time_in_int = jirafeau_datestr_to_int($time);
1970 return jirafeau_add_file(
1971 jirafeau_create_file_array($local_file_path),
1972 $one_time_download,
1973 $key,
1974 $time_in_int,
1975 $ip,
1976 $crypt,
1977 $link_name_length,
1978 $file_hash_method,
1979 false
1980 );
1981 } else {
1982 return (array(
1983 'error' =>
1984 array('has_error' => true,
1985 'why' => t('INTERNAL_ERROR_FP_OPEN_LOCAL')),
1986 'link' => '',
1987 'delete_link' => ''));
1988 }
1989 }
1990
1991
1992 function jirafeau_create_file_array($file_path)
1993 {
1994 return [
1995 'type' => mime_content_type($file_path),
1996 'tmp_name' => $file_path,
1997 'name' => basename($file_path),
1998 'size' => filesize($file_path),
1999 ];
2000 }

patrick-canterino.de