]>
git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
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 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)) {
212 * gets the maximum upload size according to php.ini
213 * @returns the maximum upload size in bytes
215 function jirafeau_get_max_upload_size_bytes()
218 jirafeau_ini_to_bytes(ini_get('post_max_size')),
219 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
224 * gets the maximum upload size according to php.ini
225 * @returns the maximum upload size string
227 function jirafeau_get_max_upload_size()
229 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
233 * gets a string explaining the error
234 * @param $code the error code
235 * @returns a string explaining the error
237 function jirafeau_upload_errstr($code)
240 case UPLOAD_ERR_INI_SIZE
:
241 case UPLOAD_ERR_FORM_SIZE
:
242 return t('Your file exceeds the maximum authorized file size. ');
244 case UPLOAD_ERR_PARTIAL
:
245 case UPLOAD_ERR_NO_FILE
:
247 t('Your file was not uploaded correctly. You may succeed in retrying. ');
249 case UPLOAD_ERR_NO_TMP_DIR
:
250 case UPLOAD_ERR_CANT_WRITE
:
251 case UPLOAD_ERR_EXTENSION
:
252 return t('Internal error. You may not succeed in retrying. ');
254 return t('Unknown error. ');
257 /** Remove link and it's file
258 * @param $link the link's name (hash)
261 function jirafeau_delete_link($link)
263 $l = jirafeau_get_link($link);
268 jirafeau_clean_rm_link($link);
274 if (file_exists(VAR_FILES
. $p . $hash. '_count')) {
275 $content = file(VAR_FILES
. $p . $hash. '_count');
276 $counter = trim($content[0]);
281 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
282 fwrite($handle, $counter);
287 jirafeau_clean_rm_file($hash);
292 * Delete a file and it's links.
294 function jirafeau_delete_file($hash)
297 /* Get all links files. */
298 $stack = array(VAR_LINKS
);
299 while (($d = array_shift($stack)) && $d != null) {
302 foreach ($dir as $node) {
303 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
304 preg_match('/\.tmp/i', "$node")) {
308 if (is_dir($d . $node)) {
309 /* Push new found directory. */
310 $stack[] = $d . $node . '/';
311 } elseif (is_file($d . $node)) {
312 /* Read link informations. */
313 $l = jirafeau_get_link(basename($node));
317 if ($l['hash'] == $hash) {
319 jirafeau_delete_link($node);
324 jirafeau_clean_rm_file($hash);
329 /** hash file's content
330 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
331 * @param $file_path file to hash
332 * @returns hash string
334 function jirafeau_hash_file($method, $file_path)
338 return jirafeau_md5_outside($file_path);
340 return md5_file($file_path);
342 return jirafeau_gen_random(32);
344 return md5_file($file_path);
347 /** hash part of file: start, end and size.
348 * This is a partial file hash, faster but weaker.
349 * @param $file_path file to hash
350 * @returns hash string
352 function jirafeau_md5_outside($file_path)
355 $handle = fopen($file_path, "r");
356 if ($handle === false) {
359 $size = filesize($file_path);
360 if ($size === false) {
363 $first = fread($handle, 64);
364 if ($first === false) {
367 if (fseek($handle, $size < 64 ?
0 : $size - 64) == -1) {
370 $last = fread($handle, 64);
371 if ($last === false) {
374 $out = md5($first . $last . $size);
381 * handles an uploaded file
382 * @param $file the file struct given by $_FILE[]
383 * @param $one_time_download is the file a one time download ?
384 * @param $key if not empty, protect the file with this key
385 * @param $time the time of validity of the file
386 * @param $ip uploader's ip
387 * @param $crypt boolean asking to crypt or not
388 * @param $link_name_length size of the link name
389 * @returns an array containing some information
390 * 'error' => information on possible errors
391 * 'link' => the link name of the uploaded file
392 * 'delete_link' => the link code to delete file
394 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
396 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
399 array('has_error' => true,
400 'why' => jirafeau_upload_errstr($file['error'])),
402 'delete_link' => ''));
405 /* array representing no error */
406 $noerr = array('has_error' => false, 'why' => '');
408 /* Crypt file if option is enabled. */
411 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
412 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
414 if ($crypt == true && extension_loaded('mcrypt') == true) {
415 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
416 if (strlen($crypt_key) > 0) {
421 /* file informations */
422 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
423 $name = str_replace(NL
, '', trim($file['name']));
424 $mime_type = $file['type'];
425 $size = $file['size'];
427 /* does file already exist ? */
430 if (file_exists(VAR_FILES
. $p . $hash)) {
431 $rc = unlink($file['tmp_name']);
432 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
433 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $hash)) {
439 array('has_error' => true,
440 'why' => t('INTERNAL_ERROR_DEL')),
442 'delete_link' => ''));
445 /* Increment or create count file. */
447 if (file_exists(VAR_FILES
. $p . $hash . '_count')) {
448 $content = file(VAR_FILES
. $p . $hash. '_count');
449 $counter = trim($content[0]);
452 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
453 fwrite($handle, $counter);
456 /* Create delete code. */
457 $delete_link_code = jirafeau_gen_random(5);
459 /* hash password or empty. */
462 $password = md5($key);
465 /* create link file */
466 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
467 $handle = fopen($link_tmp_name, 'w');
470 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
471 NL
. $hash. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
472 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O')
475 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
476 $l = s2p("$hash_link");
477 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
478 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
479 if (file_exists($link_tmp_name)) {
480 unlink($link_tmp_name);
485 $handle = fopen(VAR_FILES
. $p . $hash. '_count', 'w');
486 fwrite($handle, $counter);
489 jirafeau_clean_rm_file($hash_link);
493 array('has_error' => true,
494 'why' => t('Internal error during file creation. ')),
496 'delete_link' => '');
498 return array( 'error' => $noerr,
499 'link' => $hash_link,
500 'delete_link' => $delete_link_code,
501 'crypt_key' => $crypt_key);
505 * Tells if a mime-type is viewable in a browser
506 * @param $mime the mime type
507 * @returns a boolean telling if a mime type is viewable
509 function jirafeau_is_viewable($mime)
512 /* Actually, verify if mime-type is an image or a text. */
513 $viewable = array('image', 'text', 'video', 'audio');
514 $decomposed = explode('/', $mime);
515 return in_array($decomposed[0], $viewable);
520 // Error handling functions.
521 //! Global array that contains all registered errors.
522 $error_list = array();
525 * Adds an error to the list of errors.
526 * @param $title the error's title
527 * @param $description is a human-friendly description of the problem.
529 function add_error($title, $description)
532 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
536 * Informs whether any error has been registered yet.
537 * @return true if there are errors.
542 return !empty($error_list);
546 * Displays all the errors.
548 function show_errors()
552 echo '<div class="error">';
553 foreach ($error_list as $error) {
560 function check_errors($cfg)
562 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
563 && !($cfg['installation_done'] === true)) {
564 header('Location: install.php');
568 /* Checking for errors. */
569 if (!is_writable(VAR_FILES
)) {
570 add_error(t('FILE_DIR_W'), VAR_FILES
);
573 if (!is_writable(VAR_LINKS
)) {
574 add_error(t('LINK_DIR_W'), VAR_LINKS
);
577 if (!is_writable(VAR_ASYNC
)) {
578 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
581 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
582 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
585 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
586 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
591 * Read link informations
592 * @return array containing informations.
594 function jirafeau_get_link($hash)
597 $link = VAR_LINKS
. s2p("$hash") . $hash;
599 if (!file_exists($link)) {
604 $out['file_name'] = trim($c[0]);
605 $out['mime_type'] = trim($c[1]);
606 $out['file_size'] = trim($c[2]);
607 $out['key'] = trim($c[3], NL
);
608 $out['time'] = trim($c[4]);
609 $out['hash'] = trim($c[5]);
610 $out['onetime'] = trim($c[6]);
611 $out['upload_date'] = trim($c[7]);
612 $out['ip'] = trim($c[8]);
613 $out['link_code'] = trim($c[9]);
614 $out['crypted'] = trim($c[10]) == 'C';
620 * List files in admin interface.
622 function jirafeau_admin_list($name, $file_hash, $link_hash)
624 echo '<fieldset><legend>';
626 echo t('FILENAME') . ": " . jirafeau_escape($name);
628 if (!empty($file_hash)) {
629 echo t('FILE') . ": " . jirafeau_escape($file_hash);
631 if (!empty($link_hash)) {
632 echo t('LINK') . ": " . jirafeau_escape($link_hash);
634 if (empty($name) && empty($file_hash) && empty($link_hash)) {
641 echo '<th>' . t('ACTION') . '</th>';
644 /* Get all links files. */
645 $stack = array(VAR_LINKS
);
646 while (($d = array_shift($stack)) && $d != null) {
648 foreach ($dir as $node) {
649 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
650 preg_match('/\.tmp/i', "$node")) {
653 if (is_dir($d . $node)) {
654 /* Push new found directory. */
655 $stack[] = $d . $node . '/';
656 } elseif (is_file($d . $node)) {
657 /* Read link informations. */
658 $l = jirafeau_get_link($node);
664 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
667 if (!empty($file_hash) && $file_hash != $l['hash']) {
670 if (!empty($link_hash) && $link_hash != $node) {
673 /* Print link informations. */
676 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
677 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
678 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
679 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
680 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
681 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ?
'Yes' : 'No') . '<br/>';
682 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
683 if (strlen($l['ip']) > 0) {
684 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
687 echo '<form method="post">' .
688 '<input type = "hidden" name = "action" value = "download"/>' .
689 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
690 jirafeau_admin_csrf_field() .
691 '<input type = "submit" value = "' . t('DL') . '" />' .
693 '<form method="post">' .
694 '<input type = "hidden" name = "action" value = "delete_link"/>' .
695 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
696 jirafeau_admin_csrf_field() .
697 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
699 '<form method="post">' .
700 '<input type = "hidden" name = "action" value = "delete_file"/>' .
701 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
702 jirafeau_admin_csrf_field() .
703 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
710 echo '</table></fieldset>';
714 * Clean expired files.
715 * @return number of cleaned files.
717 function jirafeau_admin_clean()
720 /* Get all links files. */
721 $stack = array(VAR_LINKS
);
722 while (($d = array_shift($stack)) && $d != null) {
725 foreach ($dir as $node) {
726 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
727 preg_match('/\.tmp/i', "$node")) {
731 if (is_dir($d . $node)) {
732 /* Push new found directory. */
733 $stack[] = $d . $node . '/';
734 } elseif (is_file($d . $node)) {
735 /* Read link informations. */
736 $l = jirafeau_get_link(basename($node));
740 $p = s2p($l['hash']);
741 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
742 !file_exists(VAR_FILES
. $p . $l['hash']) ||
// invalid
743 !file_exists(VAR_FILES
. $p . $l['hash'] . '_count')) { // invalid
744 jirafeau_delete_link($node);
755 * Clean old async transferts.
756 * @return number of cleaned files.
758 function jirafeau_admin_clean_async()
761 /* Get all links files. */
762 $stack = array(VAR_ASYNC
);
763 while (($d = array_shift($stack)) && $d != null) {
766 foreach ($dir as $node) {
767 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
768 preg_match('/\.tmp/i', "$node")) {
772 if (is_dir($d . $node)) {
773 /* Push new found directory. */
774 $stack[] = $d . $node . '/';
775 } elseif (is_file($d . $node)) {
776 /* Read async informations. */
777 $a = jirafeau_get_async_ref(basename($node));
781 /* Delete transferts older than 1 hour. */
782 if (time() - $a['last_edited'] > 3600) {
783 jirafeau_async_delete(basename($node));
792 * Read async transfert informations
793 * @return array containing informations.
795 function jirafeau_get_async_ref($ref)
798 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
800 if (!file_exists($refinfos)) {
804 $c = file($refinfos);
805 $out['file_name'] = trim($c[0]);
806 $out['mime_type'] = trim($c[1]);
807 $out['key'] = trim($c[2], NL
);
808 $out['time'] = trim($c[3]);
809 $out['onetime'] = trim($c[4]);
810 $out['ip'] = trim($c[5]);
811 $out['last_edited'] = trim($c[6]);
812 $out['next_code'] = trim($c[7]);
817 * Delete async transfert informations
819 function jirafeau_async_delete($ref)
822 if (file_exists(VAR_ASYNC
. $p . $ref)) {
823 unlink(VAR_ASYNC
. $p . $ref);
825 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
826 unlink(VAR_ASYNC
. $p . $ref . '_data');
828 $parse = VAR_ASYNC
. $p;
830 while (file_exists($parse)
831 && ($scan = scandir($parse))
832 && count($scan) == 2 // '.' and '..' folders => empty.
833 && basename($parse) != basename(VAR_ASYNC
)) {
835 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
840 * Init a new asynchronous upload.
841 * @param $finename Name of the file to send
842 * @param $one_time One time upload parameter
843 * @param $key eventual password (or blank)
844 * @param $time time limit
845 * @param $ip ip address of the client
846 * @return a string containing a temporary reference followed by a code or the string 'Error'
848 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
852 /* Create temporary folder. */
855 $code = jirafeau_gen_random(4);
857 $ref = jirafeau_gen_random(32);
858 $p = VAR_ASYNC
. s2p($ref);
859 } while (file_exists($p));
860 @mkdir
($p, 0755, true);
861 if (!file_exists($p)) {
866 /* touch empty data file */
867 $w_path = $p . $ref . '_data';
870 /* md5 password or empty */
873 $password = md5($key);
876 /* Store informations. */
878 $handle = fopen($p, 'w');
881 str_replace(NL
, '', trim($filename)) . NL
.
882 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
883 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
884 time() . NL
. $code . NL
888 return $ref . NL
. $code ;
892 * Append a piece of file on the asynchronous upload.
893 * @param $ref asynchronous upload reference
894 * @param $file piece of data
895 * @param $code client code for this operation
896 * @param $max_file_size maximum allowed file size
897 * @return a string containing a next code to use or the string "Error"
899 function jirafeau_async_push($ref, $data, $code, $max_file_size)
901 /* Get async infos. */
902 $a = jirafeau_get_async_ref($ref);
904 /* Check some errors. */
906 ||
$a['next_code'] != "$code"
907 ||
empty($data['tmp_name'])
908 ||
!is_uploaded_file($data['tmp_name'])) {
915 $r_path = $data['tmp_name'];
916 $w_path = VAR_ASYNC
. $p . $ref . '_data';
918 /* Check that file size is not above upload limit. */
919 if ($max_file_size > 0 &&
920 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
921 jirafeau_async_delete($ref);
925 /* Concatenate data. */
926 $r = fopen($r_path, 'r');
927 $w = fopen($w_path, 'a');
929 if (fwrite($w, fread($r, 1024)) === false) {
932 jirafeau_async_delete($ref);
940 /* Update async file. */
941 $code = jirafeau_gen_random(4);
942 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
945 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
946 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
947 time() . NL
. $code . NL
954 * Finalyze an asynchronous upload.
955 * @param $ref asynchronous upload reference
956 * @param $code client code for this operation
957 * @param $crypt boolean asking to crypt or not
958 * @param $link_name_length link name length
959 * @return a string containing the download reference followed by a delete code or the string 'Error'
961 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
963 /* Get async infos. */
964 $a = jirafeau_get_async_ref($ref);
966 ||
$a['next_code'] != "$code") {
970 /* Generate link infos. */
971 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
972 if (!file_exists($p)) {
978 if ($crypt == true && extension_loaded('mcrypt') == true) {
979 $crypt_key = jirafeau_encrypt_file($p, $p);
980 if (strlen($crypt_key) > 0) {
985 $hash = jirafeau_hash_file($file_hash_method, $p);
986 $size = filesize($p);
988 $delete_link_code = jirafeau_gen_random(5);
990 /* File already exist ? */
991 if (!file_exists(VAR_FILES
. $np)) {
992 @mkdir
(VAR_FILES
. $np, 0755, true);
994 if (!file_exists(VAR_FILES
. $np . $hash)) {
995 rename($p, VAR_FILES
. $np . $hash);
998 /* Increment or create count file. */
1000 if (file_exists(VAR_FILES
. $np . $hash . '_count')) {
1001 $content = file(VAR_FILES
. $np . $hash. '_count');
1002 $counter = trim($content[0]);
1005 $handle = fopen(VAR_FILES
. $np . $hash. '_count', 'w');
1006 fwrite($handle, $counter);
1010 $link_tmp_name = VAR_LINKS
. $hash . rand(0, 10000) . '.tmp';
1011 $handle = fopen($link_tmp_name, 'w');
1014 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
1015 $a['key'] . NL
. $a['time'] . NL
. $hash . NL
. $a['onetime'] . NL
.
1016 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O')
1019 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1020 $l = s2p("$hash_link");
1021 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
1022 !rename($link_tmp_name, VAR_LINKS
. $l . $hash_link)) {
1026 /* Clean async upload. */
1027 jirafeau_async_delete($ref);
1028 return $hash_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
1031 function jirafeau_crypt_create_iv($base, $size)
1034 while (strlen($iv) < $size) {
1037 $iv = substr($iv, 0, $size);
1042 * Crypt file and returns decrypt key.
1043 * @param $fp_src file path to the file to crypt.
1044 * @param $fp_dst file path to the file to write crypted file (could be the same).
1045 * @return decrypt key composed of the key and the iv separated by a point ('.')
1047 function jirafeau_encrypt_file($fp_src, $fp_dst)
1049 $fs = filesize($fp_src);
1050 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
1054 /* Prepare module. */
1055 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1057 $crypt_key = jirafeau_gen_random(10);
1058 $hash_key = md5($crypt_key);
1059 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1061 mcrypt_generic_init($m, $hash_key, $iv);
1063 $r = fopen($fp_src, 'r');
1064 $w = fopen($fp_dst, 'c');
1066 $enc = mcrypt_generic($m, fread($r, 1024));
1067 if (fwrite($w, $enc) === false) {
1074 mcrypt_generic_deinit($m);
1075 mcrypt_module_close($m);
1081 * @param $fp_src file path to the file to decrypt.
1082 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1083 * @param $k string composed of the key and the iv separated by a point ('.')
1084 * @return key used to decrypt. a string of length 0 is returned if failed.
1086 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1088 $fs = filesize($fp_src);
1089 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1094 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1095 /* Extract key and iv. */
1097 $hash_key = md5($crypt_key);
1098 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1100 $r = fopen($fp_src, 'r');
1101 $w = fopen($fp_dst, 'c');
1103 $dec = mdecrypt_generic($m, fread($r, 1024));
1104 if (fwrite($w, $dec) === false) {
1111 mcrypt_generic_deinit($m);
1112 mcrypt_module_close($m);
1117 * Check if Jirafeau is password protected for visitors.
1118 * @return true if Jirafeau is password protected, false otherwise.
1120 function jirafeau_has_upload_password($cfg)
1122 return count($cfg['upload_password']) > 0;
1126 * Challenge password for a visitor.
1127 * @param $password password to be challenged
1128 * @return true if password is valid, false otherwise.
1130 function jirafeau_challenge_upload_password($cfg, $password)
1132 if (!jirafeau_has_upload_password($cfg)) {
1135 foreach ($cfg['upload_password'] as $p) {
1136 if ($password == $p) {
1144 * Test if the given IP is whitelisted by the given list.
1146 * @param $allowedIpList array of allowed IPs
1147 * @param $challengedIp IP to be challenged
1148 * @return true if IP is authorized, false otherwise.
1150 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1152 foreach ($allowedIpList as $i) {
1153 if ($i == $challengedIp) {
1156 // CIDR test for IPv4 only.
1157 if (strpos($i, '/') !== false) {
1158 list($subnet, $mask) = explode('/', $i);
1159 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1168 * Check if Jirafeau has a restriction on the IP address for uploading.
1169 * @return true if uploading is IP restricted, false otherwise.
1171 function jirafeau_upload_has_ip_restriction($cfg)
1173 return count($cfg['upload_ip']) > 0;
1177 * Test if visitor's IP is authorized to upload at all.
1179 * @param $cfg configuration
1180 * @param $challengedIp IP to be challenged
1181 * @return true if IP is authorized, false otherwise.
1183 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1185 // If no IP address have been listed, allow upload from any IP
1186 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1189 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1193 * Test if visitor's IP is authorized to upload without a password.
1195 * @param $cfg configuration
1196 * @param $challengedIp IP to be challenged
1197 * @return true if IP is authorized, false otherwise.
1199 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1201 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1205 * Test if visitor's IP is authorized or password is supplied and authorized
1206 * @param $ip IP to be challenged
1207 * @param $password password to be challenged
1208 * @return true if access is valid, false otherwise.
1210 function jirafeau_challenge_upload($cfg, $ip, $password)
1212 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1213 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1214 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1217 /** Tell if we have some HTTP headers generated by a proxy */
1218 function has_http_forwarded()
1221 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1222 !empty($_SERVER['http_X_forwarded_for']);
1226 * Generate IP list from HTTP headers generated by a proxy
1227 * @return array of IP strings
1229 function get_ip_list_http_forwarded()
1232 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1233 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1237 foreach ($l as $ip) {
1238 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1241 if (!empty($_SERVER['http_X_forwarded_for'])) {
1242 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1243 foreach ($l as $ip) {
1244 // Separate IP from port
1245 $ipa = explode(':', $ip);
1246 if ($ipa === false) {
1250 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1257 * Get the ip address of the client from REMOTE_ADDR
1258 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1259 * @returns the client ip address
1261 function get_ip_address($cfg)
1263 $remote = $_SERVER['REMOTE_ADDR'];
1264 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1268 $ip_list = get_ip_list_http_forwarded();
1269 if (count($ip_list) == 0) {
1273 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1274 if ($remote != $proxy_ip) {
1277 // Take the last IP (the one which has been set by the defined proxy).
1278 return end($ip_list);
1284 * Convert hexadecimal string to base64
1286 function hex_to_base64($hex)
1289 foreach (str_split($hex, 2) as $pair) {
1290 $b .= chr(hexdec($pair));
1292 return base64_encode($b);
1296 * Replace markers in templates.
1298 * Available markers have the scheme "###MARKERNAME###".
1300 * @param $content string Template text with markers
1301 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1302 * @return Template with replaced markers
1304 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1307 '/###ORGANISATION###/',
1308 '/###CONTACTPERSON###/',
1311 $replacements = array(
1312 $GLOBALS['cfg']['organisation'],
1313 $GLOBALS['cfg']['contactperson'],
1314 $GLOBALS['cfg']['web_root']
1316 $content = preg_replace($patterns, $replacements, $content);
1318 if (true === $htmllinebreaks) {
1319 $content = nl2br($content);
1325 function jirafeau_escape($string)
1327 return htmlspecialchars($string, ENT_QUOTES
);
1330 function jirafeau_admin_session_start()
1332 $_SESSION['admin_auth'] = true;
1333 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1336 function jirafeau_admin_session_end()
1338 $_SESSION = array();
1342 function jirafeau_admin_session_logged()
1344 return isset($_SESSION['admin_auth']) &&
1345 isset($_SESSION['admin_csrf']) &&
1346 isset($_POST['admin_csrf']) &&
1347 $_SESSION['admin_auth'] === true &&
1348 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1351 function jirafeau_admin_csrf_field()
1353 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1356 function jirafeau_dir_size($dir)
1359 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT
) as $entry) {
1360 $size +
= is_file($entry) ?
filesize($entry) : jirafeau_dir_size($entry);
1365 function jirafeau_export_cfg($cfg)
1367 $content = '<?php' . NL
;
1368 $content .= '/* This file was generated by the install process. ' .
1369 'You can edit it. Please see config.original.php to understand the ' .
1370 'configuration items. */' . NL
;
1371 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1373 $fileWrite = file_put_contents(JIRAFEAU_CFG
, $content);
1375 if (false === $fileWrite) {
1376 jirafeau_fatal_error(t('Can not write local configuration file'));
1380 function jirafeau_mkdir($path)
1382 return !(!file_exists($path) && !@mkdir
($path, 0755));
1386 * Returns true whether the path is writable or we manage to make it
1387 * so, which essentially is the same thing.
1388 * @param $path is the file or directory to be tested.
1389 * @return true if $path is writable.
1391 function jirafeau_is_writable($path)
1393 /* "@" gets rid of error messages. */
1394 return is_writable($path) || @chmod
($path, 0777);
1397 function jirafeau_check_var_dir($path)
1399 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1400 $mkdir_str2 = t('MANUAL_CREATE');
1401 $write_str1 = t('DIR_NOT_W') . ':';
1402 $write_str2 = t('You should give the write permission to the web server on ' .
1404 $solution_str = t('HERE_SOLUTION') . ':';
1406 if (!jirafeau_mkdir($path) ||
!jirafeau_is_writable($path)) {
1407 return array('has_error' => true,
1408 'why' => $mkdir_str1 . '<br /><code>' .
1409 $path . '</code><br />' . $solution_str .
1410 '<br />' . $mkdir_str2);
1413 foreach (array('files', 'links', 'async') as $subdir) {
1414 $subpath = $path.$subdir;
1416 if (!jirafeau_mkdir($subpath) ||
!jirafeau_is_writable($subpath)) {
1417 return array('has_error' => true,
1418 'why' => $mkdir_str1 . '<br /><code>' .
1419 $subpath . '</code><br />' . $solution_str .
1420 '<br />' . $mkdir_str2);
1424 return array('has_error' => false, 'why' => '');
1427 function jirafeau_add_ending_slash($path)
1429 return $path . ((substr($path, -1) == '/') ?
'' : '/');
patrick-canterino.de