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

patrick-canterino.de