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

patrick-canterino.de