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));
106 if (isset($_SERVER['HTTPS'])) {
107 if ('on' == strtolower($_SERVER['HTTPS']) ||
108 '1' == $_SERVER['HTTPS']) {
111 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
113 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
114 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
121 function jirafeau_human_size($octets)
123 $u = array('B', 'KB', 'MB', 'GB', 'TB');
124 $o = max($octets, 0);
125 $p = min(floor(($o ?
log($o) : 0) / log(1024)), count($u) - 1);
127 return round($o, 1) . $u[$p];
130 // Convert UTC timestamp to a datetime field
131 function jirafeau_get_datetimefield($timestamp)
133 $content = '<span class="datetime" data-datetime="' . strftime('%Y-%m-%d %H:%M', $timestamp) . '">'
134 . strftime('%Y-%m-%d %H:%M', $timestamp) . ' (GMT)</span>';
138 function jirafeau_fatal_error($errorText, $cfg = array())
140 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
141 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
145 function jirafeau_non_fatal_error($errorText)
147 echo '<div class="error"><p>' . $errorText . '</p></div>';
150 function jirafeau_clean_rm_link($link)
153 if (file_exists(VAR_LINKS
. $p . $link)) {
154 unlink(VAR_LINKS
. $p . $link);
156 $parse = VAR_LINKS
. $p;
158 while (file_exists($parse)
159 && ($scan = scandir($parse))
160 && count($scan) == 2 // '.' and '..' folders => empty.
161 && basename($parse) != basename(VAR_LINKS
)) {
163 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
167 function jirafeau_clean_rm_file($hash)
170 $f = VAR_FILES
. $p . $hash;
171 if (file_exists($f) && is_file($f)) {
174 if (file_exists($f . '_count') && is_file($f . '_count')) {
175 unlink($f . '_count');
177 $parse = VAR_FILES
. $p;
179 while (file_exists($parse)
180 && ($scan = scandir($parse))
181 && count($scan) == 2 // '.' and '..' folders => empty.
182 && basename($parse) != basename(VAR_FILES
)) {
184 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
189 * transforms a php.ini string representing a value in an integer
190 * @param $value the value from php.ini
191 * @returns an integer for this value
193 function jirafeau_ini_to_bytes($value)
195 $modifier = substr($value, -1);
196 $bytes = substr($value, 0, -1);
197 switch (strtoupper($modifier)) {
199 return intval($value);
220 * gets the maximum upload size according to php.ini
221 * @returns the maximum upload size in bytes
223 function jirafeau_get_max_upload_size_bytes()
226 jirafeau_ini_to_bytes(ini_get('post_max_size')),
227 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
232 * gets the maximum upload size according to php.ini
233 * @returns the maximum upload size string
235 function jirafeau_get_max_upload_size()
237 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
241 * get the maximal upload size for a data chunk in async uploads
242 * @param max_upload_chunk_size_bytes
244 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
246 if ($max_upload_chunk_size_bytes == 0) {
247 $size = jirafeau_get_max_upload_size_bytes();
248 // Jirafeau must choose an arbitrary number as PHP config does not give any limit nor $max_upload_chunk_size_bytes
250 return 10000000; // 10MB
255 jirafeau_get_max_upload_size_bytes(),
256 $max_upload_chunk_size_bytes
259 return $max_upload_chunk_size_bytes;
265 * gets a string explaining the error
266 * @param $code the error code
267 * @returns a string explaining the error
269 function jirafeau_upload_errstr($code)
272 case UPLOAD_ERR_INI_SIZE
:
273 case UPLOAD_ERR_FORM_SIZE
:
274 return t('Your file exceeds the maximum authorized file size. ');
276 case UPLOAD_ERR_PARTIAL
:
277 case UPLOAD_ERR_NO_FILE
:
279 t('Your file was not uploaded correctly. You may succeed in retrying. ');
281 case UPLOAD_ERR_NO_TMP_DIR
:
282 case UPLOAD_ERR_CANT_WRITE
:
283 case UPLOAD_ERR_EXTENSION
:
284 return t('Internal error. You may not succeed in retrying. ');
286 return t('Unknown error. ');
289 /** Remove link and it's file
290 * @param $link the link's name (hash)
293 function jirafeau_delete_link($link)
295 $l = jirafeau_get_link($link);
300 jirafeau_clean_rm_link($link);
306 if (file_exists(VAR_FILES
. $p . $hash. '_count')) {
307 $content = file(VAR_FILES
. $p . $hash. '_count');
308 $counter = trim($content[0]);
313 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
314 fwrite($handle, $counter);
319 jirafeau_clean_rm_file($hash);
324 * Delete a file and it's links.
326 function jirafeau_delete_file($hash)
329 /* Get all links files. */
330 $stack = array(VAR_LINKS
);
331 while (($d = array_shift($stack)) && $d != null) {
334 foreach ($dir as $node) {
335 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
336 preg_match('/\.tmp/i', "$node")) {
340 if (is_dir($d . $node)) {
341 /* Push new found directory. */
342 $stack[] = $d . $node . '/';
343 } elseif (is_file($d . $node)) {
344 /* Read link informations. */
345 $l = jirafeau_get_link(basename($node));
349 if ($l['hash'] == $hash) {
351 jirafeau_delete_link($node);
356 jirafeau_clean_rm_file($hash);
361 /** hash file's content
362 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
363 * @param $file_path file to hash
364 * @returns hash string
366 function jirafeau_hash_file($method, $file_path)
370 return jirafeau_md5_outside($file_path);
372 return md5_file($file_path);
374 return jirafeau_gen_random(32);
376 return md5_file($file_path);
379 /** hash part of file: start, end and size.
380 * This is a partial file hash, faster but weaker.
381 * @param $file_path file to hash
382 * @returns hash string
384 function jirafeau_md5_outside($file_path)
387 $handle = fopen($file_path, "r");
388 if ($handle === false) {
391 $size = filesize($file_path);
392 if ($size === false) {
395 $first = fread($handle, 64);
396 if ($first === false) {
399 if (fseek($handle, $size < 64 ?
0 : $size - 64) == -1) {
402 $last = fread($handle, 64);
403 if ($last === false) {
406 $out = md5($first . $last . $size);
413 * handles an uploaded file
414 * @param $file the file struct given by $_FILE[]
415 * @param $one_time_download is the file a one time download ?
416 * @param $key if not empty, protect the file with this key
417 * @param $time the time of validity of the file
418 * @param $ip uploader's ip
419 * @param $crypt boolean asking to crypt or not
420 * @param $link_name_length size of the link name
421 * @returns an array containing some information
422 * 'error' => information on possible errors
423 * 'link' => the link name of the uploaded file
424 * 'delete_link' => the link code to delete file
426 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
428 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
431 array('has_error' => true,
432 'why' => jirafeau_upload_errstr($file['error'])),
434 'delete_link' => ''));
437 /* array representing no error */
438 $noerr = array('has_error' => false, 'why' => '');
440 /* Crypt file if option is enabled. */
443 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
444 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
446 if ($crypt == true && extension_loaded('mcrypt') == true) {
447 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
448 if (strlen($crypt_key) > 0) {
453 /* file information */
454 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
455 $name = str_replace(NL
, '', trim($file['name']));
456 $mime_type = $file['type'];
457 $size = $file['size'];
459 /* does file already exist ? */
462 if (file_exists(VAR_FILES
. $p . $hash)) {
463 $rc = unlink($file['tmp_name']);
464 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
465 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $hash)) {
471 array('has_error' => true,
472 'why' => t('INTERNAL_ERROR_DEL')),
474 'delete_link' => ''));
477 /* Increment or create count file. */
479 if (file_exists(VAR_FILES
. $p . $hash . '_count')) {
480 $content = file(VAR_FILES
. $p . $hash. '_count');
481 $counter = trim($content[0]);
484 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
485 fwrite($handle, $counter);
488 /* Create delete code. */
489 $delete_link_code = jirafeau_gen_random(5);
491 /* hash password or empty. */
494 $password = md5($key);
497 /* create link file */
498 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
499 $handle = fopen($link_tmp_name, 'w');
502 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
503 NL
. $hash. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
504 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O')
507 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
508 $l = s2p("$hash_link");
509 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
510 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
511 if (file_exists($link_tmp_name)) {
512 unlink($link_tmp_name);
517 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
518 fwrite($handle, $counter);
521 jirafeau_clean_rm_file($hash_link);
525 array('has_error' => true,
526 'why' => t('Internal error during file creation. ')),
528 'delete_link' => '');
530 return array( 'error' => $noerr,
531 'link' => $hash_link,
532 'delete_link' => $delete_link_code,
533 'crypt_key' => $crypt_key);
537 * Tells if a mime-type is viewable in a browser
538 * @param $mime the mime type
539 * @returns a boolean telling if a mime type is viewable
541 function jirafeau_is_viewable($mime)
544 $viewable = array('image', 'video', 'audio');
545 $decomposed = explode('/', $mime);
546 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
549 $viewable = array('text/plain');
550 if (in_array($mime, $viewable)) {
557 // Error handling functions.
558 //! Global array that contains all registered errors.
559 $error_list = array();
562 * Adds an error to the list of errors.
563 * @param $title the error's title
564 * @param $description is a human-friendly description of the problem.
566 function add_error($title, $description)
569 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
573 * Informs whether any error has been registered yet.
574 * @return true if there are errors.
579 return !empty($error_list);
583 * Displays all the errors.
585 function show_errors()
589 echo '<div class="error">';
590 foreach ($error_list as $error) {
597 function check_errors($cfg)
599 if (!($cfg['installation_done'] === true)) {
600 if (file_exists(JIRAFEAU_ROOT
. 'install.php')) {
601 header('Location: install.php');
604 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
608 if (!is_writable(VAR_FILES
)) {
609 add_error(t('FILE_DIR_W'), VAR_FILES
);
612 if (!is_writable(VAR_LINKS
)) {
613 add_error(t('LINK_DIR_W'), VAR_LINKS
);
616 if (!is_writable(VAR_ASYNC
)) {
617 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
620 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
621 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
624 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
625 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
627 if ($cfg['upload_ldap_auth'] === true) {
628 if (sizeof($cfg['upload_password']) > 0) {
629 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'upload_ldap_auth=true<br>sizeof(upload_password) > 0');
631 if (sizeof($cfg['upload_ip_nopassword']) > 0) {
632 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'upload_ldap_auth=true<br>sizeof(upload_ip_nopassword) > 0');
638 * Read link information
639 * @return array containing information.
641 function jirafeau_get_link($hash)
644 $link = VAR_LINKS
. s2p("$hash") . $hash;
646 if (!file_exists($link)) {
651 $out['file_name'] = trim($c[0]);
652 $out['mime_type'] = trim($c[1]);
653 $out['file_size'] = trim($c[2]);
654 $out['key'] = trim($c[3], NL
);
655 $out['time'] = trim($c[4]);
656 $out['hash'] = trim($c[5]);
657 $out['onetime'] = trim($c[6]);
658 $out['upload_date'] = trim($c[7]);
659 $out['ip'] = trim($c[8]);
660 $out['link_code'] = trim($c[9]);
661 $out['crypted'] = trim($c[10]) == 'C';
667 * List files in admin interface.
669 function jirafeau_admin_list($name, $file_hash, $link_hash)
671 echo '<fieldset><legend>';
673 echo t('FILENAME') . ": " . jirafeau_escape($name);
675 if (!empty($file_hash)) {
676 echo t('FILE') . ": " . jirafeau_escape($file_hash);
678 if (!empty($link_hash)) {
679 echo t('LINK') . ": " . jirafeau_escape($link_hash);
681 if (empty($name) && empty($file_hash) && empty($link_hash)) {
688 echo '<th>' . t('ACTION') . '</th>';
691 /* Get all links files. */
692 $stack = array(VAR_LINKS
);
693 while (($d = array_shift($stack)) && $d != null) {
695 foreach ($dir as $node) {
696 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
697 preg_match('/\.tmp/i', "$node")) {
700 if (is_dir($d . $node)) {
701 /* Push new found directory. */
702 $stack[] = $d . $node . '/';
703 } elseif (is_file($d . $node)) {
704 /* Read link information. */
705 $l = jirafeau_get_link($node);
711 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
714 if (!empty($file_hash) && $file_hash != $l['hash']) {
717 if (!empty($link_hash) && $link_hash != $node) {
720 /* Print link information. */
723 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
724 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
725 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
726 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
727 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
728 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ?
'Yes' : 'No') . '<br/>';
729 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
730 if (strlen($l['ip']) > 0) {
731 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
734 echo '<form method="post">' .
735 '<input type = "hidden" name = "action" value = "download"/>' .
736 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
737 jirafeau_admin_csrf_field() .
738 '<input type = "submit" value = "' . t('DL') . '" />' .
740 '<form method="post">' .
741 '<input type = "hidden" name = "action" value = "delete_link"/>' .
742 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
743 jirafeau_admin_csrf_field() .
744 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
746 '<form method="post">' .
747 '<input type = "hidden" name = "action" value = "delete_file"/>' .
748 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
749 jirafeau_admin_csrf_field() .
750 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
757 echo '</table></fieldset>';
761 * Clean expired files.
762 * @return number of cleaned files.
764 function jirafeau_admin_clean()
767 /* Get all links files. */
768 $stack = array(VAR_LINKS
);
769 while (($d = array_shift($stack)) && $d != null) {
772 foreach ($dir as $node) {
773 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
774 preg_match('/\.tmp/i', "$node")) {
778 if (is_dir($d . $node)) {
779 /* Push new found directory. */
780 $stack[] = $d . $node . '/';
781 } elseif (is_file($d . $node)) {
782 /* Read link information. */
783 $l = jirafeau_get_link(basename($node));
787 $p = s2p($l['hash']);
788 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
789 !file_exists(VAR_FILES
. $p . $l['hash']) ||
// invalid
790 !file_exists(VAR_FILES
. $p . $l['hash'] . '_count')) { // invalid
791 jirafeau_delete_link($node);
802 * Clean old async transfers.
803 * @return number of cleaned files.
805 function jirafeau_admin_clean_async()
808 /* Get all links files. */
809 $stack = array(VAR_ASYNC
);
810 while (($d = array_shift($stack)) && $d != null) {
813 foreach ($dir as $node) {
814 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
815 preg_match('/\.tmp/i', "$node")) {
819 if (is_dir($d . $node)) {
820 /* Push new found directory. */
821 $stack[] = $d . $node . '/';
822 } elseif (is_file($d . $node)) {
823 /* Read async information. */
824 $a = jirafeau_get_async_ref(basename($node));
828 /* Delete transfers older than 1 hour. */
829 if (time() - $a['last_edited'] > 3600) {
830 jirafeau_async_delete(basename($node));
840 * Better strval function for debug purposes
842 function jirafeau_strval($value)
844 if (gettype($value) == "boolean") {
845 return $value ?
'true' : 'false';
847 return strval($value);
851 * Show file/folder permissions
853 function jirafeau_fileperms($path)
855 $out = substr(sprintf("%o", @fileperms
($path)), -4) . ", ";
856 $out .= "read " . (is_readable($path) ?
"OK" : "KO") . ", ";
857 $out .= "write " . (is_writable($path) ?
"OK" : "KO");
862 * Show some useful informations for bug reporting.
864 function jirafeau_admin_bug_report($cfg)
866 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
867 $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>";
869 $out .= "# Jirafeau<br/>";
870 $out .= "- version: " . JIRAFEAU_VERSION
. "<br/>";
871 $jirafeau_options = [
874 'litespeed_workaround',
879 'maximal_upload_size',
881 'max_upload_chunk_size_bytes'
883 foreach ($jirafeau_options as &$o) {
885 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
889 $out .= "# PHP options<br/>";
890 $out .= "- php version: " . phpversion() . "<br/>";
891 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
894 'upload_max_filesize',
896 'max_execution_time',
899 foreach ($php_options as &$o) {
901 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
903 $out .= "- can set_time_limit: " . (set_time_limit(0) ?
"yes" : "no") . "<br/>";
906 $out .= "# File permissions<br/>";
907 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
908 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES
) . "<br/>";
909 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS
) . "<br/>";
910 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC
) . "<br/>";
913 $out .= "# Server details<br/>";
914 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
917 $out .= "# OS details<br/>";
918 $out .= "- OS: " . php_uname() . "<br/>";
921 $out .= "# Browser details<br/>";
922 $out .= "<script type='text/javascript' lang='Javascript'>
923 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
924 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
925 document.write('- user agent: ' + navigator.userAgent + '<br/>');
930 $out .= "# Memory<br/>";
931 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
933 $out .= "</code></fieldset>";
938 * Read async transfer information
939 * @return array containing information.
941 function jirafeau_get_async_ref($ref)
944 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
946 if (!file_exists($refinfos)) {
950 $c = file($refinfos);
951 $out['file_name'] = trim($c[0]);
952 $out['mime_type'] = trim($c[1]);
953 $out['key'] = trim($c[2], NL
);
954 $out['time'] = trim($c[3]);
955 $out['onetime'] = trim($c[4]);
956 $out['ip'] = trim($c[5]);
957 $out['last_edited'] = trim($c[6]);
958 $out['next_code'] = trim($c[7]);
963 * Delete async transfer information
965 function jirafeau_async_delete($ref)
968 if (file_exists(VAR_ASYNC
. $p . $ref)) {
969 unlink(VAR_ASYNC
. $p . $ref);
971 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
972 unlink(VAR_ASYNC
. $p . $ref . '_data');
974 $parse = VAR_ASYNC
. $p;
976 while (file_exists($parse)
977 && ($scan = scandir($parse))
978 && count($scan) == 2 // '.' and '..' folders => empty.
979 && basename($parse) != basename(VAR_ASYNC
)) {
981 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
986 * Init a new asynchronous upload.
987 * @param $filename Name of the file to send
988 * @param $one_time One time upload parameter
989 * @param $key eventual password (or blank)
990 * @param $time time limit
991 * @param $ip ip address of the client
992 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
994 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
996 /* Create temporary folder. */
999 $code = jirafeau_gen_random(4);
1001 $ref = jirafeau_gen_random(32);
1002 $p = VAR_ASYNC
. s2p($ref);
1003 } while (file_exists($p));
1004 @mkdir
($p, 0755, true);
1005 if (!file_exists($p)) {
1006 return 'Error: cannot create async folder.';
1009 /* touch empty data file */
1010 $w_path = $p . $ref . '_data';
1013 /* md5 password or empty */
1016 $password = md5($key);
1019 /* Store information. */
1021 $handle = fopen($p, 'w');
1024 str_replace(NL
, '', trim($filename)) . NL
.
1025 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
1026 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
1027 time() . NL
. $code . NL
1031 return $ref . NL
. $code ;
1035 * Append a piece of file on the asynchronous upload.
1036 * @param $ref asynchronous upload reference
1037 * @param $file piece of data
1038 * @param $code client code for this operation
1039 * @param $max_file_size maximum allowed file size
1040 * @return a string containing a next code to use or a string starting with 'Error'
1042 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1044 /* Get async infos. */
1045 $a = jirafeau_get_async_ref($ref);
1047 /* Check some errors. */
1048 if (count($a) == 0) {
1049 return "Error: cannot find transfer";
1051 if ($a['next_code'] != "$code") {
1052 return "Error: bad transfer code";
1054 if ($data['error'] != UPLOAD_ERR_OK
) {
1055 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1056 $data_details = print_r($data, true);
1057 return "Error: upload error: {$data_details}";
1059 if (empty($data['tmp_name'])) {
1060 return "Error: missing tmp_name";
1062 if (!is_uploaded_file($data['tmp_name'])) {
1063 return "Error: tmp_name may not be uploaded";
1069 $r_path = $data['tmp_name'];
1070 $w_path = VAR_ASYNC
. $p . $ref . '_data';
1072 /* Check that file size is not above upload limit. */
1073 if ($max_file_size > 0 &&
1074 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
1075 jirafeau_async_delete($ref);
1076 return "Error: file size is above upload limit";
1079 /* Concatenate data. */
1080 $r = fopen($r_path, 'r');
1081 $w = fopen($w_path, 'a');
1083 if (fwrite($w, fread($r, 1024)) === false) {
1086 jirafeau_async_delete($ref);
1087 return "Error: cannot write file";
1094 /* Update async file. */
1095 $code = jirafeau_gen_random(4);
1096 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
1099 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
1100 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
1101 time() . NL
. $code . NL
1108 * Finalize an asynchronous upload.
1109 * @param $ref asynchronous upload reference
1110 * @param $code client code for this operation
1111 * @param $crypt boolean asking to crypt or not
1112 * @param $link_name_length link name length
1113 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1115 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1117 /* Get async infos. */
1118 $a = jirafeau_get_async_ref($ref);
1120 ||
$a['next_code'] != "$code") {
1121 return "Error: bad code for ending transfer";
1124 /* Generate link infos. */
1125 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
1126 if (!file_exists($p)) {
1127 return "Error: referenced file does not exist";
1132 if ($crypt == true && extension_loaded('mcrypt') == true) {
1133 $crypt_key = jirafeau_encrypt_file($p, $p);
1134 if (strlen($crypt_key) > 0) {
1139 $hash = jirafeau_hash_file($file_hash_method, $p);
1140 $size = filesize($p);
1142 $delete_link_code = jirafeau_gen_random(5);
1144 /* File already exist ? */
1145 if (!file_exists(VAR_FILES
. $np)) {
1146 @mkdir
(VAR_FILES
. $np, 0755, true);
1148 if (!file_exists(VAR_FILES
. $np . $hash)) {
1149 rename($p, VAR_FILES
. $np . $hash);
1152 /* Increment or create count file. */
1154 if (file_exists(VAR_FILES
. $np . $hash . '_count')) {
1155 $content = file(VAR_FILES
. $np . $hash. '_count');
1156 $counter = trim($content[0]);
1159 $handle = fopen(VAR_FILES
. $np . $hash. '_count', 'w');
1160 fwrite($handle, $counter);
1164 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
1165 $handle = fopen($link_tmp_name, 'w');
1168 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
1169 $a['key'] . NL
. $a['time'] . NL
. $hash . NL
. $a['onetime'] . NL
.
1170 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O')
1173 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1174 $l = s2p("$hash_link");
1175 if (!@mkdir
(VAR_LINKS
. $l, 0755, true)) {
1176 return "Error: cannot create folder in LINKS";
1178 if (!rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
1179 return "Error: cannot rename file in LINKS";
1182 /* Clean async upload. */
1183 jirafeau_async_delete($ref);
1184 return $hash_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
1187 function jirafeau_crypt_create_iv($base, $size)
1190 while (strlen($iv) < $size) {
1193 $iv = substr($iv, 0, $size);
1198 * Crypt file and returns decrypt key.
1199 * @param $fp_src file path to the file to crypt.
1200 * @param $fp_dst file path to the file to write crypted file (could be the same).
1201 * @return decrypt key composed of the key and the iv separated by a point ('.')
1203 function jirafeau_encrypt_file($fp_src, $fp_dst)
1205 $fs = filesize($fp_src);
1206 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
1210 /* Prepare module. */
1211 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1213 $crypt_key = jirafeau_gen_random(10);
1214 $hash_key = md5($crypt_key);
1215 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1217 mcrypt_generic_init($m, $hash_key, $iv);
1219 $r = fopen($fp_src, 'r');
1220 $w = fopen($fp_dst, 'c');
1222 $enc = mcrypt_generic($m, fread($r, 1024));
1223 if (fwrite($w, $enc) === false) {
1230 mcrypt_generic_deinit($m);
1231 mcrypt_module_close($m);
1237 * @param $fp_src file path to the file to decrypt.
1238 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1239 * @param $k string composed of the key and the iv separated by a point ('.')
1240 * @return key used to decrypt. a string of length 0 is returned if failed.
1242 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1244 $fs = filesize($fp_src);
1245 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1250 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1251 /* Extract key and iv. */
1253 $hash_key = md5($crypt_key);
1254 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1256 $r = fopen($fp_src, 'r');
1257 $w = fopen($fp_dst, 'c');
1259 $dec = mdecrypt_generic($m, fread($r, 1024));
1260 if (fwrite($w, $dec) === false) {
1267 mcrypt_generic_deinit($m);
1268 mcrypt_module_close($m);
1273 * Check if Jirafeau is password protected for visitors.
1274 * @return true if Jirafeau is password protected, false otherwise.
1276 function jirafeau_has_upload_password($cfg)
1278 return count($cfg['upload_password']) > 0;
1282 * Challenge password for a visitor.
1283 * @param $password password to be challenged
1284 * @return true if password is valid, false otherwise.
1286 function jirafeau_challenge_upload_password($cfg, $password)
1288 if (!jirafeau_has_upload_password($cfg)) {
1291 foreach ($cfg['upload_password'] as $p) {
1292 if ($password == $p) {
1300 * Test if the given IP is whitelisted by the given list.
1302 * @param $allowedIpList array of allowed IPs
1303 * @param $challengedIp IP to be challenged
1304 * @return true if IP is authorized, false otherwise.
1306 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1308 foreach ($allowedIpList as $i) {
1309 if ($i == $challengedIp) {
1312 // CIDR test for IPv4 only.
1313 if (strpos($i, '/') !== false) {
1314 list($subnet, $mask) = explode('/', $i);
1315 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1324 * Check if Jirafeau has a restriction on the IP address for uploading.
1325 * @return true if uploading is IP restricted, false otherwise.
1327 function jirafeau_upload_has_ip_restriction($cfg)
1329 return count($cfg['upload_ip']) > 0;
1333 * Test if visitor's IP is authorized to upload at all.
1335 * @param $cfg configuration
1336 * @param $challengedIp IP to be challenged
1337 * @return true if IP is authorized, false otherwise.
1339 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1341 // If no IP address have been listed, allow upload from any IP
1342 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1345 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1349 * Test if visitor's IP is authorized to upload without a password.
1351 * @param $cfg configuration
1352 * @param $challengedIp IP to be challenged
1353 * @return true if IP is authorized, false otherwise.
1355 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1357 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1361 * Test if visitor's IP is authorized or password is supplied and authorized
1362 * @param $ip IP to be challenged
1363 * @param $password password to be challenged
1364 * @return true if access is valid, false otherwise.
1366 function jirafeau_challenge_upload($cfg, $ip, $password)
1368 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1369 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1370 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1373 /** Tell if we have some HTTP headers generated by a proxy */
1374 function has_http_forwarded()
1377 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1378 !empty($_SERVER['http_X_forwarded_for']);
1382 * Generate IP list from HTTP headers generated by a proxy
1383 * @return array of IP strings
1385 function get_ip_list_http_forwarded()
1388 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1389 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1393 foreach ($l as $ip) {
1394 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1397 if (!empty($_SERVER['http_X_forwarded_for'])) {
1398 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1399 foreach ($l as $ip) {
1400 // Separate IP from port
1401 $ipa = explode(':', $ip);
1402 if ($ipa === false) {
1406 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1413 * Get the ip address of the client from REMOTE_ADDR
1414 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1415 * @returns the client ip address
1417 function get_ip_address($cfg)
1419 $remote = $_SERVER['REMOTE_ADDR'];
1420 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1424 $ip_list = get_ip_list_http_forwarded();
1425 if (count($ip_list) == 0) {
1429 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1430 if ($remote != $proxy_ip) {
1433 // Take the last IP (the one which has been set by the defined proxy).
1434 return end($ip_list);
1440 * Convert hexadecimal string to base64
1442 function hex_to_base64($hex)
1445 foreach (str_split($hex, 2) as $pair) {
1446 $b .= chr(hexdec($pair));
1448 return base64_encode($b);
1452 * Replace markers in templates.
1454 * Available markers have the scheme "###MARKERNAME###".
1456 * @param $content string Template text with markers
1457 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1458 * @return Template with replaced markers
1460 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1463 '/###ORGANISATION###/',
1464 '/###CONTACTPERSON###/',
1467 $replacements = array(
1468 $GLOBALS['cfg']['organisation'],
1469 $GLOBALS['cfg']['contactperson'],
1470 $GLOBALS['cfg']['web_root']
1472 $content = preg_replace($patterns, $replacements, $content);
1474 if (true === $htmllinebreaks) {
1475 $content = nl2br($content);
1481 function jirafeau_escape($string)
1483 return htmlspecialchars($string, ENT_QUOTES
);
1486 function jirafeau_admin_session_start()
1488 $_SESSION['admin_auth'] = true;
1489 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1492 function jirafeau_session_end()
1494 $_SESSION = array();
1498 function jirafeau_admin_session_logged()
1500 return isset($_SESSION['admin_auth']) &&
1501 isset($_SESSION['admin_csrf']) &&
1502 isset($_POST['admin_csrf']) &&
1503 $_SESSION['admin_auth'] === true &&
1504 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1507 function jirafeau_admin_csrf_field()
1509 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1512 function jirafeau_user_session_start()
1514 $_SESSION['user_auth'] = true;
1517 function jirafeau_user_session_logged()
1519 return isset($_SESSION['user_auth']) &&
1520 $_SESSION['user_auth'] === true;
1523 function jirafeau_dir_size($dir)
1526 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT
) as $entry) {
1527 $size +
= is_file($entry) ?
filesize($entry) : jirafeau_dir_size($entry);
1532 function jirafeau_export_cfg($cfg)
1534 $content = '<?php' . NL
;
1535 $content .= '/* This file was generated by the install process. ' .
1536 'You can edit it. Please see config.original.php to understand the ' .
1537 'configuration items. */' . NL
;
1538 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1540 $fileWrite = file_put_contents(JIRAFEAU_CFG
, $content);
1542 if (false === $fileWrite) {
1543 jirafeau_fatal_error(t('Can not write local configuration file'));
1547 function jirafeau_mkdir($path)
1549 return !(!file_exists($path) && !@mkdir
($path, 0755));
1553 * Returns true whether the path is writable or we manage to make it
1554 * so, which essentially is the same thing.
1555 * @param $path is the file or directory to be tested.
1556 * @return true if $path is writable.
1558 function jirafeau_is_writable($path)
1560 /* "@" gets rid of error messages. */
1561 return is_writable($path) || @chmod
($path, 0777);
1564 function jirafeau_check_var_dir($path)
1566 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1567 $mkdir_str2 = t('MANUAL_CREATE');
1568 $write_str1 = t('DIR_NOT_W') . ':';
1569 $write_str2 = t('You should give the write permission to the web server on ' .
1571 $solution_str = t('HERE_SOLUTION') . ':';
1573 if (!jirafeau_mkdir($path) ||
!jirafeau_is_writable($path)) {
1574 return array('has_error' => true,
1575 'why' => $mkdir_str1 . '<br /><code>' .
1576 $path . '</code><br />' . $solution_str .
1577 '<br />' . $mkdir_str2);
1580 foreach (array('files', 'links', 'async') as $subdir) {
1581 $subpath = $path.$subdir;
1583 if (!jirafeau_mkdir($subpath) ||
!jirafeau_is_writable($subpath)) {
1584 return array('has_error' => true,
1585 'why' => $mkdir_str1 . '<br /><code>' .
1586 $subpath . '</code><br />' . $solution_str .
1587 '<br />' . $mkdir_str2);
1591 return array('has_error' => false, 'why' => '');
1594 function jirafeau_add_ending_slash($path)
1596 return $path . ((substr($path, -1) == '/') ?
'' : '/');
1599 function jirafeau_default_web_root()
1601 return $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1604 function jirafeau_has_ldap_auth($cfg)
1606 return $cfg['upload_ldap_auth'] === true;
1609 function jirafeau_challenge_ldap_auth($cfg, $user, $password)
1611 if (!jirafeau_has_ldap_auth($cfg)) {
1612 return "upload_ldap_auth not set";
1614 if (strlen($cfg['upload_ldap_host']) == 0) {
1615 return "upload_ldap_host not set";
1617 if (strlen($cfg['upload_ldap_base_dn']) == 0) {
1618 return "upload_ldap_base_dn not set";
1620 $host = $cfg['upload_ldap_host'];
1621 $base_dn = $cfg['upload_ldap_base_dn'];
1622 $con = ldap_connect("ldap://$host");
1623 $ldap_user = "cn=$user,$base_dn";
1625 return "cannot initiate connection to ldap server";
1627 ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION
, 3);
1628 ldap_set_option($con, LDAP_OPT_REFERRALS
, 0);
1629 $bind = ldap_bind_ext($con, $ldap_user, $password, [['oid' => LDAP_CONTROL_PASSWORDPOLICYREQUEST
]]);
1632 return "cannot bind to ldap server";
1634 $parsing = ldap_parse_result($con, $bind, $errcode, $matcheddn, $errmsg, $referrals, $ctrls);
1637 return "cannot parlse ldap results";
1639 if ($errcode == 49) {
1641 return "bad password";
1643 if ($errcode != 0) {
1645 return "ldap auth error: $errmsg ($errcode)";