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>
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.
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.
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/>.
23 * Transform a string in a path by separating each letters by a '/'.
24 * @return path finishing with a '/'
30 for ($i = 0; $i < strlen($s); $i++
) {
32 if (($i +
1) %
$block_size == 0) {
36 if (strlen($s) %
$block_size != 0) {
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
46 function base_16_to_64($num)
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
49 $hex2bin = array('0000', # 0
68 # Convert long hex string to bin.
70 for ($i = 0; $i < $size; $i++
) {
71 $b .= $hex2bin[hexdec($num[$i])];
73 # Convert long bin to base 64.
75 for ($i = $size - 6; $i >= 0; $i -= 6) {
76 $o = $m[bindec(substr($b, $i, 6))] . $o;
78 # Some few bits remaining ?
79 if ($i < 0 && $i > -6) {
80 $o = $m[bindec(substr($b, 0, $i +
6))] . $o;
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
90 function jirafeau_gen_random($l)
97 for ($i = 0; $i < $l; $i++
) {
98 $code .= dechex(rand(0, 15));
104 function jirafeau_gen_download_pass($length, $allowed_chars)
110 for ($i = 0; $i < $length; $i++
) {
111 $pass .= $allowed_chars[rand(0, strlen($allowed_chars) - 1)];
119 if (isset($_SERVER['HTTPS'])) {
120 if ('on' == strtolower($_SERVER['HTTPS']) ||
121 '1' == $_SERVER['HTTPS']) {
124 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
126 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
127 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
134 function jirafeau_human_size($octets)
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);
140 return round($o, 1) . $u[$p];
143 // Convert UTC timestamp to a datetime field
144 function jirafeau_get_datetimefield($timestamp)
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>';
154 function jirafeau_fatal_error($errorText, $cfg = array())
156 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
157 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
161 function jirafeau_clean_rm_link($link)
164 if (file_exists(VAR_LINKS
. $p . $link)) {
165 unlink(VAR_LINKS
. $p . $link);
167 if (file_exists(VAR_LINKS
. $p . $link . '_download')) {
168 unlink(VAR_LINKS
. $p . $link . '_download');
170 $parse = VAR_LINKS
. $p;
172 while (file_exists($parse)
173 && ($scan = scandir($parse))
174 && count($scan) == 2 // '.' and '..' folders => empty.
175 && basename($parse) != basename(VAR_LINKS
)) {
177 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
181 function jirafeau_clean_rm_file($hash)
184 $f = VAR_FILES
. $p . $hash;
185 if (file_exists($f) && is_file($f)) {
188 if (file_exists($f . '_count') && is_file($f . '_count')) {
189 unlink($f . '_count');
191 $parse = VAR_FILES
. $p;
193 while (file_exists($parse)
194 && ($scan = scandir($parse))
195 && count($scan) == 2 // '.' and '..' folders => empty.
196 && basename($parse) != basename(VAR_FILES
)) {
198 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
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
207 function jirafeau_ini_to_bytes($value)
209 $modifier = substr($value, -1);
210 $bytes = substr($value, 0, -1);
211 switch (strtoupper($modifier)) {
213 return intval($value);
234 * gets the maximum upload size according to php.ini
235 * @returns the maximum upload size in bytes
237 function jirafeau_get_max_upload_size_bytes()
240 jirafeau_ini_to_bytes(ini_get('post_max_size')),
241 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
246 * gets the maximum upload size according to php.ini
247 * @returns the maximum upload size string
249 function jirafeau_get_max_upload_size()
251 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
255 * get the maximal upload size for a data chunk in async uploads
256 * @param max_upload_chunk_size_bytes
258 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
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
264 return 10000000; // 10MB
269 jirafeau_get_max_upload_size_bytes(),
270 $max_upload_chunk_size_bytes
273 return $max_upload_chunk_size_bytes;
279 * gets a string explaining the error
280 * @param $code the error code
281 * @returns a string explaining the error
283 function jirafeau_upload_errstr($code)
286 case UPLOAD_ERR_INI_SIZE
:
287 case UPLOAD_ERR_FORM_SIZE
:
288 return t('Your file exceeds the maximum authorized file size. ');
290 case UPLOAD_ERR_PARTIAL
:
291 case UPLOAD_ERR_NO_FILE
:
293 t('Your file was not uploaded correctly. You may succeed in retrying. ');
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. ');
300 return t('Unknown error. ');
303 /** Remove link and it's file
304 * @param $link the link's name (hash)
307 function jirafeau_delete_link($link)
309 $l = jirafeau_get_link($link);
314 jirafeau_clean_rm_link($link);
320 if (file_exists(VAR_FILES
. $p . $hash. '_count')) {
321 $content = file(VAR_FILES
. $p . $hash. '_count');
322 $counter = trim($content[0]);
327 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
328 fwrite($handle, $counter);
333 jirafeau_clean_rm_file($hash);
338 * Delete a file and it's links.
340 function jirafeau_delete_file($hash)
343 /* Get all links files. */
344 $stack = array(VAR_LINKS
);
345 while (($d = array_shift($stack)) && $d != null) {
348 foreach ($dir as $node) {
349 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
350 preg_match('/\.tmp/i', "$node")) {
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));
363 if ($l['hash'] == $hash) {
365 jirafeau_delete_link($node);
370 jirafeau_clean_rm_file($hash);
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
380 function jirafeau_hash_file($method, $file_path)
384 return jirafeau_md5_outside($file_path);
386 return md5_file($file_path);
388 return jirafeau_gen_random(32);
390 return md5_file($file_path);
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
398 function jirafeau_md5_outside($file_path)
401 $handle = fopen($file_path, "r");
402 if ($handle === false) {
405 $size = filesize($file_path);
406 if ($size === false) {
409 $first = fread($handle, 64);
410 if ($first === false) {
413 if (fseek($handle, $size < 64 ?
0 : $size - 64) == -1) {
416 $last = fread($handle, 64);
417 if ($last === false) {
420 $out = md5($first . $last . $size);
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
440 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
442 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
445 array('has_error' => true,
446 'why' => jirafeau_upload_errstr($file['error'])),
448 'delete_link' => ''));
451 /* array representing no error */
452 $noerr = array('has_error' => false, 'why' => '');
454 /* Crypt file if option is enabled. */
457 if ($crypt == true && !(extension_loaded('sodium') == true)) {
458 error_log("PHP extension sodium not loaded, won't encrypt in Jirafeau");
460 if ($crypt == true && extension_loaded('sodium') == true) {
461 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name'].'crypt');
462 if (strlen($crypt_key) > 0) {
464 rename($file['tmp_name'].'crypt', $file['tmp_name']);
468 /* file information */
469 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
470 $name = str_replace(NL
, '', trim($file['name']));
471 $mime_type = $file['type'];
472 $size = $file['size'];
474 /* does file already exist ? */
477 if (file_exists(VAR_FILES
. $p . $hash)) {
478 $rc = unlink($file['tmp_name']);
479 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
480 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $hash)) {
486 array('has_error' => true,
487 'why' => t('INTERNAL_ERROR_DEL')),
489 'delete_link' => ''));
492 /* Increment or create count file. */
494 if (file_exists(VAR_FILES
. $p . $hash . '_count')) {
495 $content = file(VAR_FILES
. $p . $hash. '_count');
496 $counter = trim($content[0]);
499 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
500 fwrite($handle, $counter);
503 /* Create delete code. */
504 $delete_link_code = jirafeau_gen_random(5);
506 /* hash password or empty. */
509 $password = md5($key);
512 /* create link file */
513 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
514 $handle = fopen($link_tmp_name, 'w');
517 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
518 NL
. $hash. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
519 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C2' : 'O')
522 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
523 $l = s2p("$hash_link");
524 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
525 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
526 if (file_exists($link_tmp_name)) {
527 unlink($link_tmp_name);
532 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
533 fwrite($handle, $counter);
536 jirafeau_clean_rm_file($hash_link);
540 array('has_error' => true,
541 'why' => t('Internal error during file creation. ')),
543 'delete_link' => '');
545 return array( 'error' => $noerr,
546 'link' => $hash_link,
547 'delete_link' => $delete_link_code,
548 'crypt_key' => $crypt_key);
552 * Tells if a mime-type is viewable in a browser
553 * @param $mime the mime type
554 * @returns a boolean telling if a mime type is viewable
556 function jirafeau_is_viewable($mime)
559 $viewable = array('image', 'video', 'audio');
560 $decomposed = explode('/', $mime);
561 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
564 $viewable = array('text/plain');
565 if (in_array($mime, $viewable)) {
572 // Error handling functions.
573 //! Global array that contains all registered errors.
574 $error_list = array();
577 * Adds an error to the list of errors.
578 * @param $title the error's title
579 * @param $description is a human-friendly description of the problem.
581 function add_error($title, $description)
584 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
588 * Informs whether any error has been registered yet.
589 * @return true if there are errors.
594 return !empty($error_list);
598 * Displays all the errors.
600 function show_errors()
604 echo '<div class="error">';
605 foreach ($error_list as $error) {
612 function check_errors($cfg)
614 if (!($cfg['installation_done'] === true)) {
615 if (file_exists(JIRAFEAU_ROOT
. 'install.php')) {
616 header('Location: install.php');
619 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
623 if (!is_writable(VAR_FILES
)) {
624 add_error(t('FILE_DIR_W'), VAR_FILES
);
627 if (!is_writable(VAR_LINKS
)) {
628 add_error(t('LINK_DIR_W'), VAR_LINKS
);
631 if (!is_writable(VAR_ASYNC
)) {
632 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
635 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
636 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
639 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
640 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
645 * Read link information
646 * @return array containing information.
648 function jirafeau_get_link($hash)
651 $link = VAR_LINKS
. s2p("$hash") . $hash;
653 if (!file_exists($link)) {
658 $out['file_name'] = trim($c[0]);
659 $out['mime_type'] = trim($c[1]);
660 $out['file_size'] = trim($c[2]);
661 $out['key'] = trim($c[3], NL
);
662 $out['time'] = trim($c[4]);
663 $out['hash'] = trim($c[5]);
664 $out['onetime'] = trim($c[6]);
665 $out['upload_date'] = trim($c[7]);
666 $out['ip'] = trim($c[8]);
667 $out['link_code'] = trim($c[9]);
668 $out['crypted'] = trim($c[10]) == 'C2';
669 $out['crypted_legacy'] = trim($c[10]) == 'C';
675 * List files in admin interface.
677 function jirafeau_admin_list($name, $file_hash, $link_hash)
679 echo '<fieldset><legend>';
681 echo t('FILENAME') . ": " . jirafeau_escape($name);
683 if (!empty($file_hash)) {
684 echo t('FILE') . ": " . jirafeau_escape($file_hash);
686 if (!empty($link_hash)) {
687 echo t('LINK') . ": " . jirafeau_escape($link_hash);
689 if (empty($name) && empty($file_hash) && empty($link_hash)) {
696 echo '<th>' . t('ACTION') . '</th>';
699 /* Get all links files. */
700 $stack = array(VAR_LINKS
);
701 while (($d = array_shift($stack)) && $d != null) {
703 foreach ($dir as $node) {
704 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
705 preg_match('/\.tmp/i', "$node")) {
708 if (is_dir($d . $node)) {
709 /* Push new found directory. */
710 $stack[] = $d . $node . '/';
711 } elseif (is_file($d . $node)) {
712 /* Read link information. */
713 $l = jirafeau_get_link($node);
717 $ld = jirafeau_get_download_stats($node);
720 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
723 if (!empty($file_hash) && $file_hash != $l['hash']) {
726 if (!empty($link_hash) && $link_hash != $node) {
729 /* Print link information. */
732 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
733 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
734 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
735 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
736 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
737 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ?
'Yes' : 'No') . '<br/>';
738 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
739 if (strlen($l['ip']) > 0) {
740 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
742 echo t('DOWNLOAD_COUNT') . ': ' . $ld['count'] . '<br/>';
743 if ($ld['count'] > 0) {
744 echo t('DOWNLOAD_DATE') . ': ' . jirafeau_get_datetimefield($ld['date']) . '<br/>';
745 echo t('DOWNLOAD_IP') . ': ' . $ld['ip'] . '<br/>';
748 echo '<form method="post">' .
749 '<input type = "hidden" name = "action" value = "download"/>' .
750 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
751 jirafeau_admin_csrf_field() .
752 '<input type = "submit" value = "' . t('DL') . '" />' .
754 '<form method="post">' .
755 '<input type = "hidden" name = "action" value = "delete_link"/>' .
756 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
757 jirafeau_admin_csrf_field() .
758 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
760 '<form method="post">' .
761 '<input type = "hidden" name = "action" value = "delete_file"/>' .
762 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
763 jirafeau_admin_csrf_field() .
764 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
771 echo '</table></fieldset>';
775 * Clean expired files.
776 * @return number of cleaned files.
778 function jirafeau_admin_clean()
781 /* Get all links files. */
782 $stack = array(VAR_LINKS
);
783 while (($d = array_shift($stack)) && $d != null) {
786 foreach ($dir as $node) {
787 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
788 preg_match('/\.tmp/i', "$node")) {
792 if (is_dir($d . $node)) {
793 /* Push new found directory. */
794 $stack[] = $d . $node . '/';
795 } elseif (is_file($d . $node)) {
796 /* Read link information. */
797 $l = jirafeau_get_link(basename($node));
801 $p = s2p($l['hash']);
802 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
803 !file_exists(VAR_FILES
. $p . $l['hash']) ||
// invalid
804 !file_exists(VAR_FILES
. $p . $l['hash'] . '_count')) { // invalid
805 jirafeau_delete_link($node);
816 * Clean old async transfers.
817 * @return number of cleaned files.
819 function jirafeau_admin_clean_async()
822 /* Get all links files. */
823 $stack = array(VAR_ASYNC
);
824 while (($d = array_shift($stack)) && $d != null) {
827 foreach ($dir as $node) {
828 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
829 preg_match('/\.tmp/i', "$node")) {
833 if (is_dir($d . $node)) {
834 /* Push new found directory. */
835 $stack[] = $d . $node . '/';
836 } elseif (is_file($d . $node)) {
837 /* Read async information. */
838 $a = jirafeau_get_async_ref(basename($node));
842 /* Delete transfers older than 1 hour. */
843 if (time() - $a['last_edited'] > 3600) {
844 jirafeau_async_delete(basename($node));
854 * Better strval function for debug purposes
856 function jirafeau_strval($value)
858 if (gettype($value) == "boolean") {
859 return $value ?
'true' : 'false';
861 return strval($value);
865 * Show file/folder permissions
867 function jirafeau_fileperms($path)
869 $out = substr(sprintf("%o", @fileperms
($path)), -4) . ", ";
870 $out .= "read " . (is_readable($path) ?
"OK" : "KO") . ", ";
871 $out .= "write " . (is_writable($path) ?
"OK" : "KO");
876 * Show some useful informations for bug reporting.
878 function jirafeau_admin_bug_report($cfg)
880 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
881 $out .= "If you have a problem related to Jirafeau, please <a href='https://gitlab.com/mojo42/Jirafeau/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>";
883 $out .= "# Jirafeau<br/>";
884 $out .= "- version: " . JIRAFEAU_VERSION
. "<br/>";
885 $jirafeau_options = [
888 'litespeed_workaround',
893 'maximal_upload_size',
895 'max_upload_chunk_size_bytes'
897 foreach ($jirafeau_options as &$o) {
899 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
903 $out .= "# PHP options<br/>";
904 $out .= "- php version: " . phpversion() . "<br/>";
905 $out .= "- sodium version: " . phpversion('sodium') . "<br/>";
906 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
909 'upload_max_filesize',
911 'max_execution_time',
914 foreach ($php_options as &$o) {
916 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
918 $out .= "- can set_time_limit: " . (set_time_limit(0) ?
"yes" : "no") . "<br/>";
921 $out .= "# File permissions<br/>";
922 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
923 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES
) . "<br/>";
924 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS
) . "<br/>";
925 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC
) . "<br/>";
928 $out .= "# Server details<br/>";
929 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
932 $out .= "# OS details<br/>";
933 $out .= "- OS: " . php_uname() . "<br/>";
936 $out .= "# Browser details<br/>";
937 $out .= "<script type='text/javascript' lang='Javascript'>
938 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
939 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
940 document.write('- user agent: ' + navigator.userAgent + '<br/>');
945 $out .= "# Memory<br/>";
946 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
948 $out .= "</code></fieldset>";
953 * Read async transfer information
954 * @return array containing information.
956 function jirafeau_get_async_ref($ref)
959 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
961 if (!file_exists($refinfos)) {
965 $c = file($refinfos);
966 $out['file_name'] = trim($c[0]);
967 $out['mime_type'] = trim($c[1]);
968 $out['key'] = trim($c[2], NL
);
969 $out['time'] = trim($c[3]);
970 $out['onetime'] = trim($c[4]);
971 $out['ip'] = trim($c[5]);
972 $out['last_edited'] = trim($c[6]);
973 $out['next_code'] = trim($c[7]);
978 * Delete async transfer information
980 function jirafeau_async_delete($ref)
983 if (file_exists(VAR_ASYNC
. $p . $ref)) {
984 unlink(VAR_ASYNC
. $p . $ref);
986 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
987 unlink(VAR_ASYNC
. $p . $ref . '_data');
989 $parse = VAR_ASYNC
. $p;
991 while (file_exists($parse)
992 && ($scan = scandir($parse))
993 && count($scan) == 2 // '.' and '..' folders => empty.
994 && basename($parse) != basename(VAR_ASYNC
)) {
996 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1001 * Init a new asynchronous upload.
1002 * @param $filename Name of the file to send
1003 * @param $one_time One time upload parameter
1004 * @param $key eventual password (or blank)
1005 * @param $time time limit
1006 * @param $ip ip address of the client
1007 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1009 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1011 /* Create temporary folder. */
1014 $code = jirafeau_gen_random(4);
1016 $ref = jirafeau_gen_random(32);
1017 $p = VAR_ASYNC
. s2p($ref);
1018 } while (file_exists($p));
1019 @mkdir
($p, 0755, true);
1020 if (!file_exists($p)) {
1021 return 'Error: cannot create async folder.';
1024 /* touch empty data file */
1025 $w_path = $p . $ref . '_data';
1028 /* md5 password or empty */
1031 $password = md5($key);
1034 /* Store information. */
1036 $handle = fopen($p, 'w');
1039 str_replace(NL
, '', trim($filename)) . NL
.
1040 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
1041 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
1042 time() . NL
. $code . NL
1046 return $ref . NL
. $code ;
1050 * Append a piece of file on the asynchronous upload.
1051 * @param $ref asynchronous upload reference
1052 * @param $file piece of data
1053 * @param $code client code for this operation
1054 * @param $max_file_size maximum allowed file size
1055 * @return a string containing a next code to use or a string starting with 'Error'
1057 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1059 /* Get async infos. */
1060 $a = jirafeau_get_async_ref($ref);
1062 /* Check some errors. */
1063 if (count($a) == 0) {
1064 return "Error: cannot find transfer";
1066 if ($a['next_code'] != "$code") {
1067 return "Error: bad transfer code";
1069 if ($data['error'] != UPLOAD_ERR_OK
) {
1070 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1071 $data_details = print_r($data, true);
1072 return "Error: upload error: {$data_details}";
1074 if (empty($data['tmp_name'])) {
1075 return "Error: missing tmp_name";
1077 if (!is_uploaded_file($data['tmp_name'])) {
1078 return "Error: tmp_name may not be uploaded";
1084 $r_path = $data['tmp_name'];
1085 $w_path = VAR_ASYNC
. $p . $ref . '_data';
1087 /* Check that file size is not above upload limit. */
1088 if ($max_file_size > 0 &&
1089 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
1090 jirafeau_async_delete($ref);
1091 return "Error: file size is above upload limit";
1094 /* Concatenate data. */
1095 $r = fopen($r_path, 'r');
1096 $w = fopen($w_path, 'a');
1098 if (fwrite($w, fread($r, 1024)) === false) {
1101 jirafeau_async_delete($ref);
1102 return "Error: cannot write file";
1109 /* Update async file. */
1110 $code = jirafeau_gen_random(4);
1111 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
1114 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
1115 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
1116 time() . NL
. $code . NL
1123 * Finalize an asynchronous upload.
1124 * @param $ref asynchronous upload reference
1125 * @param $code client code for this operation
1126 * @param $crypt boolean asking to crypt or not
1127 * @param $link_name_length link name length
1128 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1130 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1132 /* Get async infos. */
1133 $a = jirafeau_get_async_ref($ref);
1135 ||
$a['next_code'] != "$code") {
1136 return "Error: bad code for ending transfer";
1139 /* Generate link infos. */
1140 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
1141 if (!file_exists($p)) {
1142 return "Error: referenced file does not exist";
1147 if ($crypt == true && extension_loaded('sodium') == true) {
1148 //$crypt_key = jirafeau_encrypt_file($p, $p);
1149 $crypt_key = jirafeau_encrypt_file($p, $p.'.crypt');
1150 if (strlen($crypt_key) > 0) {
1152 rename($p.'.crypt', $p);
1156 $hash = jirafeau_hash_file($file_hash_method, $p);
1157 $size = filesize($p);
1159 $delete_link_code = jirafeau_gen_random(5);
1161 /* File already exist ? */
1162 if (!file_exists(VAR_FILES
. $np)) {
1163 @mkdir
(VAR_FILES
. $np, 0755, true);
1165 if (!file_exists(VAR_FILES
. $np . $hash)) {
1166 rename($p, VAR_FILES
. $np . $hash);
1169 /* Increment or create count file. */
1171 if (file_exists(VAR_FILES
. $np . $hash . '_count')) {
1172 $content = file(VAR_FILES
. $np . $hash. '_count');
1173 $counter = trim($content[0]);
1176 $handle = fopen(VAR_FILES
. $np . $hash. '_count', 'w');
1177 fwrite($handle, $counter);
1181 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
1182 $handle = fopen($link_tmp_name, 'w');
1185 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
1186 $a['key'] . NL
. $a['time'] . NL
. $hash . NL
. $a['onetime'] . NL
.
1187 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C2' : 'O')
1190 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1191 $l = s2p("$hash_link");
1192 if (!@mkdir
(VAR_LINKS
. $l, 0755, true)) {
1193 return "Error: cannot create folder in LINKS";
1195 if (!rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
1196 return "Error: cannot rename file in LINKS";
1199 /* Clean async upload. */
1200 jirafeau_async_delete($ref);
1201 return $hash_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
1204 function jirafeau_crypt_create_iv($base, $size)
1207 while (strlen($iv) < $size) {
1210 $iv = substr($iv, 0, $size);
1215 * Crypt file and returns decrypt key.
1216 * @param $fp_src file path to the file to crypt.
1217 * @param $fp_dst file path to the file to write crypted file (could be the same).
1218 * @return decrypt key composed of the key and the iv separated by a point ('.')
1220 function jirafeau_encrypt_file($fp_src, $fp_dst)
1222 $fs = filesize($fp_src);
1223 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('sodium') == true)) {
1228 $crypt_key = bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
/ 2));
1230 [$crypt_state, $crypt_header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($crypt_key);
1232 $r = fopen($fp_src, 'rb');
1233 $w = fopen($fp_dst, 'wb');
1234 fwrite($w, $crypt_header);
1236 for ($i = 0; $i < $fs; $i +
= JIRAFEAU_SODIUM_CHUNKSIZE
) {
1237 $to_enc = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE
);
1238 $enc = sodium_crypto_secretstream_xchacha20poly1305_push($crypt_state, $to_enc);
1240 if (fwrite($w, $enc) === false) {
1249 sodium_memzero($crypt_state);
1256 * @param $fp_src file path to the file to decrypt.
1257 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1258 * @param $k string composed of the key and the iv separated by a point ('.')
1259 * @return key used to decrypt. a string of length 0 is returned if failed.
1261 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1263 $fs = filesize($fp_src);
1264 if ($fs === false ||
$fs == 0 ||
extension_loaded('sodium') == false) {
1269 $r = fopen(VAR_FILES
. $p . $link['hash'], 'rb');
1271 $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES
);
1274 $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $crypt_key);
1278 for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES
; $i < $fs; $i +
= JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES
) {
1279 $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES
);
1280 [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
1287 sodium_memzero($crypt_state);
1294 * @param $fp_src file path to the file to decrypt.
1295 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1296 * @param $k string composed of the key and the iv separated by a point ('.')
1297 * @return key used to decrypt. a string of length 0 is returned if failed.
1299 function jirafeau_decrypt_file_legacy($fp_src, $fp_dst, $k)
1301 $fs = filesize($fp_src);
1302 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1307 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1308 /* Extract key and iv. */
1310 $hash_key = md5($crypt_key);
1311 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1313 $r = fopen($fp_src, 'r');
1314 $w = fopen($fp_dst, 'c');
1316 $dec = mdecrypt_generic($m, fread($r, 1024));
1317 if (fwrite($w, $dec) === false) {
1324 mcrypt_generic_deinit($m);
1325 mcrypt_module_close($m);
1330 * Check if Jirafeau is password protected for visitors.
1331 * @return true if Jirafeau is password protected, false otherwise.
1333 function jirafeau_has_upload_password($cfg)
1335 return count($cfg['upload_password']) > 0;
1339 * Challenge password for a visitor.
1340 * @param $password password to be challenged
1341 * @return true if password is valid, false otherwise.
1343 function jirafeau_challenge_upload_password($cfg, $password)
1345 if (!jirafeau_has_upload_password($cfg)) {
1348 foreach ($cfg['upload_password'] as $p) {
1349 if ($password == $p) {
1357 * Test if the given IP is whitelisted by the given list.
1359 * @param $allowedIpList array of allowed IPs
1360 * @param $challengedIp IP to be challenged
1361 * @return true if IP is authorized, false otherwise.
1363 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1365 foreach ($allowedIpList as $i) {
1366 if ($i == $challengedIp) {
1369 // CIDR test for IPv4 only.
1370 if (strpos($i, '/') !== false) {
1371 list($subnet, $mask) = explode('/', $i);
1372 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1381 * Check if Jirafeau has a restriction on the IP address for uploading.
1382 * @return true if uploading is IP restricted, false otherwise.
1384 function jirafeau_upload_has_ip_restriction($cfg)
1386 return count($cfg['upload_ip']) > 0;
1390 * Test if visitor's IP is authorized to upload at all.
1392 * @param $cfg configuration
1393 * @param $challengedIp IP to be challenged
1394 * @return true if IP is authorized, false otherwise.
1396 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1398 // If no IP address have been listed, allow upload from any IP
1399 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1402 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1406 * Test if visitor's IP is authorized to upload without a password.
1408 * @param $cfg configuration
1409 * @param $challengedIp IP to be challenged
1410 * @return true if IP is authorized, false otherwise.
1412 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1414 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1418 * Test if visitor's IP is authorized or password is supplied and authorized
1419 * @param $ip IP to be challenged
1420 * @param $password password to be challenged
1421 * @return true if access is valid, false otherwise.
1423 function jirafeau_challenge_upload($cfg, $ip, $password)
1425 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1426 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1427 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1431 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1432 * @return true if admin interface is IP restricted, false otherwise.
1434 function jirafeau_admin_has_ip_restriction($cfg)
1436 return count($cfg['admin_ip']) > 0;
1440 * Test if visitor's IP is authorized to access the admin interface.
1442 * @param $cfg configuration
1443 * @param $challengedIp IP to be challenged
1444 * @return true if IP is authorized, false otherwise.
1446 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1448 // If no IP address have been listed, allow upload from any IP
1449 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1452 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1455 /** Tell if we have some HTTP headers generated by a proxy */
1456 function has_http_forwarded()
1459 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1460 !empty($_SERVER['http_X_forwarded_for']);
1464 * Generate IP list from HTTP headers generated by a proxy
1465 * @return array of IP strings
1467 function get_ip_list_http_forwarded()
1470 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1471 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1475 foreach ($l as $ip) {
1476 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1479 if (!empty($_SERVER['http_X_forwarded_for'])) {
1480 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1481 foreach ($l as $ip) {
1482 // Separate IP from port
1483 $ipa = explode(':', $ip);
1484 if ($ipa === false) {
1488 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1495 * Get the ip address of the client from REMOTE_ADDR
1496 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1497 * @returns the client ip address
1499 function get_ip_address($cfg)
1501 $remote = $_SERVER['REMOTE_ADDR'];
1502 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1506 $ip_list = get_ip_list_http_forwarded();
1507 if (count($ip_list) == 0) {
1511 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1512 if ($remote != $proxy_ip) {
1515 // Take the last IP (the one which has been set by the defined proxy).
1516 return end($ip_list);
1522 * Convert hexadecimal string to base64
1524 function hex_to_base64($hex)
1527 foreach (str_split($hex, 2) as $pair) {
1528 $b .= chr(hexdec($pair));
1530 return base64_encode($b);
1534 * Replace markers in templates.
1536 * Available markers have the scheme "###MARKERNAME###".
1538 * @param $content string Template text with markers
1539 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1540 * @return Template with replaced markers
1542 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1545 '/###ORGANISATION###/',
1546 '/###CONTACTPERSON###/',
1549 $replacements = array(
1550 $GLOBALS['cfg']['organisation'],
1551 $GLOBALS['cfg']['contactperson'],
1552 $GLOBALS['cfg']['web_root']
1554 $content = preg_replace($patterns, $replacements, $content);
1556 if (true === $htmllinebreaks) {
1557 $content = nl2br($content);
1563 function jirafeau_escape($string)
1565 return htmlspecialchars($string, ENT_QUOTES
);
1568 function jirafeau_admin_session_start()
1570 $_SESSION['admin_auth'] = true;
1571 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1574 function jirafeau_session_end()
1576 $_SESSION = array();
1580 function jirafeau_admin_session_logged()
1582 return isset($_SESSION['admin_auth']) &&
1583 isset($_SESSION['admin_csrf']) &&
1584 isset($_POST['admin_csrf']) &&
1585 $_SESSION['admin_auth'] === true &&
1586 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1589 function jirafeau_admin_csrf_field()
1591 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1594 function jirafeau_user_session_start()
1596 $_SESSION['user_auth'] = true;
1599 function jirafeau_user_session_logged()
1601 return isset($_SESSION['user_auth']) &&
1602 $_SESSION['user_auth'] === true;
1605 function jirafeau_dir_size($dir)
1608 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT
) as $entry) {
1609 $size +
= is_file($entry) ?
filesize($entry) : jirafeau_dir_size($entry);
1614 function jirafeau_export_cfg($cfg)
1616 $content = '<?php' . NL
;
1617 $content .= '/* This file was generated by the install process. ' .
1618 'You can edit it. Please see config.original.php to understand the ' .
1619 'configuration items. */' . NL
;
1620 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1622 $fileWrite = file_put_contents(JIRAFEAU_CFG
, $content);
1624 if (false === $fileWrite) {
1625 jirafeau_fatal_error(t('Can not write local configuration file'));
1629 function jirafeau_mkdir($path)
1631 return !(!file_exists($path) && !@mkdir
($path, 0755));
1635 * Returns true whether the path is writable or we manage to make it
1636 * so, which essentially is the same thing.
1637 * @param $path is the file or directory to be tested.
1638 * @return true if $path is writable.
1640 function jirafeau_is_writable($path)
1642 /* "@" gets rid of error messages. */
1643 return is_writable($path) || @chmod
($path, 0777);
1646 function jirafeau_check_var_dir($path)
1648 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1649 $mkdir_str2 = t('MANUAL_CREATE');
1650 $write_str1 = t('DIR_NOT_W') . ':';
1651 $write_str2 = t('You should give the write permission to the web server on ' .
1653 $solution_str = t('HERE_SOLUTION') . ':';
1655 if (!jirafeau_mkdir($path) ||
!jirafeau_is_writable($path)) {
1656 return array('has_error' => true,
1657 'why' => $mkdir_str1 . '<br /><code>' .
1658 $path . '</code><br />' . $solution_str .
1659 '<br />' . $mkdir_str2);
1662 foreach (array('files', 'links', 'async') as $subdir) {
1663 $subpath = $path.$subdir;
1665 if (!jirafeau_mkdir($subpath) ||
!jirafeau_is_writable($subpath)) {
1666 return array('has_error' => true,
1667 'why' => $mkdir_str1 . '<br /><code>' .
1668 $subpath . '</code><br />' . $solution_str .
1669 '<br />' . $mkdir_str2);
1673 return array('has_error' => false, 'why' => '');
1676 function jirafeau_add_ending_slash($path)
1678 return $path . ((substr($path, -1) == '/') ?
'' : '/');
1681 function jirafeau_default_web_root()
1683 $url_scheme = (isset($_SERVER['HTTPS'])) ?
'https://' : 'http://';
1684 return $url_scheme . $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1687 function jirafeau_get_download_stats($hash)
1689 $filename = VAR_LINKS
. s2p("$hash") . $hash . '_download';
1691 if (!file_exists($filename)) {
1692 return array('count'=>0);
1695 $c = file($filename);
1696 $data['count'] = trim($c[0]);
1697 $data['date'] = trim($c[1]);
1698 $data['ip'] = trim($c[2]);
1703 function jirafeau_write_download_stats($hash, $ip)
1705 $data = jirafeau_get_download_stats($hash);
1706 $count = $data['count'];
1709 $filename = VAR_LINKS
. s2p("$hash") . $hash . '_download';
1711 $handle = fopen($filename, 'w');
1712 fwrite($handle, $count . NL
. time() . NL
. $ip);