]>
git.p6c8.net - jirafeau.git/blob - lib/functions.php
84f2a44d2cda8e567d524ce43459688c1f753ba9
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
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 seperating 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_clean_rm_link($link)
148 if (file_exists(VAR_LINKS
. $p . $link)) {
149 unlink(VAR_LINKS
. $p . $link);
151 $parse = VAR_LINKS
. $p;
153 while (file_exists($parse)
154 && ($scan = scandir($parse))
155 && count($scan) == 2 // '.' and '..' folders => empty.
156 && basename($parse) != basename(VAR_LINKS
)) {
158 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
162 function jirafeau_clean_rm_file($hash)
165 $f = VAR_FILES
. $p . $hash;
166 if (file_exists($f) && is_file($f)) {
169 if (file_exists($f . '_count') && is_file($f . '_count')) {
170 unlink($f . '_count');
172 $parse = VAR_FILES
. $p;
174 while (file_exists($parse)
175 && ($scan = scandir($parse))
176 && count($scan) == 2 // '.' and '..' folders => empty.
177 && basename($parse) != basename(VAR_FILES
)) {
179 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
184 * transforms a php.ini string representing a value in an integer
185 * @param $value the value from php.ini
186 * @returns an integer for this value
188 function jirafeau_ini_to_bytes($value)
190 $modifier = substr($value, -1);
191 $bytes = substr($value, 0, -1);
192 switch (strtoupper($modifier)) {
208 * gets the maximum upload size according to php.ini
209 * @returns the maximum upload size in bytes
211 function jirafeau_get_max_upload_size_bytes()
213 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
214 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
218 * gets the maximum upload size according to php.ini
219 * @returns the maximum upload size string
221 function jirafeau_get_max_upload_size()
223 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
227 * gets a string explaining the error
228 * @param $code the error code
229 * @returns a string explaining the error
231 function jirafeau_upload_errstr($code)
234 case UPLOAD_ERR_INI_SIZE
:
235 case UPLOAD_ERR_FORM_SIZE
:
236 return t('Your file exceeds the maximum authorized file size. ');
238 case UPLOAD_ERR_PARTIAL
:
239 case UPLOAD_ERR_NO_FILE
:
241 t('Your file was not uploaded correctly. You may succeed in retrying. ');
243 case UPLOAD_ERR_NO_TMP_DIR
:
244 case UPLOAD_ERR_CANT_WRITE
:
245 case UPLOAD_ERR_EXTENSION
:
246 return t('Internal error. You may not succeed in retrying. ');
248 return t('Unknown error. ');
251 /** Remove link and it's file
252 * @param $link the link's name (hash)
255 function jirafeau_delete_link($link)
257 $l = jirafeau_get_link($link);
262 jirafeau_clean_rm_link($link);
268 if (file_exists(VAR_FILES
. $p . $hash. '_count')) {
269 $content = file(VAR_FILES
. $p . $hash. '_count');
270 $counter = trim($content[0]);
275 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
276 fwrite($handle, $counter);
281 jirafeau_clean_rm_file($hash);
286 * Delete a file and it's links.
288 function jirafeau_delete_file($hash)
291 /* Get all links files. */
292 $stack = array(VAR_LINKS
);
293 while (($d = array_shift($stack)) && $d != null) {
296 foreach ($dir as $node) {
297 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
298 preg_match('/\.tmp/i', "$node")) {
302 if (is_dir($d . $node)) {
303 /* Push new found directory. */
304 $stack[] = $d . $node . '/';
305 } elseif (is_file($d . $node)) {
306 /* Read link informations. */
307 $l = jirafeau_get_link(basename($node));
311 if ($l['hash'] == $hash) {
313 jirafeau_delete_link($node);
318 jirafeau_clean_rm_file($hash);
323 /** hash file's content
324 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
325 * @param $file_path file to hash
326 * @returns hash string
328 function jirafeau_hash_file($method, $file_path)
332 return jirafeau_md5_outside($file_path);
334 return md5_file($file_path);
336 return jirafeau_gen_random(32);
338 return md5_file($file_path);
341 /** hash part of file: start, end and size.
342 * This is a partial file hash, faster but weaker.
343 * @param $file_path file to hash
344 * @returns hash string
346 function jirafeau_md5_outside($file_path)
349 $handle = fopen($file_path, "r");
350 if ($handle === false) {
353 $size = filesize($file_path);
354 if ($size === false) {
357 $first = fread($handle, 64);
358 if ($first === false) {
361 if (fseek($handle, $size < 64 ?
0 : $size - 64) == -1) {
364 $last = fread($handle, 64);
365 if ($last === false) {
368 $out = md5($first . $last . $size);
375 * handles an uploaded file
376 * @param $file the file struct given by $_FILE[]
377 * @param $one_time_download is the file a one time download ?
378 * @param $key if not empty, protect the file with this key
379 * @param $time the time of validity of the file
380 * @param $ip uploader's ip
381 * @param $crypt boolean asking to crypt or not
382 * @param $link_name_length size of the link name
383 * @returns an array containing some information
384 * 'error' => information on possible errors
385 * 'link' => the link name of the uploaded file
386 * 'delete_link' => the link code to delete file
388 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
390 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
393 array('has_error' => true,
394 'why' => jirafeau_upload_errstr($file['error'])),
396 'delete_link' => ''));
399 /* array representing no error */
400 $noerr = array('has_error' => false, 'why' => '');
402 /* Crypt file if option is enabled. */
405 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
406 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
408 if ($crypt == true && extension_loaded('mcrypt') == true) {
409 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
410 if (strlen($crypt_key) > 0) {
415 /* file informations */
416 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
417 $name = str_replace(NL
, '', trim($file['name']));
418 $mime_type = $file['type'];
419 $size = $file['size'];
421 /* does file already exist ? */
424 if (file_exists(VAR_FILES
. $p . $hash)) {
425 $rc = unlink($file['tmp_name']);
426 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
427 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $hash)) {
433 array('has_error' => true,
434 'why' => t('INTERNAL_ERROR_DEL')),
436 'delete_link' => ''));
439 /* Increment or create count file. */
441 if (file_exists(VAR_FILES
. $p . $hash . '_count')) {
442 $content = file(VAR_FILES
. $p . $hash. '_count');
443 $counter = trim($content[0]);
446 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
447 fwrite($handle, $counter);
450 /* Create delete code. */
451 $delete_link_code = jirafeau_gen_random(5);
453 /* hash password or empty. */
456 $password = md5($key);
459 /* create link file */
460 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
461 $handle = fopen($link_tmp_name, 'w');
463 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
464 NL
. $hash. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
465 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
467 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
468 $l = s2p("$hash_link");
469 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
470 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
471 if (file_exists($link_tmp_name)) {
472 unlink($link_tmp_name);
477 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
478 fwrite($handle, $counter);
481 jirafeau_clean_rm_file($hash_link);
485 array('has_error' => true,
486 'why' => t('Internal error during file creation. ')),
488 'delete_link' => '');
490 return array( 'error' => $noerr,
491 'link' => $hash_link,
492 'delete_link' => $delete_link_code,
493 'crypt_key' => $crypt_key);
497 * Tells if a mime-type is viewable in a browser
498 * @param $mime the mime type
499 * @returns a boolean telling if a mime type is viewable
501 function jirafeau_is_viewable($mime)
504 /* Actually, verify if mime-type is an image or a text. */
505 $viewable = array('image', 'text', 'video', 'audio');
506 $decomposed = explode('/', $mime);
507 return in_array($decomposed[0], $viewable);
512 // Error handling functions.
513 //! Global array that contains all registered errors.
514 $error_list = array();
517 * Adds an error to the list of errors.
518 * @param $title the error's title
519 * @param $description is a human-friendly description of the problem.
521 function add_error($title, $description)
524 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
528 * Informs whether any error has been registered yet.
529 * @return true if there are errors.
534 return !empty($error_list);
538 * Displays all the errors.
540 function show_errors()
544 echo '<div class="error">';
545 foreach ($error_list as $error) {
552 function check_errors($cfg)
554 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
555 && !($cfg['installation_done'] === true)) {
556 header('Location: install.php');
560 /* Checking for errors. */
561 if (!is_writable(VAR_FILES
)) {
562 add_error(t('FILE_DIR_W'), VAR_FILES
);
565 if (!is_writable(VAR_LINKS
)) {
566 add_error(t('LINK_DIR_W'), VAR_LINKS
);
569 if (!is_writable(VAR_ASYNC
)) {
570 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
573 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
574 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
577 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
578 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
583 * Read link informations
584 * @return array containing informations.
586 function jirafeau_get_link($hash)
589 $link = VAR_LINKS
. s2p("$hash") . $hash;
591 if (!file_exists($link)) {
596 $out['file_name'] = trim($c[0]);
597 $out['mime_type'] = trim($c[1]);
598 $out['file_size'] = trim($c[2]);
599 $out['key'] = trim($c[3], NL
);
600 $out['time'] = trim($c[4]);
601 $out['hash'] = trim($c[5]);
602 $out['onetime'] = trim($c[6]);
603 $out['upload_date'] = trim($c[7]);
604 $out['ip'] = trim($c[8]);
605 $out['link_code'] = trim($c[9]);
606 $out['crypted'] = trim($c[10]) == 'C';
612 * List files in admin interface.
614 function jirafeau_admin_list($name, $file_hash, $link_hash)
616 echo '<fieldset><legend>';
618 echo t('FILENAME') . ": " . jirafeau_escape($name);
620 if (!empty($file_hash)) {
621 echo t('FILE') . ": " . jirafeau_escape($file_hash);
623 if (!empty($link_hash)) {
624 echo t('LINK') . ": " . jirafeau_escape($link_hash);
626 if (empty($name) && empty($file_hash) && empty($link_hash)) {
630 echo '<table border="1" width="1100">';
632 echo '<th>' . t('FILENAME') . '</th>';
633 echo '<th>' . t('TYPE') . '</th>';
634 echo '<th>' . t('SIZE') . '</th>';
635 echo '<th>' . t('EXPIRE') . '</th>';
636 echo '<th>' . t('ONETIME') . '</th>';
637 echo '<th>' . t('UPLOAD_DATE') . '</th>';
638 echo '<th>' . t('ORIGIN') . '</th>';
639 echo '<th>' . t('ACTION') . '</th>';
642 /* Get all links files. */
643 $stack = array(VAR_LINKS
);
644 while (($d = array_shift($stack)) && $d != null) {
646 foreach ($dir as $node) {
647 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
648 preg_match('/\.tmp/i', "$node")) {
651 if (is_dir($d . $node)) {
652 /* Push new found directory. */
653 $stack[] = $d . $node . '/';
654 } elseif (is_file($d . $node)) {
655 /* Read link informations. */
656 $l = jirafeau_get_link($node);
662 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
665 if (!empty($file_hash) && $file_hash != $l['hash']) {
668 if (!empty($link_hash) && $link_hash != $node) {
671 /* Print link informations. */
674 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
675 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
677 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
678 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
679 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
681 if ($l['onetime'] == 'O') {
687 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
688 echo '<td>' . $l['ip'] . '</td>';
690 '<form method="post">' .
691 '<input type = "hidden" name = "action" value = "download"/>' .
692 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
693 jirafeau_admin_csrf_field() .
694 '<input type = "submit" value = "' . t('DL') . '" />' .
696 '<form method="post">' .
697 '<input type = "hidden" name = "action" value = "delete_link"/>' .
698 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
699 jirafeau_admin_csrf_field() .
700 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
702 '<form method="post">' .
703 '<input type = "hidden" name = "action" value = "delete_file"/>' .
704 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
705 jirafeau_admin_csrf_field() .
706 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
713 echo '</table></fieldset>';
717 * Clean expired files.
718 * @return number of cleaned files.
720 function jirafeau_admin_clean()
723 /* Get all links files. */
724 $stack = array(VAR_LINKS
);
725 while (($d = array_shift($stack)) && $d != null) {
728 foreach ($dir as $node) {
729 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
730 preg_match('/\.tmp/i', "$node")) {
734 if (is_dir($d . $node)) {
735 /* Push new found directory. */
736 $stack[] = $d . $node . '/';
737 } elseif (is_file($d . $node)) {
738 /* Read link informations. */
739 $l = jirafeau_get_link(basename($node));
743 $p = s2p($l['hash']);
744 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
745 !file_exists(VAR_FILES
. $p . $l['hash']) ||
// invalid
746 !file_exists(VAR_FILES
. $p . $l['hash'] . '_count')) { // invalid
747 jirafeau_delete_link($node);
758 * Clean old async transferts.
759 * @return number of cleaned files.
761 function jirafeau_admin_clean_async()
764 /* Get all links files. */
765 $stack = array(VAR_ASYNC
);
766 while (($d = array_shift($stack)) && $d != null) {
769 foreach ($dir as $node) {
770 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
771 preg_match('/\.tmp/i', "$node")) {
775 if (is_dir($d . $node)) {
776 /* Push new found directory. */
777 $stack[] = $d . $node . '/';
778 } elseif (is_file($d . $node)) {
779 /* Read async informations. */
780 $a = jirafeau_get_async_ref(basename($node));
784 /* Delete transferts older than 1 hour. */
785 if (time() - $a['last_edited'] > 3600) {
786 jirafeau_async_delete(basename($node));
795 * Read async transfert informations
796 * @return array containing informations.
798 function jirafeau_get_async_ref($ref)
801 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
803 if (!file_exists($refinfos)) {
807 $c = file($refinfos);
808 $out['file_name'] = trim($c[0]);
809 $out['mime_type'] = trim($c[1]);
810 $out['key'] = trim($c[2], NL
);
811 $out['time'] = trim($c[3]);
812 $out['onetime'] = trim($c[4]);
813 $out['ip'] = trim($c[5]);
814 $out['last_edited'] = trim($c[6]);
815 $out['next_code'] = trim($c[7]);
820 * Delete async transfert informations
822 function jirafeau_async_delete($ref)
825 if (file_exists(VAR_ASYNC
. $p . $ref)) {
826 unlink(VAR_ASYNC
. $p . $ref);
828 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
829 unlink(VAR_ASYNC
. $p . $ref . '_data');
831 $parse = VAR_ASYNC
. $p;
833 while (file_exists($parse)
834 && ($scan = scandir($parse))
835 && count($scan) == 2 // '.' and '..' folders => empty.
836 && basename($parse) != basename(VAR_ASYNC
)) {
838 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
843 * Init a new asynchronous upload.
844 * @param $finename Name of the file to send
845 * @param $one_time One time upload parameter
846 * @param $key eventual password (or blank)
847 * @param $time time limit
848 * @param $ip ip address of the client
849 * @return a string containing a temporary reference followed by a code or the string 'Error'
851 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
855 /* Create temporary folder. */
858 $code = jirafeau_gen_random(4);
860 $ref = jirafeau_gen_random(32);
861 $p = VAR_ASYNC
. s2p($ref);
862 } while (file_exists($p));
863 @mkdir
($p, 0755, true);
864 if (!file_exists($p)) {
869 /* md5 password or empty */
872 $password = md5($key);
875 /* Store informations. */
877 $handle = fopen($p, 'w');
879 str_replace(NL
, '', trim($filename)) . NL
.
880 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
881 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
882 time() . NL
. $code . NL
);
885 return $ref . NL
. $code ;
889 * Append a piece of file on the asynchronous upload.
890 * @param $ref asynchronous upload reference
891 * @param $file piece of data
892 * @param $code client code for this operation
893 * @param $max_file_size maximum allowed file size
894 * @return a string containing a next code to use or the string "Error"
896 function jirafeau_async_push($ref, $data, $code, $max_file_size)
898 /* Get async infos. */
899 $a = jirafeau_get_async_ref($ref);
901 /* Check some errors. */
903 ||
$a['next_code'] != "$code"
904 ||
empty($data['tmp_name'])
905 ||
!is_uploaded_file($data['tmp_name'])) {
912 $r_path = $data['tmp_name'];
913 $w_path = VAR_ASYNC
. $p . $ref . '_data';
915 /* Check that file size is not above upload limit. */
916 if ($max_file_size > 0 &&
917 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
918 jirafeau_async_delete($ref);
922 /* Concatenate data. */
923 $r = fopen($r_path, 'r');
924 $w = fopen($w_path, 'a');
926 if (fwrite($w, fread($r, 1024)) === false) {
929 jirafeau_async_delete($ref);
937 /* Update async file. */
938 $code = jirafeau_gen_random(4);
939 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
941 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
942 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
943 time() . NL
. $code . NL
);
949 * Finalyze an asynchronous upload.
950 * @param $ref asynchronous upload reference
951 * @param $code client code for this operation
952 * @param $crypt boolean asking to crypt or not
953 * @param $link_name_length link name length
954 * @return a string containing the download reference followed by a delete code or the string 'Error'
956 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
958 /* Get async infos. */
959 $a = jirafeau_get_async_ref($ref);
961 ||
$a['next_code'] != "$code") {
965 /* Generate link infos. */
966 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
967 if (!file_exists($p)) {
973 if ($crypt == true && extension_loaded('mcrypt') == true) {
974 $crypt_key = jirafeau_encrypt_file($p, $p);
975 if (strlen($crypt_key) > 0) {
980 $hash = jirafeau_hash_file($file_hash_method, $p);
981 $size = filesize($p);
983 $delete_link_code = jirafeau_gen_random(5);
985 /* File already exist ? */
986 if (!file_exists(VAR_FILES
. $np)) {
987 @mkdir
(VAR_FILES
. $np, 0755, true);
989 if (!file_exists(VAR_FILES
. $np . $hash)) {
990 rename($p, VAR_FILES
. $np . $hash);
993 /* Increment or create count file. */
995 if (file_exists(VAR_FILES
. $np . $hash . '_count')) {
996 $content = file(VAR_FILES
. $np . $hash. '_count');
997 $counter = trim($content[0]);
1000 $handle = fopen(VAR_FILES
. $np . $hash. '_count', 'w');
1001 fwrite($handle, $counter);
1005 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
1006 $handle = fopen($link_tmp_name, 'w');
1008 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
1009 $a['key'] . NL
. $a['time'] . NL
. $hash . NL
. $a['onetime'] . NL
.
1010 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
1012 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1013 $l = s2p("$hash_link");
1014 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
1015 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
1019 /* Clean async upload. */
1020 jirafeau_async_delete($ref);
1021 return $hash_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
1024 function jirafeau_crypt_create_iv($base, $size)
1027 while (strlen($iv) < $size) {
1030 $iv = substr($iv, 0, $size);
1035 * Crypt file and returns decrypt key.
1036 * @param $fp_src file path to the file to crypt.
1037 * @param $fp_dst file path to the file to write crypted file (could be the same).
1038 * @return decrypt key composed of the key and the iv separated by a point ('.')
1040 function jirafeau_encrypt_file($fp_src, $fp_dst)
1042 $fs = filesize($fp_src);
1043 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
1047 /* Prepare module. */
1048 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1050 $crypt_key = jirafeau_gen_random(10);
1051 $hash_key = md5($crypt_key);
1052 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1054 mcrypt_generic_init($m, $hash_key, $iv);
1056 $r = fopen($fp_src, 'r');
1057 $w = fopen($fp_dst, 'c');
1059 $enc = mcrypt_generic($m, fread($r, 1024));
1060 if (fwrite($w, $enc) === false) {
1067 mcrypt_generic_deinit($m);
1068 mcrypt_module_close($m);
1074 * @param $fp_src file path to the file to decrypt.
1075 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1076 * @param $k string composed of the key and the iv separated by a point ('.')
1077 * @return key used to decrypt. a string of length 0 is returned if failed.
1079 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1081 $fs = filesize($fp_src);
1082 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1087 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1088 /* Extract key and iv. */
1090 $hash_key = md5($crypt_key);
1091 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1093 $r = fopen($fp_src, 'r');
1094 $w = fopen($fp_dst, 'c');
1096 $dec = mdecrypt_generic($m, fread($r, 1024));
1097 if (fwrite($w, $dec) === false) {
1104 mcrypt_generic_deinit($m);
1105 mcrypt_module_close($m);
1110 * Check if Jirafeau is password protected for visitors.
1111 * @return true if Jirafeau is password protected, false otherwise.
1113 function jirafeau_has_upload_password($cfg)
1115 return count($cfg['upload_password']) > 0;
1119 * Challenge password for a visitor.
1120 * @param $password password to be challenged
1121 * @return true if password is valid, false otherwise.
1123 function jirafeau_challenge_upload_password($cfg, $password)
1125 if (!jirafeau_has_upload_password($cfg)) {
1128 foreach ($cfg['upload_password'] as $p) {
1129 if ($password == $p) {
1137 * Test if the given IP is whitelisted by the given list.
1139 * @param $allowedIpList array of allowed IPs
1140 * @param $challengedIp IP to be challenged
1141 * @return true if IP is authorized, false otherwise.
1143 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1145 foreach ($allowedIpList as $i) {
1146 if ($i == $challengedIp) {
1149 // CIDR test for IPv4 only.
1150 if (strpos($i, '/') !== false) {
1151 list($subnet, $mask) = explode('/', $i);
1152 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1161 * Check if Jirafeau has a restriction on the IP address for uploading.
1162 * @return true if uploading is IP restricted, false otherwise.
1164 function jirafeau_upload_has_ip_restriction($cfg) {
1165 return count($cfg['upload_ip']) > 0;
1169 * Test if visitor's IP is authorized to upload at all.
1171 * @param $cfg configuration
1172 * @param $challengedIp IP to be challenged
1173 * @return true if IP is authorized, false otherwise.
1175 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1177 // If no IP address have been listed, allow upload from any IP
1178 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1181 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1185 * Test if visitor's IP is authorized to upload without a password.
1187 * @param $cfg configuration
1188 * @param $challengedIp IP to be challenged
1189 * @return true if IP is authorized, false otherwise.
1191 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1193 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1197 * Test if visitor's IP is authorized or password is supplied and authorized
1198 * @param $ip IP to be challenged
1199 * @param $password password to be challenged
1200 * @return true if access is valid, false otherwise.
1202 function jirafeau_challenge_upload ($cfg, $ip, $password)
1204 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1205 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1206 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1209 /** Tell if we have some HTTP headers generated by a proxy */
1210 function has_http_forwarded()
1213 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1214 !empty($_SERVER['http_X_forwarded_for']);
1218 * Generate IP list from HTTP headers generated by a proxy
1219 * @return array of IP strings
1221 function get_ip_list_http_forwarded()
1224 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1225 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1229 foreach ($l as $ip) {
1230 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1233 if (!empty($_SERVER['http_X_forwarded_for'])) {
1234 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1235 foreach ($l as $ip) {
1236 // Separate IP from port
1237 $ipa = explode(':', $ip);
1238 if ($ipa === false) {
1242 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1249 * Get the ip address of the client from REMOTE_ADDR
1250 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1251 * @returns the client ip address
1253 function get_ip_address($cfg)
1255 $remote = $_SERVER['REMOTE_ADDR'];
1256 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1260 $ip_list = get_ip_list_http_forwarded();
1261 if (count($ip_list) == 0) {
1265 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1266 if ($remote != $proxy_ip) {
1269 // Take the last IP (the one which has been set by the defined proxy).
1270 return end($ip_list);
1276 * Convert hexadecimal string to base64
1278 function hex_to_base64($hex)
1281 foreach (str_split($hex, 2) as $pair) {
1282 $b .= chr(hexdec($pair));
1284 return base64_encode($b);
1288 * Replace markers in templates.
1290 * Available markers have the scheme "###MARKERNAME###".
1292 * @param $content string Template text with markers
1293 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1294 * @return Template with replaced markers
1296 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1299 '/###ORGANISATION###/',
1300 '/###CONTACTPERSON###/',
1303 $replacements = array(
1304 $GLOBALS['cfg']['organisation'],
1305 $GLOBALS['cfg']['contactperson'],
1306 $GLOBALS['cfg']['web_root']
1308 $content = preg_replace($patterns, $replacements, $content);
1310 if (true === $htmllinebreaks) {
1311 $content = nl2br($content);
1317 function jirafeau_escape($string)
1319 return htmlspecialchars($string, ENT_QUOTES
);
1322 function jirafeau_admin_session_start()
1324 $_SESSION['admin_auth'] = true;
1325 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1328 function jirafeau_admin_session_end()
1330 $_SESSION = array();
1334 function jirafeau_admin_session_logged()
1336 return isset($_SESSION['admin_auth']) &&
1337 isset($_SESSION['admin_csrf']) &&
1338 isset($_POST['admin_csrf']) &&
1339 $_SESSION['admin_auth'] === true &&
1340 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1343 function jirafeau_admin_csrf_field()
1345 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1348 function jirafeau_dir_size($dir)
1351 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT
) as $entry) {
1352 $size +
= is_file($entry) ?
filesize($entry) : jirafeau_dir_size($entry);
patrick-canterino.de