3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
6 * Copyright (C) 2024 Jirafeau project <https://gitlab.com/jirafeau> (see AUTHORS.md)
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)
146 $ts = date_create('@' . $timestamp);
147 $content = '<span class="datetime" data-datetime="' . date_format($ts, 'Y-m-d H:i') . '">'
148 . date_format($ts, 'Y-m-d H:i') . ' (GMT)</span>';
153 function jirafeau_fatal_error($errorText, $cfg = array())
155 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
156 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
160 function jirafeau_clean_rm_link($link)
163 if (file_exists(VAR_LINKS
. $p . $link)) {
164 unlink(VAR_LINKS
. $p . $link);
166 if (file_exists(VAR_LINKS
. $p . $link . '_download')) {
167 unlink(VAR_LINKS
. $p . $link . '_download');
169 $parse = VAR_LINKS
. $p;
171 while (file_exists($parse)
172 && ($scan = scandir($parse))
173 && count($scan) == 2 // '.' and '..' folders => empty.
174 && basename($parse) != basename(VAR_LINKS
)) {
176 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
180 function jirafeau_clean_rm_file($hash)
183 $f = VAR_FILES
. $p . $hash;
184 if (file_exists($f) && is_file($f)) {
187 if (file_exists($f . '_count') && is_file($f . '_count')) {
188 unlink($f . '_count');
190 $parse = VAR_FILES
. $p;
192 while (file_exists($parse)
193 && ($scan = scandir($parse))
194 && count($scan) == 2 // '.' and '..' folders => empty.
195 && basename($parse) != basename(VAR_FILES
)) {
197 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
202 * transforms a php.ini string representing a value in an integer
203 * @param $value the value from php.ini
204 * @returns an integer for this value
206 function jirafeau_ini_to_bytes($value)
208 $modifier = substr($value, -1);
209 $bytes = substr($value, 0, -1);
210 switch (strtoupper($modifier)) {
212 return intval($value);
233 * gets the maximum upload size according to php.ini
234 * @returns the maximum upload size in bytes
236 function jirafeau_get_max_upload_size_bytes()
239 jirafeau_ini_to_bytes(ini_get('post_max_size')),
240 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
245 * gets the maximum upload size according to php.ini
246 * @returns the maximum upload size string
248 function jirafeau_get_max_upload_size()
250 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
254 * get the maximal upload size for a data chunk in async uploads
255 * @param max_upload_chunk_size_bytes
257 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
259 if ($max_upload_chunk_size_bytes == 0) {
260 $size = jirafeau_get_max_upload_size_bytes();
261 // Jirafeau must choose an arbitrary number as PHP config does not give any limit nor $max_upload_chunk_size_bytes
263 return 10000000; // 10MB
268 jirafeau_get_max_upload_size_bytes(),
269 $max_upload_chunk_size_bytes
272 return $max_upload_chunk_size_bytes;
278 * gets a string explaining the error
279 * @param $code the error code
280 * @returns a string explaining the error
282 function jirafeau_upload_errstr($code)
285 case UPLOAD_ERR_INI_SIZE
:
286 case UPLOAD_ERR_FORM_SIZE
:
287 return t('Your file exceeds the maximum authorized file size. ');
289 case UPLOAD_ERR_PARTIAL
:
290 case UPLOAD_ERR_NO_FILE
:
292 t('Your file was not uploaded correctly. You may succeed in retrying. ');
294 case UPLOAD_ERR_NO_TMP_DIR
:
295 case UPLOAD_ERR_CANT_WRITE
:
296 case UPLOAD_ERR_EXTENSION
:
297 return t('Internal error. You may not succeed in retrying. ');
299 return t('Unknown error. ');
302 /** Remove link and it's file
303 * @param $link the link's name (hash)
306 function jirafeau_delete_link($link)
308 $l = jirafeau_get_link($link);
313 jirafeau_clean_rm_link($link);
319 if (file_exists(VAR_FILES
. $p . $hash. '_count')) {
320 $content = file(VAR_FILES
. $p . $hash. '_count');
321 $counter = trim($content[0]);
326 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
327 fwrite($handle, $counter);
332 jirafeau_clean_rm_file($hash);
337 * Delete a file and it's links.
339 function jirafeau_delete_file($hash)
342 /* Get all links files. */
343 $stack = array(VAR_LINKS
);
344 while (($d = array_shift($stack)) && $d != null) {
347 foreach ($dir as $node) {
348 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
349 preg_match('/\.tmp/i', "$node")) {
353 if (is_dir($d . $node)) {
354 /* Push new found directory. */
355 $stack[] = $d . $node . '/';
356 } elseif (is_file($d . $node)) {
357 /* Read link informations. */
358 $l = jirafeau_get_link(basename($node));
362 if ($l['hash'] == $hash) {
364 jirafeau_delete_link($node);
369 jirafeau_clean_rm_file($hash);
374 /** hash file's content
375 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
376 * @param $file_path file to hash
377 * @returns hash string
379 function jirafeau_hash_file($method, $file_path)
383 return jirafeau_md5_outside($file_path);
385 return md5_file($file_path);
387 return jirafeau_gen_random(32);
389 return md5_file($file_path);
392 /** hash part of file: start, end and size.
393 * This is a partial file hash, faster but weaker.
394 * @param $file_path file to hash
395 * @returns hash string
397 function jirafeau_md5_outside($file_path)
400 $handle = fopen($file_path, 'r');
401 if ($handle === false) {
404 $size = filesize($file_path);
405 if ($size === false) {
408 $first = fread($handle, 64);
409 if ($first === false) {
412 if (fseek($handle, $size < 64 ?
0 : $size - 64) == -1) {
415 $last = fread($handle, 64);
416 if ($last === false) {
419 $out = md5($first . $last . $size);
426 * handles an uploaded file
427 * @param $file the file struct given by $_FILE[]
428 * @param $one_time_download is the file a one time download ?
429 * @param $key if not empty, protect the file with this key
430 * @param $time the time of validity of the file
431 * @param $ip uploader's ip
432 * @param $crypt boolean asking to crypt or not
433 * @param $link_name_length size of the link name
434 * @returns an array containing some information
435 * 'error' => information on possible errors
436 * 'link' => the link name of the uploaded file
437 * 'delete_link' => the link code to delete file
439 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
441 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
444 array('has_error' => true,
445 'why' => jirafeau_upload_errstr($file['error'])),
447 'delete_link' => ''));
449 jirafeau_add_file($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method);
454 * @param bool $crypt_module_enabled
455 * @param string $file_path
456 * @return array [bool, string]
458 function jirafeau_handle_add_file_encryption($crypt_module_enabled, $file_path)
460 /* Crypt file if option is enabled. */
463 if ($crypt_module_enabled == true && !(extension_loaded('sodium') == true)) {
464 error_log("PHP extension sodium not loaded, won't encrypt in Jirafeau");
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) {
475 return [$crypted, $crypt_key];
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
493 function jirafeau_add_file($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method, $is_upload = true)
495 // TODO needs to be adapted
496 $move_operation = $is_upload ?
'move_uploaded_file' : 'symlink';
498 /* array representing no error */
499 $noerr = array('has_error' => false, 'why' => '');
503 list($crypted, $crypt_key) = jirafeau_handle_add_file_encryption($crypt, $file['tmp_name']);
505 /* file information */
506 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
507 $name = str_replace(NL
, '', trim($file['name']));
508 $mime_type = $file['type'];
509 $size = $file['size'];
511 /* does file already exist ? */
514 if (file_exists(VAR_FILES
. $p . $hash)) {
515 $rc = unlink($file['tmp_name']);
517 (file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true)) &&
518 $move_operation($file['tmp_name'], VAR_FILES
. $p . $hash)) {
524 array('has_error' => true,
525 'why' => t('INTERNAL_ERROR_DEL')),
527 'delete_link' => ''));
530 /* Increment or create count file. */
532 if (file_exists(VAR_FILES
. $p . $hash . '_count')) {
533 $content = file(VAR_FILES
. $p . $hash. '_count');
534 $counter = trim($content[0]);
537 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
538 fwrite($handle, $counter);
541 /* Create delete code. */
542 $delete_link_code = jirafeau_gen_random(5);
544 /* hash password or empty. */
547 $password = md5($key);
550 /* create link file */
551 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
552 $handle = fopen($link_tmp_name, 'w');
555 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
556 NL
. $hash. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
557 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O')
560 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
561 $l = s2p("$hash_link");
562 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
563 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
564 if (file_exists($link_tmp_name)) {
565 unlink($link_tmp_name);
570 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
571 fwrite($handle, $counter);
574 jirafeau_clean_rm_file($hash_link);
578 array('has_error' => true,
579 'why' => t('Internal error during file creation. ')),
581 'delete_link' => '');
583 return array( 'error' => $noerr,
584 'link' => $hash_link,
585 'delete_link' => $delete_link_code,
586 'crypt_key' => $crypt_key);
589 function jirafeau_admin_list_table($name, $file_hash, $link_hash, $visitor_function = null)
591 echo '<fieldset><legend>';
593 echo t('FILENAME') . ": " . jirafeau_escape($name);
595 if (!empty($file_hash)) {
596 echo t('FILE') . ": " . jirafeau_escape($file_hash);
598 if (!empty($link_hash)) {
599 echo t('LINK') . ": " . jirafeau_escape($link_hash);
601 if (empty($name) && empty($file_hash) && empty($link_hash)) {
608 echo '<th>' . t('ACTION') . '</th>';
610 if ($visitor_function != null) {
611 $visitor_function($name, $file_hash, $link_hash);
613 echo '</table></fieldset>';
617 * Tells if a mime-type is viewable in a browser
618 * @param $mime the mime type
619 * @returns a boolean telling if a mime type is viewable
621 function jirafeau_is_viewable($mime)
624 $viewable = array('image', 'video', 'audio');
625 $decomposed = explode('/', $mime);
626 if (in_array($decomposed[0], $viewable) && stripos($mime, 'image/svg+xml') === false) {
629 $viewable = array('text/plain');
630 if (in_array($mime, $viewable)) {
637 // Error handling functions.
638 //! Global array that contains all registered errors.
639 $error_list = array();
642 * Adds an error to the list of errors.
643 * @param $title the error's title
644 * @param $description is a human-friendly description of the problem.
646 function add_error($title, $description)
649 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
653 * Informs whether any error has been registered yet.
654 * @return true if there are errors.
659 return !empty($error_list);
663 * Displays all the errors.
665 function show_errors()
669 echo '<div class="error">';
670 foreach ($error_list as $error) {
677 function check_errors($cfg)
679 if (!($cfg['installation_done'] === true)) {
680 if (file_exists(JIRAFEAU_ROOT
. 'install.php')) {
681 header('Location: install.php');
684 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
688 if (!is_writable(VAR_FILES
)) {
689 add_error(t('FILE_DIR_W'), VAR_FILES
);
692 if (!is_writable(VAR_LINKS
)) {
693 add_error(t('LINK_DIR_W'), VAR_LINKS
);
696 if (!is_writable(VAR_ASYNC
)) {
697 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
700 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
701 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
704 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
705 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
710 * Read link information
711 * @return array containing information.
713 function jirafeau_get_link($hash)
716 $link = VAR_LINKS
. s2p("$hash") . $hash;
718 if (!file_exists($link)) {
723 $out['file_name'] = trim($c[0]);
724 $out['mime_type'] = trim($c[1]);
725 $out['file_size'] = trim($c[2]);
726 $out['key'] = trim($c[3], NL
);
727 $out['time'] = trim($c[4]);
728 $out['hash'] = trim($c[5]);
729 $out['onetime'] = trim($c[6]);
730 $out['upload_date'] = trim($c[7]);
731 $out['ip'] = trim($c[8]);
732 $out['link_code'] = trim($c[9]);
733 $out['crypted'] = trim($c[10]) == 'C2';
734 $out['crypted_legacy'] = trim($c[10]) == 'C';
740 * List files in admin interface.
742 function jirafeau_admin_list($name, $file_hash, $link_hash)
744 $function = function ($name, $file_hash, $link_hash) {
745 /* Get all links files. */
746 $stack = array(VAR_LINKS
);
747 while (($d = array_shift($stack)) && $d != null) {
749 foreach ($dir as $node) {
750 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
751 preg_match('/\.tmp/i', "$node")) {
754 if (is_dir($d . $node)) {
755 /* Push new found directory. */
756 $stack[] = $d . $node . '/';
757 } elseif (is_file($d . $node)) {
758 /* Read link information. */
759 $l = jirafeau_get_link($node);
765 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
768 if (!empty($file_hash) && $file_hash != $l['hash']) {
771 if (!empty($link_hash) && $link_hash != $node) {
774 /* Print link information. */
778 if (!$l['crypted'] && !$l['crypted_legacy']) {
779 echo'<a href="f.php?h='. jirafeau_escape($node) .'" title="' .
780 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a>';
782 echo jirafeau_escape($l['file_name']);
785 echo '</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' ?
t('YES') : t('NO')) . '<br/>';
791 echo t('ENCRYPTED') . ': ' . (($l['crypted'] ||
$l['crypted_legacy']) ?
t('YES') : t('NO')) . '<br/>';
792 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
793 if (strlen($l['ip']) > 0) {
794 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
798 if (!$l['crypted'] && !$l['crypted_legacy']) {
799 echo '<form method="post">' .
800 '<input type = "hidden" name = "action" value = "download"/>' .
801 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
802 jirafeau_admin_csrf_field() .
803 '<input type = "submit" value = "' . t('DL') . '" />' .
807 echo '<form method="post">' .
808 '<input type = "hidden" name = "action" value = "delete_link"/>' .
809 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
810 jirafeau_admin_csrf_field() .
811 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
813 '<form method="post">' .
814 '<input type = "hidden" name = "action" value = "delete_file"/>' .
815 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
816 jirafeau_admin_csrf_field() .
817 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
826 jirafeau_admin_list_table($name, $file_hash, $link_hash, $function);
830 * Clean expired files.
831 * @return number of cleaned files.
833 function jirafeau_admin_clean()
836 /* Get all links files. */
837 $stack = array(VAR_LINKS
);
838 while (($d = array_shift($stack)) && $d != null) {
841 foreach ($dir as $node) {
842 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
843 preg_match('/\.tmp/i', "$node")) {
847 if (is_dir($d . $node)) {
848 /* Push new found directory. */
849 $stack[] = $d . $node . '/';
850 } elseif (is_file($d . $node)) {
851 /* Read link information. */
852 $l = jirafeau_get_link(basename($node));
856 $p = s2p($l['hash']);
857 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
858 !file_exists(VAR_FILES
. $p . $l['hash']) ||
// invalid
859 !file_exists(VAR_FILES
. $p . $l['hash'] . '_count')) { // invalid
860 jirafeau_delete_link($node);
871 * Clean old async transfers.
872 * @return number of cleaned files.
874 function jirafeau_admin_clean_async()
877 /* Get all links files. */
878 $stack = array(VAR_ASYNC
);
879 while (($d = array_shift($stack)) && $d != null) {
882 foreach ($dir as $node) {
883 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
884 preg_match('/\.tmp/i', "$node")) {
888 if (is_dir($d . $node)) {
889 /* Push new found directory. */
890 $stack[] = $d . $node . '/';
891 } elseif (is_file($d . $node)) {
892 /* Read async information. */
893 $a = jirafeau_get_async_ref(basename($node));
897 /* Delete transfers older than 1 hour. */
898 if (time() - $a['last_edited'] > 3600) {
899 jirafeau_async_delete(basename($node));
909 * Better strval function for debug purposes
911 function jirafeau_strval($value)
913 if (gettype($value) == "boolean") {
914 return $value ?
'true' : 'false';
916 return strval($value);
920 * Show file/folder permissions
922 function jirafeau_fileperms($path)
924 $out = substr(sprintf("%o", @fileperms
($path)), -4) . ", ";
925 $out .= "read " . (is_readable($path) ?
"OK" : "KO") . ", ";
926 $out .= "write " . (is_writable($path) ?
"OK" : "KO");
931 * Show some useful informations for bug reporting.
933 function jirafeau_admin_bug_report($cfg)
935 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
936 $out .= "If you have a problem related to Jirafeau, please <a href='" . JIRAFEAU_WEBSITE
. "/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>";
938 $out .= "# Jirafeau<br/>";
939 $out .= "- version: " . JIRAFEAU_VERSION
. "<br/>";
940 $jirafeau_options = [
943 'litespeed_workaround',
948 'maximal_upload_size',
950 'max_upload_chunk_size_bytes'
952 foreach ($jirafeau_options as &$o) {
954 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
958 $out .= "# PHP options<br/>";
959 $out .= "- php version: " . phpversion() . "<br/>";
960 $out .= "- sodium version: " . phpversion('sodium') . "<br/>";
961 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
964 'upload_max_filesize',
966 'max_execution_time',
969 foreach ($php_options as &$o) {
971 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
973 $out .= "- can set_time_limit: " . (set_time_limit(0) ?
"yes" : "no") . "<br/>";
976 $out .= "# File permissions<br/>";
977 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
978 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES
) . "<br/>";
979 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS
) . "<br/>";
980 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC
) . "<br/>";
983 $out .= "# Server details<br/>";
984 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
987 $out .= "# OS details<br/>";
988 $out .= "- OS: " . php_uname() . "<br/>";
991 $out .= "# Browser details<br/>";
992 $out .= "<script type='text/javascript' lang='Javascript'>
993 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
994 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
995 document.write('- user agent: ' + navigator.userAgent + '<br/>');
1000 $out .= "# Memory<br/>";
1001 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
1003 $out .= "</code></fieldset>";
1008 * Read async transfer information
1009 * @return array containing information.
1011 function jirafeau_get_async_ref($ref)
1014 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
1016 if (!file_exists($refinfos)) {
1020 $c = file($refinfos);
1021 $out['file_name'] = trim($c[0]);
1022 $out['mime_type'] = trim($c[1]);
1023 $out['key'] = trim($c[2], NL
);
1024 $out['time'] = trim($c[3]);
1025 $out['onetime'] = trim($c[4]);
1026 $out['ip'] = trim($c[5]);
1027 $out['last_edited'] = trim($c[6]);
1028 $out['next_code'] = trim($c[7]);
1033 * Delete async transfer information
1035 function jirafeau_async_delete($ref)
1038 if (file_exists(VAR_ASYNC
. $p . $ref)) {
1039 unlink(VAR_ASYNC
. $p . $ref);
1041 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
1042 unlink(VAR_ASYNC
. $p . $ref . '_data');
1044 $parse = VAR_ASYNC
. $p;
1046 while (file_exists($parse)
1047 && ($scan = scandir($parse))
1048 && count($scan) == 2 // '.' and '..' folders => empty.
1049 && basename($parse) != basename(VAR_ASYNC
)) {
1051 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1056 * Init a new asynchronous upload.
1057 * @param $filename Name of the file to send
1058 * @param $one_time One time upload parameter
1059 * @param $key eventual password (or blank)
1060 * @param $time time limit
1061 * @param $ip ip address of the client
1062 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1064 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1066 /* Create temporary folder. */
1069 $code = jirafeau_gen_random(4);
1071 $ref = jirafeau_gen_random(32);
1072 $p = VAR_ASYNC
. s2p($ref);
1073 } while (file_exists($p));
1074 @mkdir
($p, 0755, true);
1075 if (!file_exists($p)) {
1076 return 'Error: cannot create async folder.';
1079 /* touch empty data file */
1080 $w_path = $p . $ref . '_data';
1083 /* md5 password or empty */
1086 $password = md5($key);
1089 /* Store information. */
1091 $handle = fopen($p, 'w');
1094 str_replace(NL
, '', trim($filename)) . NL
.
1095 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
1096 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
1097 time() . NL
. $code . NL
1101 return $ref . NL
. $code ;
1105 * Append a piece of file on the asynchronous upload.
1106 * @param $ref asynchronous upload reference
1107 * @param $file piece of data
1108 * @param $code client code for this operation
1109 * @param $max_file_size maximum allowed file size
1110 * @return a string containing a next code to use or a string starting with 'Error'
1112 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1114 /* Get async infos. */
1115 $a = jirafeau_get_async_ref($ref);
1117 /* Check some errors. */
1118 if (count($a) == 0) {
1119 return "Error: cannot find transfer";
1121 if ($a['next_code'] != "$code") {
1122 return "Error: bad transfer code";
1124 if ($data['error'] != UPLOAD_ERR_OK
) {
1125 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1126 $data_details = print_r($data, true);
1127 return "Error: upload error: {$data_details}";
1129 if (empty($data['tmp_name'])) {
1130 return "Error: missing tmp_name";
1132 if (!is_uploaded_file($data['tmp_name'])) {
1133 return "Error: tmp_name may not be uploaded";
1139 $r_path = $data['tmp_name'];
1140 $w_path = VAR_ASYNC
. $p . $ref . '_data';
1142 /* Check that file size is not above upload limit. */
1143 if ($max_file_size > 0 &&
1144 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
1145 jirafeau_async_delete($ref);
1146 return "Error: file size is above upload limit";
1149 /* Concatenate data. */
1150 $r = fopen($r_path, 'r');
1151 $w = fopen($w_path, 'a');
1153 if (fwrite($w, fread($r, 1024)) === false) {
1156 jirafeau_async_delete($ref);
1157 return "Error: cannot write file";
1164 /* Update async file. */
1165 $code = jirafeau_gen_random(4);
1166 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
1169 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
1170 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
1171 time() . NL
. $code . NL
1178 * Finalize an asynchronous upload.
1179 * @param $ref asynchronous upload reference
1180 * @param $code client code for this operation
1181 * @param $crypt boolean asking to crypt or not
1182 * @param $link_name_length link name length
1183 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1185 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1187 /* Get async infos. */
1188 $a = jirafeau_get_async_ref($ref);
1190 ||
$a['next_code'] != "$code") {
1191 return "Error: bad code for ending transfer";
1194 /* Generate link infos. */
1195 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
1196 if (!file_exists($p)) {
1197 return "Error: referenced file does not exist";
1200 /* Store filesize before encrypting the file */
1201 /* Otherwise we would send the size of the encrypted file and the data of the unencrypted file */
1202 /* This would break some browsers */
1203 $size = filesize($p);
1207 if ($crypt == true && extension_loaded('sodium') == true) {
1208 $crypt_key = jirafeau_encrypt_file($p, $p.'.crypt');
1209 if (strlen($crypt_key) > 0) {
1210 if (rename($p.'.crypt', $p) === true) {
1216 $hash = jirafeau_hash_file($file_hash_method, $p);
1218 $delete_link_code = jirafeau_gen_random(5);
1220 /* File already exist ? */
1221 if (!file_exists(VAR_FILES
. $np)) {
1222 @mkdir
(VAR_FILES
. $np, 0755, true);
1224 if (!file_exists(VAR_FILES
. $np . $hash)) {
1225 rename($p, VAR_FILES
. $np . $hash);
1228 /* Increment or create count file. */
1230 if (file_exists(VAR_FILES
. $np . $hash . '_count')) {
1231 $content = file(VAR_FILES
. $np . $hash. '_count');
1232 $counter = trim($content[0]);
1235 $handle = fopen(VAR_FILES
. $np . $hash. '_count', 'w');
1236 fwrite($handle, $counter);
1240 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
1241 $handle = fopen($link_tmp_name, 'w');
1244 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
1245 $a['key'] . NL
. $a['time'] . NL
. $hash . NL
. $a['onetime'] . NL
.
1246 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C2' : 'O')
1249 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1250 $l = s2p("$hash_link");
1251 if (!@mkdir
(VAR_LINKS
. $l, 0755, true)) {
1252 return "Error: cannot create folder in LINKS";
1254 if (!rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
1255 return "Error: cannot rename file in LINKS";
1258 /* Clean async upload. */
1259 jirafeau_async_delete($ref);
1260 return $hash_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
1263 function jirafeau_crypt_create_iv($base, $size)
1266 while (strlen($iv) < $size) {
1269 $iv = substr($iv, 0, $size);
1274 * Crypt file using Sodium and returns decrypt key.
1275 * @param $fp_src file path to the file to crypt.
1276 * @param $fp_dst file path to the file to write crypted file (must not be the same).
1277 * @return key used to encrypt the file
1279 function jirafeau_encrypt_file($fp_src, $fp_dst)
1281 $fs = filesize($fp_src);
1282 if ($fs === false ||
$fs == 0 ||
extension_loaded('sodium') == false ||
$fp_src == $fp_dst) {
1287 $crypt_key = bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
/ 2));
1289 [$crypt_state, $crypt_header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($crypt_key);
1291 $r = fopen($fp_src, 'rb');
1292 $w = fopen($fp_dst, 'wb');
1293 fwrite($w, $crypt_header);
1295 for ($i = 0; $i < $fs; $i +
= JIRAFEAU_SODIUM_CHUNKSIZE
) {
1296 $to_enc = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE
);
1297 $enc = sodium_crypto_secretstream_xchacha20poly1305_push($crypt_state, $to_enc);
1299 if (fwrite($w, $enc) === false) {
1308 sodium_memzero($crypt_state);
1314 * Decrypt file using Sodium.
1315 * @param $fp_src file path to the file to decrypt.
1316 * @param $fp_dst file path to the file to write decrypted file (must not be the same).
1317 * @param $k decryption key
1318 * @return true if decryption succeeded, false otherwise
1320 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1322 $fs = filesize($fp_src);
1323 if ($fs === false ||
$fs == 0 ||
extension_loaded('sodium') == false ||
$fp_src == $fp_dst) {
1328 $r = fopen($fp_src, 'rb');
1329 $w = fopen($fp_dst, 'wb');
1331 $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES
);
1334 $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $k);
1338 for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES
; $i < $fs; $i +
= JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES
) {
1339 $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES
);
1340 [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
1342 if (fwrite($w, $dec) === false) {
1351 sodium_memzero($crypt_state);
1357 * Decrypt file using mcrypt.
1358 * @param $fp_src file path to the file to decrypt.
1359 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1360 * @param $k string composed of the key and the iv separated by a point ('.')
1361 * @return true if decryption succeeded, false otherwise
1363 function jirafeau_decrypt_file_legacy($fp_src, $fp_dst, $k)
1365 $fs = filesize($fp_src);
1366 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1371 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1372 /* Extract key and iv. */
1374 $hash_key = md5($crypt_key);
1375 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1377 mcrypt_generic_init($m, $hash_key, $iv);
1379 $r = fopen($fp_src, 'r');
1380 $w = fopen($fp_dst, 'c');
1382 $dec = mdecrypt_generic($m, fread($r, 1024));
1383 if (fwrite($w, $dec) === false) {
1390 mcrypt_generic_deinit($m);
1391 mcrypt_module_close($m);
1396 * Check if Jirafeau is password protected for visitors.
1397 * @return true if Jirafeau is password protected, false otherwise.
1399 function jirafeau_has_upload_password($cfg)
1401 return count($cfg['upload_password']) > 0;
1405 * Challenge password for a visitor.
1406 * @param $password password to be challenged
1407 * @return true if password is valid, false otherwise.
1409 function jirafeau_challenge_upload_password($cfg, $password)
1411 if (!jirafeau_has_upload_password($cfg)) {
1414 foreach ($cfg['upload_password'] as $p) {
1415 if ($password == $p) {
1423 * Test if the given IP is whitelisted by the given list.
1425 * @param $allowedIpList array of allowed IPs
1426 * @param $challengedIp IP to be challenged
1427 * @return true if IP is authorized, false otherwise.
1429 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1431 foreach ($allowedIpList as $i) {
1432 if ($i == $challengedIp) {
1435 // CIDR test for IPv4 only.
1436 if (strpos($i, '/') !== false) {
1437 list($subnet, $mask) = explode('/', $i);
1438 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1447 * Check if Jirafeau has a restriction on the IP address for uploading.
1448 * @return true if uploading is IP restricted, false otherwise.
1450 function jirafeau_upload_has_ip_restriction($cfg)
1452 return count($cfg['upload_ip']) > 0;
1456 * Test if visitor's IP is authorized to upload at all.
1458 * @param $cfg configuration
1459 * @param $challengedIp IP to be challenged
1460 * @return true if IP is authorized, false otherwise.
1462 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1464 // If no IP address have been listed, allow upload from any IP
1465 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1468 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1472 * Test if visitor's IP is authorized to upload without a password.
1474 * @param $cfg configuration
1475 * @param $challengedIp IP to be challenged
1476 * @return true if IP is authorized, false otherwise.
1478 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1480 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1484 * Test if visitor's IP is authorized or password is supplied and authorized
1485 * @param $ip IP to be challenged
1486 * @param $password password to be challenged
1487 * @return true if access is valid, false otherwise.
1489 function jirafeau_challenge_upload($cfg, $ip, $password)
1491 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1492 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1493 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1497 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1498 * @return true if admin interface is IP restricted, false otherwise.
1500 function jirafeau_admin_has_ip_restriction($cfg)
1502 return count($cfg['admin_ip']) > 0;
1506 * Test if visitor's IP is authorized to access the admin interface.
1508 * @param $cfg configuration
1509 * @param $challengedIp IP to be challenged
1510 * @return true if IP is authorized, false otherwise.
1512 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1514 // If no IP address have been listed, allow upload from any IP
1515 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1518 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1521 /** Tell if we have some HTTP headers generated by a proxy */
1522 function has_http_forwarded()
1525 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1526 !empty($_SERVER['http_X_forwarded_for']);
1530 * Generate IP list from HTTP headers generated by a proxy
1531 * @return array of IP strings
1533 function get_ip_list_http_forwarded()
1536 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1537 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1541 foreach ($l as $ip) {
1542 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1545 if (!empty($_SERVER['http_X_forwarded_for'])) {
1546 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1547 foreach ($l as $ip) {
1548 // Separate IP from port
1549 $ipa = explode(':', $ip);
1550 if ($ipa === false) {
1554 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1561 * Get the ip address of the client from REMOTE_ADDR
1562 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1563 * @returns the client ip address
1565 function get_ip_address($cfg)
1567 $remote = $_SERVER['REMOTE_ADDR'];
1568 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1572 $ip_list = get_ip_list_http_forwarded();
1573 if (count($ip_list) == 0) {
1577 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1578 if ($remote != $proxy_ip) {
1581 // Take the last IP (the one which has been set by the defined proxy).
1582 return end($ip_list);
1588 * Convert hexadecimal string to base64
1590 function hex_to_base64($hex)
1593 foreach (str_split($hex, 2) as $pair) {
1594 $b .= chr(hexdec($pair));
1596 return base64_encode($b);
1600 * Replace markers in templates.
1602 * Available markers have the scheme "###MARKERNAME###".
1604 * @param $content string Template text with markers
1605 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1606 * @return Template with replaced markers
1608 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1611 '/###ORGANISATION###/',
1612 '/###CONTACTPERSON###/',
1615 $replacements = array(
1616 $GLOBALS['cfg']['organisation'],
1617 $GLOBALS['cfg']['contactperson'],
1618 $GLOBALS['cfg']['web_root']
1620 $content = preg_replace($patterns, $replacements, $content);
1622 if (true === $htmllinebreaks) {
1623 $content = nl2br($content);
1629 function jirafeau_escape($string)
1631 return htmlspecialchars($string, ENT_QUOTES
);
1634 function jirafeau_admin_session_start()
1636 $_SESSION['admin_auth'] = true;
1637 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1640 function jirafeau_session_end()
1642 $_SESSION = array();
1646 function jirafeau_admin_session_logged()
1648 return isset($_SESSION['admin_auth']) &&
1649 isset($_SESSION['admin_csrf']) &&
1650 isset($_POST['admin_csrf']) &&
1651 $_SESSION['admin_auth'] === true &&
1652 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1655 function jirafeau_admin_csrf_field()
1657 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1660 function jirafeau_user_session_start()
1662 $_SESSION['user_auth'] = true;
1665 function jirafeau_user_session_logged()
1667 return isset($_SESSION['user_auth']) &&
1668 $_SESSION['user_auth'] === true;
1671 function jirafeau_dir_size($dir)
1674 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT
) as $entry) {
1675 $size +
= is_file($entry) ?
filesize($entry) : jirafeau_dir_size($entry);
1680 function jirafeau_export_cfg($cfg)
1682 $content = '<?php' . NL
;
1683 $content .= '/* This file was generated by the install process. ' .
1684 'You can edit it. Please see config.original.php to understand the ' .
1685 'configuration items. */' . NL
;
1686 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1688 $fileWrite = file_put_contents(JIRAFEAU_CFG
, $content);
1690 if (false === $fileWrite) {
1691 jirafeau_fatal_error(t('Can not write local configuration file'));
1695 function jirafeau_mkdir($path)
1697 return !(!file_exists($path) && !@mkdir
($path, 0755));
1701 * Returns true whether the path is writable or we manage to make it
1702 * so, which essentially is the same thing.
1703 * @param $path is the file or directory to be tested.
1704 * @return true if $path is writable.
1706 function jirafeau_is_writable($path)
1708 /* "@" gets rid of error messages. */
1709 return is_writable($path) || @chmod
($path, 0777);
1712 function jirafeau_check_var_dir($path)
1714 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1715 $mkdir_str2 = t('MANUAL_CREATE');
1716 $write_str1 = t('DIR_NOT_W') . ':';
1717 $write_str2 = t('You should give the write permission to the web server on ' .
1719 $solution_str = t('HERE_SOLUTION') . ':';
1721 if (!jirafeau_mkdir($path) ||
!jirafeau_is_writable($path)) {
1722 return array('has_error' => true,
1723 'why' => $mkdir_str1 . '<br /><code>' .
1724 $path . '</code><br />' . $solution_str .
1725 '<br />' . $mkdir_str2);
1728 foreach (array('files', 'links', 'async') as $subdir) {
1729 $subpath = $path.$subdir;
1731 if (!jirafeau_mkdir($subpath) ||
!jirafeau_is_writable($subpath)) {
1732 return array('has_error' => true,
1733 'why' => $mkdir_str1 . '<br /><code>' .
1734 $subpath . '</code><br />' . $solution_str .
1735 '<br />' . $mkdir_str2);
1739 return array('has_error' => false, 'why' => '');
1742 function jirafeau_add_ending_slash($path)
1744 return $path . ((substr($path, -1) == '/') ?
'' : '/');
1747 function jirafeau_default_web_root()
1749 $url_scheme = (isset($_SERVER['HTTPS'])) ?
'https://' : 'http://';
1750 return $url_scheme . $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1753 function jirafeau_get_download_stats($hash)
1755 $filename = VAR_LINKS
. s2p("$hash") . $hash . '_download';
1757 if (!file_exists($filename)) {
1758 return array('count' => 0);
1761 $c = file($filename);
1762 $data['count'] = trim($c[0]);
1763 $data['date'] = trim($c[1]);
1764 $data['ip'] = trim($c[2]);
1769 function jirafeau_write_download_stats($hash, $ip)
1771 $data = jirafeau_get_download_stats($hash);
1772 $count = $data['count'];
1775 $filename = VAR_LINKS
. s2p("$hash") . $hash . '_download';
1777 $handle = fopen($filename, 'w');
1778 fwrite($handle, $count . NL
. time() . NL
. $ip);
1782 function jirafeau_create_upload_finished_box($preview = true)
1786 <div id
="upload_finished">
1787 <p
><?php
echo t('FILE_UP') ?
></p
>
1789 <div id
="upload_finished_download_page">
1791 <a id
="upload_link" href
=""><?php
echo t('DL_PAGE') ?
></a
>
1792 <a id
="upload_link_email" href
=""><img id
="upload_image_email"/></a
>
1794 <code id
=upload_link_text
></code
>
1795 <button id
="upload_link_button">📋</button>
1800 if ($preview == true) { ?
>
1801 <div id
="upload_finished_preview">
1803 <a id
="preview_link" href
=""><?php
echo t('VIEW_LINK') ?
></a
>
1805 <code id
=preview_link_text
></code
>
1806 <button id
="preview_link_button">📋</button>
1813 <div id
="upload_direct_download">
1815 <a id
="direct_link" href
=""><?php
echo t('DIRECT_DL') ?
></a
>
1817 <code id
=direct_link_text
></code
>
1818 <button id
="direct_link_button">📋</button>
1822 <div id
="upload_delete">
1824 <a id
="delete_link" href
=""><?php
echo t('DELETE_LINK') ?
></a
>
1826 <code id
=delete_link_text
></code
>
1827 <button id
="delete_link_button">📋</button>
1831 <div id
="upload_validity">
1832 <p
><?php
echo t('VALID_UNTIL'); ?
>:</p
>
1839 function jirafeau_get_expiration_time_options()
1843 'value' => 'minute',
1859 'value' => 'fortnight',
1867 'value' => 'quarter',
1883 * creates the time selection field
1887 function jirafeau_create_selection_array($cfg)
1889 echo '<select name="time" id="select_time">';
1891 $expirationTimeOptions = jirafeau_get_expiration_time_options();
1893 foreach ($expirationTimeOptions as $expirationTimeOption) {
1894 $selected = ($expirationTimeOption['value'] === $cfg['availability_default']) ?
'selected="selected"' : '';
1895 if (true === $cfg['availabilities'][$expirationTimeOption['value']]) {
1896 echo '<option value="' . $expirationTimeOption['value'] . '" ' .
1897 $selected . '>' . t($expirationTimeOption['label']) . '</option>';
1904 function jirafeau_datestr_to_int($time_str)
1907 switch ($time_str) {
1909 $time +
= JIRAFEAU_MINUTE
;
1912 $time +
= JIRAFEAU_HOUR
;
1915 $time +
= JIRAFEAU_DAY
;
1918 $time +
= JIRAFEAU_WEEK
;
1921 $time +
= JIRAFEAU_FORTNIGHT
;
1924 $time +
= JIRAFEAU_MONTH
;
1927 $time +
= JIRAFEAU_QUARTER
;
1930 $time +
= JIRAFEAU_YEAR
;
1933 $time = JIRAFEAU_INFINITY
;
1943 * links or copy a local file
1944 * TODO: boolean in config for linking
1945 * @param string $filepath
1946 * @param $one_time_download is the file a one time download?
1947 * @param $key if not empty, protect the file with this key
1948 * @param $time the time of validity of the file
1949 * @param $ip uploader's ip
1950 * @param $crypt boolean asking to crypt or not
1951 * @param $link_name_length size of the link name
1952 * @returns an array containing some information
1953 * 'error' => information on possible errors
1954 * 'link' => the link name of the uploaded file
1955 * 'delete_link' => the link code to delete file
1957 function jirafeau_copy_local_file($local_file_path, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
1959 if (!file_exists($local_file_path)) {
1962 array('has_error' => true,
1963 'why' => t('INTERNAL_ERROR_FILE_NOT_EXIST')),
1965 'delete_link' => ''));
1968 // sanity check if file can be opened
1969 $file = fopen($local_file_path, 'r')
1971 // close file pointer - it's not needed here
1973 $time_in_int = jirafeau_datestr_to_int($time);
1974 return jirafeau_add_file(
1975 jirafeau_create_file_array($local_file_path),
1988 array('has_error' => true,
1989 'why' => t('INTERNAL_ERROR_FP_OPEN_LOCAL')),
1991 'delete_link' => ''));
1996 function jirafeau_create_file_array($file_path)
1999 'type' => mime_content_type($file_path),
2000 'tmp_name' => $file_path,
2001 'name' => basename($file_path),
2002 'size' => filesize($file_path),